xref: /minix3/external/bsd/llvm/dist/llvm/lib/Support/CommandLine.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===-- CommandLine.cpp - Command line parser implementation --------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This class implements a command line argument processor that is useful when
11f4a2713aSLionel Sambuc // creating a tool.  It provides a simple, minimalistic interface that is easily
12f4a2713aSLionel Sambuc // extensible and supports nonlocal (library) command line options.
13f4a2713aSLionel Sambuc //
14f4a2713aSLionel Sambuc // Note that rather than trying to figure out what this code does, you could try
15f4a2713aSLionel Sambuc // reading the library documentation located in docs/CommandLine.html
16f4a2713aSLionel Sambuc //
17f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
18f4a2713aSLionel Sambuc 
19f4a2713aSLionel Sambuc #include "llvm/Support/CommandLine.h"
20*0a6a1f1dSLionel Sambuc #include "llvm-c/Support.h"
21f4a2713aSLionel Sambuc #include "llvm/ADT/ArrayRef.h"
22f4a2713aSLionel Sambuc #include "llvm/ADT/SmallPtrSet.h"
23f4a2713aSLionel Sambuc #include "llvm/ADT/SmallString.h"
24f4a2713aSLionel Sambuc #include "llvm/ADT/StringMap.h"
25f4a2713aSLionel Sambuc #include "llvm/ADT/Twine.h"
26f4a2713aSLionel Sambuc #include "llvm/Config/config.h"
27f4a2713aSLionel Sambuc #include "llvm/Support/ConvertUTF.h"
28f4a2713aSLionel Sambuc #include "llvm/Support/Debug.h"
29f4a2713aSLionel Sambuc #include "llvm/Support/ErrorHandling.h"
30f4a2713aSLionel Sambuc #include "llvm/Support/Host.h"
31f4a2713aSLionel Sambuc #include "llvm/Support/ManagedStatic.h"
32f4a2713aSLionel Sambuc #include "llvm/Support/MemoryBuffer.h"
33f4a2713aSLionel Sambuc #include "llvm/Support/Path.h"
34f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
35f4a2713aSLionel Sambuc #include <cerrno>
36f4a2713aSLionel Sambuc #include <cstdlib>
37f4a2713aSLionel Sambuc #include <map>
38*0a6a1f1dSLionel Sambuc #include <system_error>
39f4a2713aSLionel Sambuc using namespace llvm;
40f4a2713aSLionel Sambuc using namespace cl;
41f4a2713aSLionel Sambuc 
42*0a6a1f1dSLionel Sambuc #define DEBUG_TYPE "commandline"
43*0a6a1f1dSLionel Sambuc 
44f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
45f4a2713aSLionel Sambuc // Template instantiations and anchors.
46f4a2713aSLionel Sambuc //
47*0a6a1f1dSLionel Sambuc namespace llvm {
48*0a6a1f1dSLionel Sambuc namespace cl {
49f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class basic_parser<bool>);
50f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
51f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class basic_parser<int>);
52f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
53f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
54f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class basic_parser<double>);
55f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class basic_parser<float>);
56f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
57f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class basic_parser<char>);
58f4a2713aSLionel Sambuc 
59f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class opt<unsigned>);
60f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class opt<int>);
61f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class opt<std::string>);
62f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class opt<char>);
63f4a2713aSLionel Sambuc TEMPLATE_INSTANTIATION(class opt<bool>);
64*0a6a1f1dSLionel Sambuc }
65*0a6a1f1dSLionel Sambuc } // end namespace llvm::cl
66f4a2713aSLionel Sambuc 
67f4a2713aSLionel Sambuc // Pin the vtables to this file.
anchor()68f4a2713aSLionel Sambuc void GenericOptionValue::anchor() {}
anchor()69f4a2713aSLionel Sambuc void OptionValue<boolOrDefault>::anchor() {}
anchor()70f4a2713aSLionel Sambuc void OptionValue<std::string>::anchor() {}
anchor()71f4a2713aSLionel Sambuc void Option::anchor() {}
anchor()72f4a2713aSLionel Sambuc void basic_parser_impl::anchor() {}
anchor()73f4a2713aSLionel Sambuc void parser<bool>::anchor() {}
anchor()74f4a2713aSLionel Sambuc void parser<boolOrDefault>::anchor() {}
anchor()75f4a2713aSLionel Sambuc void parser<int>::anchor() {}
anchor()76f4a2713aSLionel Sambuc void parser<unsigned>::anchor() {}
anchor()77f4a2713aSLionel Sambuc void parser<unsigned long long>::anchor() {}
anchor()78f4a2713aSLionel Sambuc void parser<double>::anchor() {}
anchor()79f4a2713aSLionel Sambuc void parser<float>::anchor() {}
anchor()80f4a2713aSLionel Sambuc void parser<std::string>::anchor() {}
anchor()81f4a2713aSLionel Sambuc void parser<char>::anchor() {}
anchor()82f4a2713aSLionel Sambuc void StringSaver::anchor() {}
83f4a2713aSLionel Sambuc 
84f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
85f4a2713aSLionel Sambuc 
86f4a2713aSLionel Sambuc // Globals for name and overview of program.  Program name is not a string to
87f4a2713aSLionel Sambuc // avoid static ctor/dtor issues.
88f4a2713aSLionel Sambuc static char ProgramName[80] = "<premain>";
89*0a6a1f1dSLionel Sambuc static const char *ProgramOverview = nullptr;
90f4a2713aSLionel Sambuc 
91f4a2713aSLionel Sambuc // This collects additional help to be printed.
92f4a2713aSLionel Sambuc static ManagedStatic<std::vector<const char *>> MoreHelp;
93f4a2713aSLionel Sambuc 
extrahelp(const char * Help)94*0a6a1f1dSLionel Sambuc extrahelp::extrahelp(const char *Help) : morehelp(Help) {
95f4a2713aSLionel Sambuc   MoreHelp->push_back(Help);
96f4a2713aSLionel Sambuc }
97f4a2713aSLionel Sambuc 
98f4a2713aSLionel Sambuc static bool OptionListChanged = false;
99f4a2713aSLionel Sambuc 
100f4a2713aSLionel Sambuc // MarkOptionsChanged - Internal helper function.
MarkOptionsChanged()101*0a6a1f1dSLionel Sambuc void cl::MarkOptionsChanged() { OptionListChanged = true; }
102f4a2713aSLionel Sambuc 
103f4a2713aSLionel Sambuc /// RegisteredOptionList - This is the list of the command line options that
104f4a2713aSLionel Sambuc /// have statically constructed themselves.
105*0a6a1f1dSLionel Sambuc static Option *RegisteredOptionList = nullptr;
106f4a2713aSLionel Sambuc 
addArgument()107f4a2713aSLionel Sambuc void Option::addArgument() {
108*0a6a1f1dSLionel Sambuc   assert(!NextRegistered && "argument multiply registered!");
109f4a2713aSLionel Sambuc 
110f4a2713aSLionel Sambuc   NextRegistered = RegisteredOptionList;
111f4a2713aSLionel Sambuc   RegisteredOptionList = this;
112f4a2713aSLionel Sambuc   MarkOptionsChanged();
113f4a2713aSLionel Sambuc }
114f4a2713aSLionel Sambuc 
removeArgument()115*0a6a1f1dSLionel Sambuc void Option::removeArgument() {
116*0a6a1f1dSLionel Sambuc   if (RegisteredOptionList == this) {
117*0a6a1f1dSLionel Sambuc     RegisteredOptionList = NextRegistered;
118*0a6a1f1dSLionel Sambuc     MarkOptionsChanged();
119*0a6a1f1dSLionel Sambuc     return;
120*0a6a1f1dSLionel Sambuc   }
121*0a6a1f1dSLionel Sambuc   Option *O = RegisteredOptionList;
122*0a6a1f1dSLionel Sambuc   for (; O->NextRegistered != this; O = O->NextRegistered)
123*0a6a1f1dSLionel Sambuc     ;
124*0a6a1f1dSLionel Sambuc   O->NextRegistered = NextRegistered;
125*0a6a1f1dSLionel Sambuc   MarkOptionsChanged();
126*0a6a1f1dSLionel Sambuc }
127*0a6a1f1dSLionel Sambuc 
128f4a2713aSLionel Sambuc // This collects the different option categories that have been registered.
129f4a2713aSLionel Sambuc typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
130f4a2713aSLionel Sambuc static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
131f4a2713aSLionel Sambuc 
132f4a2713aSLionel Sambuc // Initialise the general option category.
133f4a2713aSLionel Sambuc OptionCategory llvm::cl::GeneralCategory("General options");
134f4a2713aSLionel Sambuc 
registerCategory()135*0a6a1f1dSLionel Sambuc void OptionCategory::registerCategory() {
136*0a6a1f1dSLionel Sambuc   assert(std::count_if(RegisteredOptionCategories->begin(),
137*0a6a1f1dSLionel Sambuc                        RegisteredOptionCategories->end(),
138*0a6a1f1dSLionel Sambuc                        [this](const OptionCategory *Category) {
139*0a6a1f1dSLionel Sambuc                          return getName() == Category->getName();
140*0a6a1f1dSLionel Sambuc                        }) == 0 &&
141*0a6a1f1dSLionel Sambuc          "Duplicate option categories");
142*0a6a1f1dSLionel Sambuc 
143f4a2713aSLionel Sambuc   RegisteredOptionCategories->insert(this);
144f4a2713aSLionel Sambuc }
145f4a2713aSLionel Sambuc 
146f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
147f4a2713aSLionel Sambuc // Basic, shared command line option processing machinery.
148f4a2713aSLionel Sambuc //
149f4a2713aSLionel Sambuc 
150f4a2713aSLionel Sambuc /// GetOptionInfo - Scan the list of registered options, turning them into data
151f4a2713aSLionel Sambuc /// structures that are easier to handle.
GetOptionInfo(SmallVectorImpl<Option * > & PositionalOpts,SmallVectorImpl<Option * > & SinkOpts,StringMap<Option * > & OptionsMap)152f4a2713aSLionel Sambuc static void GetOptionInfo(SmallVectorImpl<Option *> &PositionalOpts,
153f4a2713aSLionel Sambuc                           SmallVectorImpl<Option *> &SinkOpts,
154f4a2713aSLionel Sambuc                           StringMap<Option *> &OptionsMap) {
155*0a6a1f1dSLionel Sambuc   bool HadErrors = false;
156f4a2713aSLionel Sambuc   SmallVector<const char *, 16> OptionNames;
157*0a6a1f1dSLionel Sambuc   Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
158f4a2713aSLionel Sambuc   for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
159f4a2713aSLionel Sambuc     // If this option wants to handle multiple option names, get the full set.
160f4a2713aSLionel Sambuc     // This handles enum options like "-O1 -O2" etc.
161f4a2713aSLionel Sambuc     O->getExtraOptionNames(OptionNames);
162f4a2713aSLionel Sambuc     if (O->ArgStr[0])
163f4a2713aSLionel Sambuc       OptionNames.push_back(O->ArgStr);
164f4a2713aSLionel Sambuc 
165f4a2713aSLionel Sambuc     // Handle named options.
166f4a2713aSLionel Sambuc     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
167f4a2713aSLionel Sambuc       // Add argument to the argument map!
168*0a6a1f1dSLionel Sambuc       if (!OptionsMap.insert(std::make_pair(OptionNames[i], O)).second) {
169*0a6a1f1dSLionel Sambuc         errs() << ProgramName << ": CommandLine Error: Option '"
170*0a6a1f1dSLionel Sambuc                << OptionNames[i] << "' registered more than once!\n";
171*0a6a1f1dSLionel Sambuc         HadErrors = true;
172f4a2713aSLionel Sambuc       }
173f4a2713aSLionel Sambuc     }
174f4a2713aSLionel Sambuc 
175f4a2713aSLionel Sambuc     OptionNames.clear();
176f4a2713aSLionel Sambuc 
177f4a2713aSLionel Sambuc     // Remember information about positional options.
178f4a2713aSLionel Sambuc     if (O->getFormattingFlag() == cl::Positional)
179f4a2713aSLionel Sambuc       PositionalOpts.push_back(O);
180f4a2713aSLionel Sambuc     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
181f4a2713aSLionel Sambuc       SinkOpts.push_back(O);
182f4a2713aSLionel Sambuc     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
183*0a6a1f1dSLionel Sambuc       if (CAOpt) {
184f4a2713aSLionel Sambuc         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
185*0a6a1f1dSLionel Sambuc         HadErrors = true;
186*0a6a1f1dSLionel Sambuc       }
187f4a2713aSLionel Sambuc       CAOpt = O;
188f4a2713aSLionel Sambuc     }
189f4a2713aSLionel Sambuc   }
190f4a2713aSLionel Sambuc 
191f4a2713aSLionel Sambuc   if (CAOpt)
192f4a2713aSLionel Sambuc     PositionalOpts.push_back(CAOpt);
193f4a2713aSLionel Sambuc 
194f4a2713aSLionel Sambuc   // Make sure that they are in order of registration not backwards.
195f4a2713aSLionel Sambuc   std::reverse(PositionalOpts.begin(), PositionalOpts.end());
196f4a2713aSLionel Sambuc 
197*0a6a1f1dSLionel Sambuc   // Fail hard if there were errors. These are strictly unrecoverable and
198*0a6a1f1dSLionel Sambuc   // indicate serious issues such as conflicting option names or an incorrectly
199*0a6a1f1dSLionel Sambuc   // linked LLVM distribution.
200*0a6a1f1dSLionel Sambuc   if (HadErrors)
201*0a6a1f1dSLionel Sambuc     report_fatal_error("inconsistency in registered CommandLine options");
202*0a6a1f1dSLionel Sambuc }
203f4a2713aSLionel Sambuc 
204f4a2713aSLionel Sambuc /// LookupOption - Lookup the option specified by the specified option on the
205f4a2713aSLionel Sambuc /// command line.  If there is a value specified (after an equal sign) return
206f4a2713aSLionel Sambuc /// that as well.  This assumes that leading dashes have already been stripped.
LookupOption(StringRef & Arg,StringRef & Value,const StringMap<Option * > & OptionsMap)207f4a2713aSLionel Sambuc static Option *LookupOption(StringRef &Arg, StringRef &Value,
208f4a2713aSLionel Sambuc                             const StringMap<Option *> &OptionsMap) {
209f4a2713aSLionel Sambuc   // Reject all dashes.
210*0a6a1f1dSLionel Sambuc   if (Arg.empty())
211*0a6a1f1dSLionel Sambuc     return nullptr;
212f4a2713aSLionel Sambuc 
213f4a2713aSLionel Sambuc   size_t EqualPos = Arg.find('=');
214f4a2713aSLionel Sambuc 
215f4a2713aSLionel Sambuc   // If we have an equals sign, remember the value.
216f4a2713aSLionel Sambuc   if (EqualPos == StringRef::npos) {
217f4a2713aSLionel Sambuc     // Look up the option.
218f4a2713aSLionel Sambuc     StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
219*0a6a1f1dSLionel Sambuc     return I != OptionsMap.end() ? I->second : nullptr;
220f4a2713aSLionel Sambuc   }
221f4a2713aSLionel Sambuc 
222f4a2713aSLionel Sambuc   // If the argument before the = is a valid option name, we match.  If not,
223f4a2713aSLionel Sambuc   // return Arg unmolested.
224f4a2713aSLionel Sambuc   StringMap<Option *>::const_iterator I =
225f4a2713aSLionel Sambuc       OptionsMap.find(Arg.substr(0, EqualPos));
226*0a6a1f1dSLionel Sambuc   if (I == OptionsMap.end())
227*0a6a1f1dSLionel Sambuc     return nullptr;
228f4a2713aSLionel Sambuc 
229f4a2713aSLionel Sambuc   Value = Arg.substr(EqualPos + 1);
230f4a2713aSLionel Sambuc   Arg = Arg.substr(0, EqualPos);
231f4a2713aSLionel Sambuc   return I->second;
232f4a2713aSLionel Sambuc }
233f4a2713aSLionel Sambuc 
234f4a2713aSLionel Sambuc /// LookupNearestOption - Lookup the closest match to the option specified by
235f4a2713aSLionel Sambuc /// the specified option on the command line.  If there is a value specified
236f4a2713aSLionel Sambuc /// (after an equal sign) return that as well.  This assumes that leading dashes
237f4a2713aSLionel Sambuc /// have already been stripped.
LookupNearestOption(StringRef Arg,const StringMap<Option * > & OptionsMap,std::string & NearestString)238f4a2713aSLionel Sambuc static Option *LookupNearestOption(StringRef Arg,
239f4a2713aSLionel Sambuc                                    const StringMap<Option *> &OptionsMap,
240f4a2713aSLionel Sambuc                                    std::string &NearestString) {
241f4a2713aSLionel Sambuc   // Reject all dashes.
242*0a6a1f1dSLionel Sambuc   if (Arg.empty())
243*0a6a1f1dSLionel Sambuc     return nullptr;
244f4a2713aSLionel Sambuc 
245f4a2713aSLionel Sambuc   // Split on any equal sign.
246f4a2713aSLionel Sambuc   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
247f4a2713aSLionel Sambuc   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
248f4a2713aSLionel Sambuc   StringRef &RHS = SplitArg.second;
249f4a2713aSLionel Sambuc 
250f4a2713aSLionel Sambuc   // Find the closest match.
251*0a6a1f1dSLionel Sambuc   Option *Best = nullptr;
252f4a2713aSLionel Sambuc   unsigned BestDistance = 0;
253f4a2713aSLionel Sambuc   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
254*0a6a1f1dSLionel Sambuc                                            ie = OptionsMap.end();
255*0a6a1f1dSLionel Sambuc        it != ie; ++it) {
256f4a2713aSLionel Sambuc     Option *O = it->second;
257f4a2713aSLionel Sambuc     SmallVector<const char *, 16> OptionNames;
258f4a2713aSLionel Sambuc     O->getExtraOptionNames(OptionNames);
259f4a2713aSLionel Sambuc     if (O->ArgStr[0])
260f4a2713aSLionel Sambuc       OptionNames.push_back(O->ArgStr);
261f4a2713aSLionel Sambuc 
262f4a2713aSLionel Sambuc     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
263f4a2713aSLionel Sambuc     StringRef Flag = PermitValue ? LHS : Arg;
264f4a2713aSLionel Sambuc     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
265f4a2713aSLionel Sambuc       StringRef Name = OptionNames[i];
266f4a2713aSLionel Sambuc       unsigned Distance = StringRef(Name).edit_distance(
267f4a2713aSLionel Sambuc           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
268f4a2713aSLionel Sambuc       if (!Best || Distance < BestDistance) {
269f4a2713aSLionel Sambuc         Best = O;
270f4a2713aSLionel Sambuc         BestDistance = Distance;
271f4a2713aSLionel Sambuc         if (RHS.empty() || !PermitValue)
272f4a2713aSLionel Sambuc           NearestString = OptionNames[i];
273f4a2713aSLionel Sambuc         else
274f4a2713aSLionel Sambuc           NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
275f4a2713aSLionel Sambuc       }
276f4a2713aSLionel Sambuc     }
277f4a2713aSLionel Sambuc   }
278f4a2713aSLionel Sambuc 
279f4a2713aSLionel Sambuc   return Best;
280f4a2713aSLionel Sambuc }
281f4a2713aSLionel Sambuc 
282*0a6a1f1dSLionel Sambuc /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
283*0a6a1f1dSLionel Sambuc /// that does special handling of cl::CommaSeparated options.
CommaSeparateAndAddOccurrence(Option * Handler,unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg=false)284*0a6a1f1dSLionel Sambuc static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
285*0a6a1f1dSLionel Sambuc                                           StringRef ArgName, StringRef Value,
286*0a6a1f1dSLionel Sambuc                                           bool MultiArg = false) {
287f4a2713aSLionel Sambuc   // Check to see if this option accepts a comma separated list of values.  If
288f4a2713aSLionel Sambuc   // it does, we have to split up the value into multiple values.
289f4a2713aSLionel Sambuc   if (Handler->getMiscFlags() & CommaSeparated) {
290f4a2713aSLionel Sambuc     StringRef Val(Value);
291f4a2713aSLionel Sambuc     StringRef::size_type Pos = Val.find(',');
292f4a2713aSLionel Sambuc 
293f4a2713aSLionel Sambuc     while (Pos != StringRef::npos) {
294f4a2713aSLionel Sambuc       // Process the portion before the comma.
295f4a2713aSLionel Sambuc       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
296f4a2713aSLionel Sambuc         return true;
297f4a2713aSLionel Sambuc       // Erase the portion before the comma, AND the comma.
298f4a2713aSLionel Sambuc       Val = Val.substr(Pos + 1);
299f4a2713aSLionel Sambuc       Value.substr(Pos + 1); // Increment the original value pointer as well.
300f4a2713aSLionel Sambuc       // Check for another comma.
301f4a2713aSLionel Sambuc       Pos = Val.find(',');
302f4a2713aSLionel Sambuc     }
303f4a2713aSLionel Sambuc 
304f4a2713aSLionel Sambuc     Value = Val;
305f4a2713aSLionel Sambuc   }
306f4a2713aSLionel Sambuc 
307f4a2713aSLionel Sambuc   if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
308f4a2713aSLionel Sambuc     return true;
309f4a2713aSLionel Sambuc 
310f4a2713aSLionel Sambuc   return false;
311f4a2713aSLionel Sambuc }
312f4a2713aSLionel Sambuc 
313f4a2713aSLionel Sambuc /// ProvideOption - For Value, this differentiates between an empty value ("")
314f4a2713aSLionel Sambuc /// and a null value (StringRef()).  The later is accepted for arguments that
315f4a2713aSLionel Sambuc /// don't allow a value (-foo) the former is rejected (-foo=).
ProvideOption(Option * Handler,StringRef ArgName,StringRef Value,int argc,const char * const * argv,int & i)316f4a2713aSLionel Sambuc static inline bool ProvideOption(Option *Handler, StringRef ArgName,
317f4a2713aSLionel Sambuc                                  StringRef Value, int argc,
318f4a2713aSLionel Sambuc                                  const char *const *argv, int &i) {
319f4a2713aSLionel Sambuc   // Is this a multi-argument option?
320f4a2713aSLionel Sambuc   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
321f4a2713aSLionel Sambuc 
322f4a2713aSLionel Sambuc   // Enforce value requirements
323f4a2713aSLionel Sambuc   switch (Handler->getValueExpectedFlag()) {
324f4a2713aSLionel Sambuc   case ValueRequired:
325*0a6a1f1dSLionel Sambuc     if (!Value.data()) { // No value specified?
326f4a2713aSLionel Sambuc       if (i + 1 >= argc)
327f4a2713aSLionel Sambuc         return Handler->error("requires a value!");
328f4a2713aSLionel Sambuc       // Steal the next argument, like for '-o filename'
329*0a6a1f1dSLionel Sambuc       assert(argv && "null check");
330f4a2713aSLionel Sambuc       Value = argv[++i];
331f4a2713aSLionel Sambuc     }
332f4a2713aSLionel Sambuc     break;
333f4a2713aSLionel Sambuc   case ValueDisallowed:
334f4a2713aSLionel Sambuc     if (NumAdditionalVals > 0)
335f4a2713aSLionel Sambuc       return Handler->error("multi-valued option specified"
336f4a2713aSLionel Sambuc                             " with ValueDisallowed modifier!");
337f4a2713aSLionel Sambuc 
338f4a2713aSLionel Sambuc     if (Value.data())
339*0a6a1f1dSLionel Sambuc       return Handler->error("does not allow a value! '" + Twine(Value) +
340*0a6a1f1dSLionel Sambuc                             "' specified.");
341f4a2713aSLionel Sambuc     break;
342f4a2713aSLionel Sambuc   case ValueOptional:
343f4a2713aSLionel Sambuc     break;
344f4a2713aSLionel Sambuc   }
345f4a2713aSLionel Sambuc 
346f4a2713aSLionel Sambuc   // If this isn't a multi-arg option, just run the handler.
347f4a2713aSLionel Sambuc   if (NumAdditionalVals == 0)
348*0a6a1f1dSLionel Sambuc     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
349f4a2713aSLionel Sambuc 
350f4a2713aSLionel Sambuc   // If it is, run the handle several times.
351f4a2713aSLionel Sambuc   bool MultiArg = false;
352f4a2713aSLionel Sambuc 
353f4a2713aSLionel Sambuc   if (Value.data()) {
354*0a6a1f1dSLionel Sambuc     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
355f4a2713aSLionel Sambuc       return true;
356f4a2713aSLionel Sambuc     --NumAdditionalVals;
357f4a2713aSLionel Sambuc     MultiArg = true;
358f4a2713aSLionel Sambuc   }
359f4a2713aSLionel Sambuc 
360f4a2713aSLionel Sambuc   while (NumAdditionalVals > 0) {
361f4a2713aSLionel Sambuc     if (i + 1 >= argc)
362f4a2713aSLionel Sambuc       return Handler->error("not enough values!");
363*0a6a1f1dSLionel Sambuc     assert(argv && "null check");
364f4a2713aSLionel Sambuc     Value = argv[++i];
365f4a2713aSLionel Sambuc 
366*0a6a1f1dSLionel Sambuc     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
367f4a2713aSLionel Sambuc       return true;
368f4a2713aSLionel Sambuc     MultiArg = true;
369f4a2713aSLionel Sambuc     --NumAdditionalVals;
370f4a2713aSLionel Sambuc   }
371f4a2713aSLionel Sambuc   return false;
372f4a2713aSLionel Sambuc }
373f4a2713aSLionel Sambuc 
ProvidePositionalOption(Option * Handler,StringRef Arg,int i)374f4a2713aSLionel Sambuc static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
375f4a2713aSLionel Sambuc   int Dummy = i;
376*0a6a1f1dSLionel Sambuc   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
377f4a2713aSLionel Sambuc }
378f4a2713aSLionel Sambuc 
379f4a2713aSLionel Sambuc // Option predicates...
isGrouping(const Option * O)380f4a2713aSLionel Sambuc static inline bool isGrouping(const Option *O) {
381f4a2713aSLionel Sambuc   return O->getFormattingFlag() == cl::Grouping;
382f4a2713aSLionel Sambuc }
isPrefixedOrGrouping(const Option * O)383f4a2713aSLionel Sambuc static inline bool isPrefixedOrGrouping(const Option *O) {
384f4a2713aSLionel Sambuc   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
385f4a2713aSLionel Sambuc }
386f4a2713aSLionel Sambuc 
387f4a2713aSLionel Sambuc // getOptionPred - Check to see if there are any options that satisfy the
388f4a2713aSLionel Sambuc // specified predicate with names that are the prefixes in Name.  This is
389f4a2713aSLionel Sambuc // checked by progressively stripping characters off of the name, checking to
390f4a2713aSLionel Sambuc // see if there options that satisfy the predicate.  If we find one, return it,
391f4a2713aSLionel Sambuc // otherwise return null.
392f4a2713aSLionel Sambuc //
getOptionPred(StringRef Name,size_t & Length,bool (* Pred)(const Option *),const StringMap<Option * > & OptionsMap)393f4a2713aSLionel Sambuc static Option *getOptionPred(StringRef Name, size_t &Length,
394f4a2713aSLionel Sambuc                              bool (*Pred)(const Option *),
395f4a2713aSLionel Sambuc                              const StringMap<Option *> &OptionsMap) {
396f4a2713aSLionel Sambuc 
397f4a2713aSLionel Sambuc   StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
398f4a2713aSLionel Sambuc 
399f4a2713aSLionel Sambuc   // Loop while we haven't found an option and Name still has at least two
400f4a2713aSLionel Sambuc   // characters in it (so that the next iteration will not be the empty
401f4a2713aSLionel Sambuc   // string.
402f4a2713aSLionel Sambuc   while (OMI == OptionsMap.end() && Name.size() > 1) {
403f4a2713aSLionel Sambuc     Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
404f4a2713aSLionel Sambuc     OMI = OptionsMap.find(Name);
405f4a2713aSLionel Sambuc   }
406f4a2713aSLionel Sambuc 
407f4a2713aSLionel Sambuc   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
408f4a2713aSLionel Sambuc     Length = Name.size();
409f4a2713aSLionel Sambuc     return OMI->second; // Found one!
410f4a2713aSLionel Sambuc   }
411*0a6a1f1dSLionel Sambuc   return nullptr; // No option found!
412f4a2713aSLionel Sambuc }
413f4a2713aSLionel Sambuc 
414f4a2713aSLionel Sambuc /// HandlePrefixedOrGroupedOption - The specified argument string (which started
415f4a2713aSLionel Sambuc /// with at least one '-') does not fully match an available option.  Check to
416f4a2713aSLionel Sambuc /// see if this is a prefix or grouped option.  If so, split arg into output an
417f4a2713aSLionel Sambuc /// Arg/Value pair and return the Option to parse it with.
418*0a6a1f1dSLionel Sambuc static Option *
HandlePrefixedOrGroupedOption(StringRef & Arg,StringRef & Value,bool & ErrorParsing,const StringMap<Option * > & OptionsMap)419*0a6a1f1dSLionel Sambuc HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
420f4a2713aSLionel Sambuc                               bool &ErrorParsing,
421f4a2713aSLionel Sambuc                               const StringMap<Option *> &OptionsMap) {
422*0a6a1f1dSLionel Sambuc   if (Arg.size() == 1)
423*0a6a1f1dSLionel Sambuc     return nullptr;
424f4a2713aSLionel Sambuc 
425f4a2713aSLionel Sambuc   // Do the lookup!
426f4a2713aSLionel Sambuc   size_t Length = 0;
427f4a2713aSLionel Sambuc   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
428*0a6a1f1dSLionel Sambuc   if (!PGOpt)
429*0a6a1f1dSLionel Sambuc     return nullptr;
430f4a2713aSLionel Sambuc 
431f4a2713aSLionel Sambuc   // If the option is a prefixed option, then the value is simply the
432f4a2713aSLionel Sambuc   // rest of the name...  so fall through to later processing, by
433f4a2713aSLionel Sambuc   // setting up the argument name flags and value fields.
434f4a2713aSLionel Sambuc   if (PGOpt->getFormattingFlag() == cl::Prefix) {
435f4a2713aSLionel Sambuc     Value = Arg.substr(Length);
436f4a2713aSLionel Sambuc     Arg = Arg.substr(0, Length);
437f4a2713aSLionel Sambuc     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
438f4a2713aSLionel Sambuc     return PGOpt;
439f4a2713aSLionel Sambuc   }
440f4a2713aSLionel Sambuc 
441f4a2713aSLionel Sambuc   // This must be a grouped option... handle them now.  Grouping options can't
442f4a2713aSLionel Sambuc   // have values.
443f4a2713aSLionel Sambuc   assert(isGrouping(PGOpt) && "Broken getOptionPred!");
444f4a2713aSLionel Sambuc 
445f4a2713aSLionel Sambuc   do {
446f4a2713aSLionel Sambuc     // Move current arg name out of Arg into OneArgName.
447f4a2713aSLionel Sambuc     StringRef OneArgName = Arg.substr(0, Length);
448f4a2713aSLionel Sambuc     Arg = Arg.substr(Length);
449f4a2713aSLionel Sambuc 
450f4a2713aSLionel Sambuc     // Because ValueRequired is an invalid flag for grouped arguments,
451f4a2713aSLionel Sambuc     // we don't need to pass argc/argv in.
452f4a2713aSLionel Sambuc     assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
453f4a2713aSLionel Sambuc            "Option can not be cl::Grouping AND cl::ValueRequired!");
454f4a2713aSLionel Sambuc     int Dummy = 0;
455*0a6a1f1dSLionel Sambuc     ErrorParsing |=
456*0a6a1f1dSLionel Sambuc         ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
457f4a2713aSLionel Sambuc 
458f4a2713aSLionel Sambuc     // Get the next grouping option.
459f4a2713aSLionel Sambuc     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
460f4a2713aSLionel Sambuc   } while (PGOpt && Length != Arg.size());
461f4a2713aSLionel Sambuc 
462f4a2713aSLionel Sambuc   // Return the last option with Arg cut down to just the last one.
463f4a2713aSLionel Sambuc   return PGOpt;
464f4a2713aSLionel Sambuc }
465f4a2713aSLionel Sambuc 
RequiresValue(const Option * O)466f4a2713aSLionel Sambuc static bool RequiresValue(const Option *O) {
467f4a2713aSLionel Sambuc   return O->getNumOccurrencesFlag() == cl::Required ||
468f4a2713aSLionel Sambuc          O->getNumOccurrencesFlag() == cl::OneOrMore;
469f4a2713aSLionel Sambuc }
470f4a2713aSLionel Sambuc 
EatsUnboundedNumberOfValues(const Option * O)471f4a2713aSLionel Sambuc static bool EatsUnboundedNumberOfValues(const Option *O) {
472f4a2713aSLionel Sambuc   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
473f4a2713aSLionel Sambuc          O->getNumOccurrencesFlag() == cl::OneOrMore;
474f4a2713aSLionel Sambuc }
475f4a2713aSLionel Sambuc 
isWhitespace(char C)476*0a6a1f1dSLionel Sambuc static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
477f4a2713aSLionel Sambuc 
isQuote(char C)478*0a6a1f1dSLionel Sambuc static bool isQuote(char C) { return C == '\"' || C == '\''; }
479f4a2713aSLionel Sambuc 
isGNUSpecial(char C)480*0a6a1f1dSLionel Sambuc static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
481f4a2713aSLionel Sambuc 
TokenizeGNUCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)482f4a2713aSLionel Sambuc void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
483*0a6a1f1dSLionel Sambuc                                 SmallVectorImpl<const char *> &NewArgv,
484*0a6a1f1dSLionel Sambuc                                 bool MarkEOLs) {
485f4a2713aSLionel Sambuc   SmallString<128> Token;
486f4a2713aSLionel Sambuc   for (size_t I = 0, E = Src.size(); I != E; ++I) {
487f4a2713aSLionel Sambuc     // Consume runs of whitespace.
488f4a2713aSLionel Sambuc     if (Token.empty()) {
489*0a6a1f1dSLionel Sambuc       while (I != E && isWhitespace(Src[I])) {
490*0a6a1f1dSLionel Sambuc         // Mark the end of lines in response files
491*0a6a1f1dSLionel Sambuc         if (MarkEOLs && Src[I] == '\n')
492*0a6a1f1dSLionel Sambuc           NewArgv.push_back(nullptr);
493f4a2713aSLionel Sambuc         ++I;
494*0a6a1f1dSLionel Sambuc       }
495*0a6a1f1dSLionel Sambuc       if (I == E)
496*0a6a1f1dSLionel Sambuc         break;
497f4a2713aSLionel Sambuc     }
498f4a2713aSLionel Sambuc 
499f4a2713aSLionel Sambuc     // Backslashes can escape backslashes, spaces, and other quotes.  Otherwise
500f4a2713aSLionel Sambuc     // they are literal.  This makes it much easier to read Windows file paths.
501f4a2713aSLionel Sambuc     if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
502f4a2713aSLionel Sambuc       ++I; // Skip the escape.
503f4a2713aSLionel Sambuc       Token.push_back(Src[I]);
504f4a2713aSLionel Sambuc       continue;
505f4a2713aSLionel Sambuc     }
506f4a2713aSLionel Sambuc 
507f4a2713aSLionel Sambuc     // Consume a quoted string.
508f4a2713aSLionel Sambuc     if (isQuote(Src[I])) {
509f4a2713aSLionel Sambuc       char Quote = Src[I++];
510f4a2713aSLionel Sambuc       while (I != E && Src[I] != Quote) {
511f4a2713aSLionel Sambuc         // Backslashes are literal, unless they escape a special character.
512f4a2713aSLionel Sambuc         if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
513f4a2713aSLionel Sambuc           ++I;
514f4a2713aSLionel Sambuc         Token.push_back(Src[I]);
515f4a2713aSLionel Sambuc         ++I;
516f4a2713aSLionel Sambuc       }
517*0a6a1f1dSLionel Sambuc       if (I == E)
518*0a6a1f1dSLionel Sambuc         break;
519f4a2713aSLionel Sambuc       continue;
520f4a2713aSLionel Sambuc     }
521f4a2713aSLionel Sambuc 
522f4a2713aSLionel Sambuc     // End the token if this is whitespace.
523f4a2713aSLionel Sambuc     if (isWhitespace(Src[I])) {
524f4a2713aSLionel Sambuc       if (!Token.empty())
525f4a2713aSLionel Sambuc         NewArgv.push_back(Saver.SaveString(Token.c_str()));
526f4a2713aSLionel Sambuc       Token.clear();
527f4a2713aSLionel Sambuc       continue;
528f4a2713aSLionel Sambuc     }
529f4a2713aSLionel Sambuc 
530f4a2713aSLionel Sambuc     // This is a normal character.  Append it.
531f4a2713aSLionel Sambuc     Token.push_back(Src[I]);
532f4a2713aSLionel Sambuc   }
533f4a2713aSLionel Sambuc 
534f4a2713aSLionel Sambuc   // Append the last token after hitting EOF with no whitespace.
535f4a2713aSLionel Sambuc   if (!Token.empty())
536f4a2713aSLionel Sambuc     NewArgv.push_back(Saver.SaveString(Token.c_str()));
537*0a6a1f1dSLionel Sambuc   // Mark the end of response files
538*0a6a1f1dSLionel Sambuc   if (MarkEOLs)
539*0a6a1f1dSLionel Sambuc     NewArgv.push_back(nullptr);
540f4a2713aSLionel Sambuc }
541f4a2713aSLionel Sambuc 
542f4a2713aSLionel Sambuc /// Backslashes are interpreted in a rather complicated way in the Windows-style
543f4a2713aSLionel Sambuc /// command line, because backslashes are used both to separate path and to
544f4a2713aSLionel Sambuc /// escape double quote. This method consumes runs of backslashes as well as the
545f4a2713aSLionel Sambuc /// following double quote if it's escaped.
546f4a2713aSLionel Sambuc ///
547f4a2713aSLionel Sambuc ///  * If an even number of backslashes is followed by a double quote, one
548f4a2713aSLionel Sambuc ///    backslash is output for every pair of backslashes, and the last double
549f4a2713aSLionel Sambuc ///    quote remains unconsumed. The double quote will later be interpreted as
550f4a2713aSLionel Sambuc ///    the start or end of a quoted string in the main loop outside of this
551f4a2713aSLionel Sambuc ///    function.
552f4a2713aSLionel Sambuc ///
553f4a2713aSLionel Sambuc ///  * If an odd number of backslashes is followed by a double quote, one
554f4a2713aSLionel Sambuc ///    backslash is output for every pair of backslashes, and a double quote is
555f4a2713aSLionel Sambuc ///    output for the last pair of backslash-double quote. The double quote is
556f4a2713aSLionel Sambuc ///    consumed in this case.
557f4a2713aSLionel Sambuc ///
558f4a2713aSLionel Sambuc ///  * Otherwise, backslashes are interpreted literally.
parseBackslash(StringRef Src,size_t I,SmallString<128> & Token)559f4a2713aSLionel Sambuc static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
560f4a2713aSLionel Sambuc   size_t E = Src.size();
561f4a2713aSLionel Sambuc   int BackslashCount = 0;
562f4a2713aSLionel Sambuc   // Skip the backslashes.
563f4a2713aSLionel Sambuc   do {
564f4a2713aSLionel Sambuc     ++I;
565f4a2713aSLionel Sambuc     ++BackslashCount;
566f4a2713aSLionel Sambuc   } while (I != E && Src[I] == '\\');
567f4a2713aSLionel Sambuc 
568f4a2713aSLionel Sambuc   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
569f4a2713aSLionel Sambuc   if (FollowedByDoubleQuote) {
570f4a2713aSLionel Sambuc     Token.append(BackslashCount / 2, '\\');
571f4a2713aSLionel Sambuc     if (BackslashCount % 2 == 0)
572f4a2713aSLionel Sambuc       return I - 1;
573f4a2713aSLionel Sambuc     Token.push_back('"');
574f4a2713aSLionel Sambuc     return I;
575f4a2713aSLionel Sambuc   }
576f4a2713aSLionel Sambuc   Token.append(BackslashCount, '\\');
577f4a2713aSLionel Sambuc   return I - 1;
578f4a2713aSLionel Sambuc }
579f4a2713aSLionel Sambuc 
TokenizeWindowsCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)580f4a2713aSLionel Sambuc void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
581*0a6a1f1dSLionel Sambuc                                     SmallVectorImpl<const char *> &NewArgv,
582*0a6a1f1dSLionel Sambuc                                     bool MarkEOLs) {
583f4a2713aSLionel Sambuc   SmallString<128> Token;
584f4a2713aSLionel Sambuc 
585f4a2713aSLionel Sambuc   // This is a small state machine to consume characters until it reaches the
586f4a2713aSLionel Sambuc   // end of the source string.
587f4a2713aSLionel Sambuc   enum { INIT, UNQUOTED, QUOTED } State = INIT;
588f4a2713aSLionel Sambuc   for (size_t I = 0, E = Src.size(); I != E; ++I) {
589f4a2713aSLionel Sambuc     // INIT state indicates that the current input index is at the start of
590f4a2713aSLionel Sambuc     // the string or between tokens.
591f4a2713aSLionel Sambuc     if (State == INIT) {
592*0a6a1f1dSLionel Sambuc       if (isWhitespace(Src[I])) {
593*0a6a1f1dSLionel Sambuc         // Mark the end of lines in response files
594*0a6a1f1dSLionel Sambuc         if (MarkEOLs && Src[I] == '\n')
595*0a6a1f1dSLionel Sambuc           NewArgv.push_back(nullptr);
596f4a2713aSLionel Sambuc         continue;
597*0a6a1f1dSLionel Sambuc       }
598f4a2713aSLionel Sambuc       if (Src[I] == '"') {
599f4a2713aSLionel Sambuc         State = QUOTED;
600f4a2713aSLionel Sambuc         continue;
601f4a2713aSLionel Sambuc       }
602f4a2713aSLionel Sambuc       if (Src[I] == '\\') {
603f4a2713aSLionel Sambuc         I = parseBackslash(Src, I, Token);
604f4a2713aSLionel Sambuc         State = UNQUOTED;
605f4a2713aSLionel Sambuc         continue;
606f4a2713aSLionel Sambuc       }
607f4a2713aSLionel Sambuc       Token.push_back(Src[I]);
608f4a2713aSLionel Sambuc       State = UNQUOTED;
609f4a2713aSLionel Sambuc       continue;
610f4a2713aSLionel Sambuc     }
611f4a2713aSLionel Sambuc 
612f4a2713aSLionel Sambuc     // UNQUOTED state means that it's reading a token not quoted by double
613f4a2713aSLionel Sambuc     // quotes.
614f4a2713aSLionel Sambuc     if (State == UNQUOTED) {
615f4a2713aSLionel Sambuc       // Whitespace means the end of the token.
616f4a2713aSLionel Sambuc       if (isWhitespace(Src[I])) {
617f4a2713aSLionel Sambuc         NewArgv.push_back(Saver.SaveString(Token.c_str()));
618f4a2713aSLionel Sambuc         Token.clear();
619f4a2713aSLionel Sambuc         State = INIT;
620*0a6a1f1dSLionel Sambuc         // Mark the end of lines in response files
621*0a6a1f1dSLionel Sambuc         if (MarkEOLs && Src[I] == '\n')
622*0a6a1f1dSLionel Sambuc           NewArgv.push_back(nullptr);
623f4a2713aSLionel Sambuc         continue;
624f4a2713aSLionel Sambuc       }
625f4a2713aSLionel Sambuc       if (Src[I] == '"') {
626f4a2713aSLionel Sambuc         State = QUOTED;
627f4a2713aSLionel Sambuc         continue;
628f4a2713aSLionel Sambuc       }
629f4a2713aSLionel Sambuc       if (Src[I] == '\\') {
630f4a2713aSLionel Sambuc         I = parseBackslash(Src, I, Token);
631f4a2713aSLionel Sambuc         continue;
632f4a2713aSLionel Sambuc       }
633f4a2713aSLionel Sambuc       Token.push_back(Src[I]);
634f4a2713aSLionel Sambuc       continue;
635f4a2713aSLionel Sambuc     }
636f4a2713aSLionel Sambuc 
637f4a2713aSLionel Sambuc     // QUOTED state means that it's reading a token quoted by double quotes.
638f4a2713aSLionel Sambuc     if (State == QUOTED) {
639f4a2713aSLionel Sambuc       if (Src[I] == '"') {
640f4a2713aSLionel Sambuc         State = UNQUOTED;
641f4a2713aSLionel Sambuc         continue;
642f4a2713aSLionel Sambuc       }
643f4a2713aSLionel Sambuc       if (Src[I] == '\\') {
644f4a2713aSLionel Sambuc         I = parseBackslash(Src, I, Token);
645f4a2713aSLionel Sambuc         continue;
646f4a2713aSLionel Sambuc       }
647f4a2713aSLionel Sambuc       Token.push_back(Src[I]);
648f4a2713aSLionel Sambuc     }
649f4a2713aSLionel Sambuc   }
650f4a2713aSLionel Sambuc   // Append the last token after hitting EOF with no whitespace.
651f4a2713aSLionel Sambuc   if (!Token.empty())
652f4a2713aSLionel Sambuc     NewArgv.push_back(Saver.SaveString(Token.c_str()));
653*0a6a1f1dSLionel Sambuc   // Mark the end of response files
654*0a6a1f1dSLionel Sambuc   if (MarkEOLs)
655*0a6a1f1dSLionel Sambuc     NewArgv.push_back(nullptr);
656f4a2713aSLionel Sambuc }
657f4a2713aSLionel Sambuc 
ExpandResponseFile(const char * FName,StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs=false)658f4a2713aSLionel Sambuc static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
659f4a2713aSLionel Sambuc                                TokenizerCallback Tokenizer,
660*0a6a1f1dSLionel Sambuc                                SmallVectorImpl<const char *> &NewArgv,
661*0a6a1f1dSLionel Sambuc                                bool MarkEOLs = false) {
662*0a6a1f1dSLionel Sambuc   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
663*0a6a1f1dSLionel Sambuc       MemoryBuffer::getFile(FName);
664*0a6a1f1dSLionel Sambuc   if (!MemBufOrErr)
665f4a2713aSLionel Sambuc     return false;
666*0a6a1f1dSLionel Sambuc   MemoryBuffer &MemBuf = *MemBufOrErr.get();
667*0a6a1f1dSLionel Sambuc   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
668f4a2713aSLionel Sambuc 
669f4a2713aSLionel Sambuc   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
670*0a6a1f1dSLionel Sambuc   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
671f4a2713aSLionel Sambuc   std::string UTF8Buf;
672f4a2713aSLionel Sambuc   if (hasUTF16ByteOrderMark(BufRef)) {
673f4a2713aSLionel Sambuc     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
674f4a2713aSLionel Sambuc       return false;
675f4a2713aSLionel Sambuc     Str = StringRef(UTF8Buf);
676f4a2713aSLionel Sambuc   }
677f4a2713aSLionel Sambuc 
678f4a2713aSLionel Sambuc   // Tokenize the contents into NewArgv.
679*0a6a1f1dSLionel Sambuc   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
680f4a2713aSLionel Sambuc 
681f4a2713aSLionel Sambuc   return true;
682f4a2713aSLionel Sambuc }
683f4a2713aSLionel Sambuc 
684f4a2713aSLionel Sambuc /// \brief Expand response files on a command line recursively using the given
685f4a2713aSLionel Sambuc /// StringSaver and tokenization strategy.
ExpandResponseFiles(StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & Argv,bool MarkEOLs)686f4a2713aSLionel Sambuc bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
687*0a6a1f1dSLionel Sambuc                              SmallVectorImpl<const char *> &Argv,
688*0a6a1f1dSLionel Sambuc                              bool MarkEOLs) {
689f4a2713aSLionel Sambuc   unsigned RspFiles = 0;
690*0a6a1f1dSLionel Sambuc   bool AllExpanded = true;
691f4a2713aSLionel Sambuc 
692f4a2713aSLionel Sambuc   // Don't cache Argv.size() because it can change.
693f4a2713aSLionel Sambuc   for (unsigned I = 0; I != Argv.size();) {
694f4a2713aSLionel Sambuc     const char *Arg = Argv[I];
695*0a6a1f1dSLionel Sambuc     // Check if it is an EOL marker
696*0a6a1f1dSLionel Sambuc     if (Arg == nullptr) {
697*0a6a1f1dSLionel Sambuc       ++I;
698*0a6a1f1dSLionel Sambuc       continue;
699*0a6a1f1dSLionel Sambuc     }
700f4a2713aSLionel Sambuc     if (Arg[0] != '@') {
701f4a2713aSLionel Sambuc       ++I;
702f4a2713aSLionel Sambuc       continue;
703f4a2713aSLionel Sambuc     }
704f4a2713aSLionel Sambuc 
705f4a2713aSLionel Sambuc     // If we have too many response files, leave some unexpanded.  This avoids
706f4a2713aSLionel Sambuc     // crashing on self-referential response files.
707f4a2713aSLionel Sambuc     if (RspFiles++ > 20)
708f4a2713aSLionel Sambuc       return false;
709f4a2713aSLionel Sambuc 
710f4a2713aSLionel Sambuc     // Replace this response file argument with the tokenization of its
711f4a2713aSLionel Sambuc     // contents.  Nested response files are expanded in subsequent iterations.
712f4a2713aSLionel Sambuc     // FIXME: If a nested response file uses a relative path, is it relative to
713f4a2713aSLionel Sambuc     // the cwd of the process or the response file?
714f4a2713aSLionel Sambuc     SmallVector<const char *, 0> ExpandedArgv;
715*0a6a1f1dSLionel Sambuc     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
716*0a6a1f1dSLionel Sambuc                             MarkEOLs)) {
717*0a6a1f1dSLionel Sambuc       // We couldn't read this file, so we leave it in the argument stream and
718*0a6a1f1dSLionel Sambuc       // move on.
719f4a2713aSLionel Sambuc       AllExpanded = false;
720*0a6a1f1dSLionel Sambuc       ++I;
721f4a2713aSLionel Sambuc       continue;
722f4a2713aSLionel Sambuc     }
723f4a2713aSLionel Sambuc     Argv.erase(Argv.begin() + I);
724f4a2713aSLionel Sambuc     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
725f4a2713aSLionel Sambuc   }
726f4a2713aSLionel Sambuc   return AllExpanded;
727f4a2713aSLionel Sambuc }
728f4a2713aSLionel Sambuc 
729f4a2713aSLionel Sambuc namespace {
730f4a2713aSLionel Sambuc class StrDupSaver : public StringSaver {
731f4a2713aSLionel Sambuc   std::vector<char *> Dups;
732*0a6a1f1dSLionel Sambuc 
733f4a2713aSLionel Sambuc public:
~StrDupSaver()734f4a2713aSLionel Sambuc   ~StrDupSaver() {
735*0a6a1f1dSLionel Sambuc     for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
736*0a6a1f1dSLionel Sambuc          ++I) {
737f4a2713aSLionel Sambuc       char *Dup = *I;
738f4a2713aSLionel Sambuc       free(Dup);
739f4a2713aSLionel Sambuc     }
740f4a2713aSLionel Sambuc   }
SaveString(const char * Str)741*0a6a1f1dSLionel Sambuc   const char *SaveString(const char *Str) override {
742f4a2713aSLionel Sambuc     char *Dup = strdup(Str);
743f4a2713aSLionel Sambuc     Dups.push_back(Dup);
744f4a2713aSLionel Sambuc     return Dup;
745f4a2713aSLionel Sambuc   }
746f4a2713aSLionel Sambuc };
747f4a2713aSLionel Sambuc }
748f4a2713aSLionel Sambuc 
749f4a2713aSLionel Sambuc /// ParseEnvironmentOptions - An alternative entry point to the
750f4a2713aSLionel Sambuc /// CommandLine library, which allows you to read the program's name
751f4a2713aSLionel Sambuc /// from the caller (as PROGNAME) and its command-line arguments from
752f4a2713aSLionel Sambuc /// an environment variable (whose name is given in ENVVAR).
753f4a2713aSLionel Sambuc ///
ParseEnvironmentOptions(const char * progName,const char * envVar,const char * Overview)754f4a2713aSLionel Sambuc void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
755f4a2713aSLionel Sambuc                                  const char *Overview) {
756f4a2713aSLionel Sambuc   // Check args.
757f4a2713aSLionel Sambuc   assert(progName && "Program name not specified");
758f4a2713aSLionel Sambuc   assert(envVar && "Environment variable name missing");
759f4a2713aSLionel Sambuc 
760f4a2713aSLionel Sambuc   // Get the environment variable they want us to parse options out of.
761f4a2713aSLionel Sambuc   const char *envValue = getenv(envVar);
762f4a2713aSLionel Sambuc   if (!envValue)
763f4a2713aSLionel Sambuc     return;
764f4a2713aSLionel Sambuc 
765f4a2713aSLionel Sambuc   // Get program's "name", which we wouldn't know without the caller
766f4a2713aSLionel Sambuc   // telling us.
767f4a2713aSLionel Sambuc   SmallVector<const char *, 20> newArgv;
768f4a2713aSLionel Sambuc   StrDupSaver Saver;
769f4a2713aSLionel Sambuc   newArgv.push_back(Saver.SaveString(progName));
770f4a2713aSLionel Sambuc 
771f4a2713aSLionel Sambuc   // Parse the value of the environment variable into a "command line"
772f4a2713aSLionel Sambuc   // and hand it off to ParseCommandLineOptions().
773f4a2713aSLionel Sambuc   TokenizeGNUCommandLine(envValue, Saver, newArgv);
774f4a2713aSLionel Sambuc   int newArgc = static_cast<int>(newArgv.size());
775f4a2713aSLionel Sambuc   ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
776f4a2713aSLionel Sambuc }
777f4a2713aSLionel Sambuc 
ParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)778f4a2713aSLionel Sambuc void cl::ParseCommandLineOptions(int argc, const char *const *argv,
779f4a2713aSLionel Sambuc                                  const char *Overview) {
780f4a2713aSLionel Sambuc   // Process all registered options.
781f4a2713aSLionel Sambuc   SmallVector<Option *, 4> PositionalOpts;
782f4a2713aSLionel Sambuc   SmallVector<Option *, 4> SinkOpts;
783f4a2713aSLionel Sambuc   StringMap<Option *> Opts;
784f4a2713aSLionel Sambuc   GetOptionInfo(PositionalOpts, SinkOpts, Opts);
785f4a2713aSLionel Sambuc 
786*0a6a1f1dSLionel Sambuc   assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!");
787f4a2713aSLionel Sambuc 
788f4a2713aSLionel Sambuc   // Expand response files.
789f4a2713aSLionel Sambuc   SmallVector<const char *, 20> newArgv;
790f4a2713aSLionel Sambuc   for (int i = 0; i != argc; ++i)
791f4a2713aSLionel Sambuc     newArgv.push_back(argv[i]);
792f4a2713aSLionel Sambuc   StrDupSaver Saver;
793f4a2713aSLionel Sambuc   ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
794f4a2713aSLionel Sambuc   argv = &newArgv[0];
795f4a2713aSLionel Sambuc   argc = static_cast<int>(newArgv.size());
796f4a2713aSLionel Sambuc 
797f4a2713aSLionel Sambuc   // Copy the program name into ProgName, making sure not to overflow it.
798*0a6a1f1dSLionel Sambuc   StringRef ProgName = sys::path::filename(argv[0]);
799f4a2713aSLionel Sambuc   size_t Len = std::min(ProgName.size(), size_t(79));
800f4a2713aSLionel Sambuc   memcpy(ProgramName, ProgName.data(), Len);
801f4a2713aSLionel Sambuc   ProgramName[Len] = '\0';
802f4a2713aSLionel Sambuc 
803f4a2713aSLionel Sambuc   ProgramOverview = Overview;
804f4a2713aSLionel Sambuc   bool ErrorParsing = false;
805f4a2713aSLionel Sambuc 
806f4a2713aSLionel Sambuc   // Check out the positional arguments to collect information about them.
807f4a2713aSLionel Sambuc   unsigned NumPositionalRequired = 0;
808f4a2713aSLionel Sambuc 
809f4a2713aSLionel Sambuc   // Determine whether or not there are an unlimited number of positionals
810f4a2713aSLionel Sambuc   bool HasUnlimitedPositionals = false;
811f4a2713aSLionel Sambuc 
812*0a6a1f1dSLionel Sambuc   Option *ConsumeAfterOpt = nullptr;
813f4a2713aSLionel Sambuc   if (!PositionalOpts.empty()) {
814f4a2713aSLionel Sambuc     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
815f4a2713aSLionel Sambuc       assert(PositionalOpts.size() > 1 &&
816f4a2713aSLionel Sambuc              "Cannot specify cl::ConsumeAfter without a positional argument!");
817f4a2713aSLionel Sambuc       ConsumeAfterOpt = PositionalOpts[0];
818f4a2713aSLionel Sambuc     }
819f4a2713aSLionel Sambuc 
820f4a2713aSLionel Sambuc     // Calculate how many positional values are _required_.
821f4a2713aSLionel Sambuc     bool UnboundedFound = false;
822*0a6a1f1dSLionel Sambuc     for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size(); i != e;
823*0a6a1f1dSLionel Sambuc          ++i) {
824f4a2713aSLionel Sambuc       Option *Opt = PositionalOpts[i];
825f4a2713aSLionel Sambuc       if (RequiresValue(Opt))
826f4a2713aSLionel Sambuc         ++NumPositionalRequired;
827f4a2713aSLionel Sambuc       else if (ConsumeAfterOpt) {
828f4a2713aSLionel Sambuc         // ConsumeAfter cannot be combined with "optional" positional options
829f4a2713aSLionel Sambuc         // unless there is only one positional argument...
830f4a2713aSLionel Sambuc         if (PositionalOpts.size() > 2)
831*0a6a1f1dSLionel Sambuc           ErrorParsing |= Opt->error(
832*0a6a1f1dSLionel Sambuc               "error - this positional option will never be matched, "
833f4a2713aSLionel Sambuc               "because it does not Require a value, and a "
834f4a2713aSLionel Sambuc               "cl::ConsumeAfter option is active!");
835f4a2713aSLionel Sambuc       } else if (UnboundedFound && !Opt->ArgStr[0]) {
836f4a2713aSLionel Sambuc         // This option does not "require" a value...  Make sure this option is
837f4a2713aSLionel Sambuc         // not specified after an option that eats all extra arguments, or this
838f4a2713aSLionel Sambuc         // one will never get any!
839f4a2713aSLionel Sambuc         //
840f4a2713aSLionel Sambuc         ErrorParsing |= Opt->error("error - option can never match, because "
841f4a2713aSLionel Sambuc                                    "another positional argument will match an "
842f4a2713aSLionel Sambuc                                    "unbounded number of values, and this option"
843f4a2713aSLionel Sambuc                                    " does not require a value!");
844f4a2713aSLionel Sambuc       }
845f4a2713aSLionel Sambuc       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
846f4a2713aSLionel Sambuc     }
847f4a2713aSLionel Sambuc     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
848f4a2713aSLionel Sambuc   }
849f4a2713aSLionel Sambuc 
850f4a2713aSLionel Sambuc   // PositionalVals - A vector of "positional" arguments we accumulate into
851f4a2713aSLionel Sambuc   // the process at the end.
852f4a2713aSLionel Sambuc   //
853f4a2713aSLionel Sambuc   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
854f4a2713aSLionel Sambuc 
855f4a2713aSLionel Sambuc   // If the program has named positional arguments, and the name has been run
856f4a2713aSLionel Sambuc   // across, keep track of which positional argument was named.  Otherwise put
857f4a2713aSLionel Sambuc   // the positional args into the PositionalVals list...
858*0a6a1f1dSLionel Sambuc   Option *ActivePositionalArg = nullptr;
859f4a2713aSLionel Sambuc 
860f4a2713aSLionel Sambuc   // Loop over all of the arguments... processing them.
861f4a2713aSLionel Sambuc   bool DashDashFound = false; // Have we read '--'?
862f4a2713aSLionel Sambuc   for (int i = 1; i < argc; ++i) {
863*0a6a1f1dSLionel Sambuc     Option *Handler = nullptr;
864*0a6a1f1dSLionel Sambuc     Option *NearestHandler = nullptr;
865f4a2713aSLionel Sambuc     std::string NearestHandlerString;
866f4a2713aSLionel Sambuc     StringRef Value;
867f4a2713aSLionel Sambuc     StringRef ArgName = "";
868f4a2713aSLionel Sambuc 
869f4a2713aSLionel Sambuc     // If the option list changed, this means that some command line
870f4a2713aSLionel Sambuc     // option has just been registered or deregistered.  This can occur in
871f4a2713aSLionel Sambuc     // response to things like -load, etc.  If this happens, rescan the options.
872f4a2713aSLionel Sambuc     if (OptionListChanged) {
873f4a2713aSLionel Sambuc       PositionalOpts.clear();
874f4a2713aSLionel Sambuc       SinkOpts.clear();
875f4a2713aSLionel Sambuc       Opts.clear();
876f4a2713aSLionel Sambuc       GetOptionInfo(PositionalOpts, SinkOpts, Opts);
877f4a2713aSLionel Sambuc       OptionListChanged = false;
878f4a2713aSLionel Sambuc     }
879f4a2713aSLionel Sambuc 
880f4a2713aSLionel Sambuc     // Check to see if this is a positional argument.  This argument is
881f4a2713aSLionel Sambuc     // considered to be positional if it doesn't start with '-', if it is "-"
882f4a2713aSLionel Sambuc     // itself, or if we have seen "--" already.
883f4a2713aSLionel Sambuc     //
884f4a2713aSLionel Sambuc     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
885f4a2713aSLionel Sambuc       // Positional argument!
886f4a2713aSLionel Sambuc       if (ActivePositionalArg) {
887f4a2713aSLionel Sambuc         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
888f4a2713aSLionel Sambuc         continue; // We are done!
889f4a2713aSLionel Sambuc       }
890f4a2713aSLionel Sambuc 
891f4a2713aSLionel Sambuc       if (!PositionalOpts.empty()) {
892f4a2713aSLionel Sambuc         PositionalVals.push_back(std::make_pair(argv[i], i));
893f4a2713aSLionel Sambuc 
894f4a2713aSLionel Sambuc         // All of the positional arguments have been fulfulled, give the rest to
895f4a2713aSLionel Sambuc         // the consume after option... if it's specified...
896f4a2713aSLionel Sambuc         //
897*0a6a1f1dSLionel Sambuc         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
898f4a2713aSLionel Sambuc           for (++i; i < argc; ++i)
899f4a2713aSLionel Sambuc             PositionalVals.push_back(std::make_pair(argv[i], i));
900f4a2713aSLionel Sambuc           break; // Handle outside of the argument processing loop...
901f4a2713aSLionel Sambuc         }
902f4a2713aSLionel Sambuc 
903f4a2713aSLionel Sambuc         // Delay processing positional arguments until the end...
904f4a2713aSLionel Sambuc         continue;
905f4a2713aSLionel Sambuc       }
906f4a2713aSLionel Sambuc     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
907f4a2713aSLionel Sambuc                !DashDashFound) {
908f4a2713aSLionel Sambuc       DashDashFound = true; // This is the mythical "--"?
909f4a2713aSLionel Sambuc       continue;             // Don't try to process it as an argument itself.
910f4a2713aSLionel Sambuc     } else if (ActivePositionalArg &&
911f4a2713aSLionel Sambuc                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
912f4a2713aSLionel Sambuc       // If there is a positional argument eating options, check to see if this
913f4a2713aSLionel Sambuc       // option is another positional argument.  If so, treat it as an argument,
914f4a2713aSLionel Sambuc       // otherwise feed it to the eating positional.
915f4a2713aSLionel Sambuc       ArgName = argv[i] + 1;
916f4a2713aSLionel Sambuc       // Eat leading dashes.
917f4a2713aSLionel Sambuc       while (!ArgName.empty() && ArgName[0] == '-')
918f4a2713aSLionel Sambuc         ArgName = ArgName.substr(1);
919f4a2713aSLionel Sambuc 
920f4a2713aSLionel Sambuc       Handler = LookupOption(ArgName, Value, Opts);
921f4a2713aSLionel Sambuc       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
922f4a2713aSLionel Sambuc         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
923f4a2713aSLionel Sambuc         continue; // We are done!
924f4a2713aSLionel Sambuc       }
925f4a2713aSLionel Sambuc 
926f4a2713aSLionel Sambuc     } else { // We start with a '-', must be an argument.
927f4a2713aSLionel Sambuc       ArgName = argv[i] + 1;
928f4a2713aSLionel Sambuc       // Eat leading dashes.
929f4a2713aSLionel Sambuc       while (!ArgName.empty() && ArgName[0] == '-')
930f4a2713aSLionel Sambuc         ArgName = ArgName.substr(1);
931f4a2713aSLionel Sambuc 
932f4a2713aSLionel Sambuc       Handler = LookupOption(ArgName, Value, Opts);
933f4a2713aSLionel Sambuc 
934f4a2713aSLionel Sambuc       // Check to see if this "option" is really a prefixed or grouped argument.
935*0a6a1f1dSLionel Sambuc       if (!Handler)
936*0a6a1f1dSLionel Sambuc         Handler =
937*0a6a1f1dSLionel Sambuc             HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, Opts);
938f4a2713aSLionel Sambuc 
939f4a2713aSLionel Sambuc       // Otherwise, look for the closest available option to report to the user
940f4a2713aSLionel Sambuc       // in the upcoming error.
941*0a6a1f1dSLionel Sambuc       if (!Handler && SinkOpts.empty())
942*0a6a1f1dSLionel Sambuc         NearestHandler =
943*0a6a1f1dSLionel Sambuc             LookupNearestOption(ArgName, Opts, NearestHandlerString);
944f4a2713aSLionel Sambuc     }
945f4a2713aSLionel Sambuc 
946*0a6a1f1dSLionel Sambuc     if (!Handler) {
947f4a2713aSLionel Sambuc       if (SinkOpts.empty()) {
948*0a6a1f1dSLionel Sambuc         errs() << ProgramName << ": Unknown command line argument '" << argv[i]
949*0a6a1f1dSLionel Sambuc                << "'.  Try: '" << argv[0] << " -help'\n";
950f4a2713aSLionel Sambuc 
951f4a2713aSLionel Sambuc         if (NearestHandler) {
952f4a2713aSLionel Sambuc           // If we know a near match, report it as well.
953*0a6a1f1dSLionel Sambuc           errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
954*0a6a1f1dSLionel Sambuc                  << "'?\n";
955f4a2713aSLionel Sambuc         }
956f4a2713aSLionel Sambuc 
957f4a2713aSLionel Sambuc         ErrorParsing = true;
958f4a2713aSLionel Sambuc       } else {
959f4a2713aSLionel Sambuc         for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
960*0a6a1f1dSLionel Sambuc                                                  E = SinkOpts.end();
961*0a6a1f1dSLionel Sambuc              I != E; ++I)
962f4a2713aSLionel Sambuc           (*I)->addOccurrence(i, "", argv[i]);
963f4a2713aSLionel Sambuc       }
964f4a2713aSLionel Sambuc       continue;
965f4a2713aSLionel Sambuc     }
966f4a2713aSLionel Sambuc 
967f4a2713aSLionel Sambuc     // If this is a named positional argument, just remember that it is the
968f4a2713aSLionel Sambuc     // active one...
969f4a2713aSLionel Sambuc     if (Handler->getFormattingFlag() == cl::Positional)
970f4a2713aSLionel Sambuc       ActivePositionalArg = Handler;
971f4a2713aSLionel Sambuc     else
972f4a2713aSLionel Sambuc       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
973f4a2713aSLionel Sambuc   }
974f4a2713aSLionel Sambuc 
975f4a2713aSLionel Sambuc   // Check and handle positional arguments now...
976f4a2713aSLionel Sambuc   if (NumPositionalRequired > PositionalVals.size()) {
977f4a2713aSLionel Sambuc     errs() << ProgramName
978f4a2713aSLionel Sambuc            << ": Not enough positional command line arguments specified!\n"
979f4a2713aSLionel Sambuc            << "Must specify at least " << NumPositionalRequired
980f4a2713aSLionel Sambuc            << " positional arguments: See: " << argv[0] << " -help\n";
981f4a2713aSLionel Sambuc 
982f4a2713aSLionel Sambuc     ErrorParsing = true;
983f4a2713aSLionel Sambuc   } else if (!HasUnlimitedPositionals &&
984f4a2713aSLionel Sambuc              PositionalVals.size() > PositionalOpts.size()) {
985*0a6a1f1dSLionel Sambuc     errs() << ProgramName << ": Too many positional arguments specified!\n"
986f4a2713aSLionel Sambuc            << "Can specify at most " << PositionalOpts.size()
987f4a2713aSLionel Sambuc            << " positional arguments: See: " << argv[0] << " -help\n";
988f4a2713aSLionel Sambuc     ErrorParsing = true;
989f4a2713aSLionel Sambuc 
990*0a6a1f1dSLionel Sambuc   } else if (!ConsumeAfterOpt) {
991f4a2713aSLionel Sambuc     // Positional args have already been handled if ConsumeAfter is specified.
992f4a2713aSLionel Sambuc     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
993f4a2713aSLionel Sambuc     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
994f4a2713aSLionel Sambuc       if (RequiresValue(PositionalOpts[i])) {
995f4a2713aSLionel Sambuc         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
996f4a2713aSLionel Sambuc                                 PositionalVals[ValNo].second);
997f4a2713aSLionel Sambuc         ValNo++;
998f4a2713aSLionel Sambuc         --NumPositionalRequired; // We fulfilled our duty...
999f4a2713aSLionel Sambuc       }
1000f4a2713aSLionel Sambuc 
1001f4a2713aSLionel Sambuc       // If we _can_ give this option more arguments, do so now, as long as we
1002f4a2713aSLionel Sambuc       // do not give it values that others need.  'Done' controls whether the
1003f4a2713aSLionel Sambuc       // option even _WANTS_ any more.
1004f4a2713aSLionel Sambuc       //
1005f4a2713aSLionel Sambuc       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1006f4a2713aSLionel Sambuc       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1007f4a2713aSLionel Sambuc         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1008f4a2713aSLionel Sambuc         case cl::Optional:
1009f4a2713aSLionel Sambuc           Done = true; // Optional arguments want _at most_ one value
1010f4a2713aSLionel Sambuc         // FALL THROUGH
1011f4a2713aSLionel Sambuc         case cl::ZeroOrMore: // Zero or more will take all they can get...
1012f4a2713aSLionel Sambuc         case cl::OneOrMore:  // One or more will take all they can get...
1013f4a2713aSLionel Sambuc           ProvidePositionalOption(PositionalOpts[i],
1014f4a2713aSLionel Sambuc                                   PositionalVals[ValNo].first,
1015f4a2713aSLionel Sambuc                                   PositionalVals[ValNo].second);
1016f4a2713aSLionel Sambuc           ValNo++;
1017f4a2713aSLionel Sambuc           break;
1018f4a2713aSLionel Sambuc         default:
1019f4a2713aSLionel Sambuc           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1020f4a2713aSLionel Sambuc                            "positional argument processing!");
1021f4a2713aSLionel Sambuc         }
1022f4a2713aSLionel Sambuc       }
1023f4a2713aSLionel Sambuc     }
1024f4a2713aSLionel Sambuc   } else {
1025f4a2713aSLionel Sambuc     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1026f4a2713aSLionel Sambuc     unsigned ValNo = 0;
1027f4a2713aSLionel Sambuc     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1028f4a2713aSLionel Sambuc       if (RequiresValue(PositionalOpts[j])) {
1029f4a2713aSLionel Sambuc         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1030f4a2713aSLionel Sambuc                                                 PositionalVals[ValNo].first,
1031f4a2713aSLionel Sambuc                                                 PositionalVals[ValNo].second);
1032f4a2713aSLionel Sambuc         ValNo++;
1033f4a2713aSLionel Sambuc       }
1034f4a2713aSLionel Sambuc 
1035f4a2713aSLionel Sambuc     // Handle the case where there is just one positional option, and it's
1036f4a2713aSLionel Sambuc     // optional.  In this case, we want to give JUST THE FIRST option to the
1037f4a2713aSLionel Sambuc     // positional option and keep the rest for the consume after.  The above
1038f4a2713aSLionel Sambuc     // loop would have assigned no values to positional options in this case.
1039f4a2713aSLionel Sambuc     //
1040f4a2713aSLionel Sambuc     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
1041f4a2713aSLionel Sambuc       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
1042f4a2713aSLionel Sambuc                                               PositionalVals[ValNo].first,
1043f4a2713aSLionel Sambuc                                               PositionalVals[ValNo].second);
1044f4a2713aSLionel Sambuc       ValNo++;
1045f4a2713aSLionel Sambuc     }
1046f4a2713aSLionel Sambuc 
1047f4a2713aSLionel Sambuc     // Handle over all of the rest of the arguments to the
1048f4a2713aSLionel Sambuc     // cl::ConsumeAfter command line option...
1049f4a2713aSLionel Sambuc     for (; ValNo != PositionalVals.size(); ++ValNo)
1050*0a6a1f1dSLionel Sambuc       ErrorParsing |=
1051*0a6a1f1dSLionel Sambuc           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1052f4a2713aSLionel Sambuc                                   PositionalVals[ValNo].second);
1053f4a2713aSLionel Sambuc   }
1054f4a2713aSLionel Sambuc 
1055f4a2713aSLionel Sambuc   // Loop over args and make sure all required args are specified!
1056*0a6a1f1dSLionel Sambuc   for (const auto &Opt : Opts) {
1057*0a6a1f1dSLionel Sambuc     switch (Opt.second->getNumOccurrencesFlag()) {
1058f4a2713aSLionel Sambuc     case Required:
1059f4a2713aSLionel Sambuc     case OneOrMore:
1060*0a6a1f1dSLionel Sambuc       if (Opt.second->getNumOccurrences() == 0) {
1061*0a6a1f1dSLionel Sambuc         Opt.second->error("must be specified at least once!");
1062f4a2713aSLionel Sambuc         ErrorParsing = true;
1063f4a2713aSLionel Sambuc       }
1064f4a2713aSLionel Sambuc     // Fall through
1065f4a2713aSLionel Sambuc     default:
1066f4a2713aSLionel Sambuc       break;
1067f4a2713aSLionel Sambuc     }
1068f4a2713aSLionel Sambuc   }
1069f4a2713aSLionel Sambuc 
1070f4a2713aSLionel Sambuc   // Now that we know if -debug is specified, we can use it.
1071f4a2713aSLionel Sambuc   // Note that if ReadResponseFiles == true, this must be done before the
1072f4a2713aSLionel Sambuc   // memory allocated for the expanded command line is free()d below.
1073f4a2713aSLionel Sambuc   DEBUG(dbgs() << "Args: ";
1074*0a6a1f1dSLionel Sambuc         for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1075*0a6a1f1dSLionel Sambuc         dbgs() << '\n';);
1076f4a2713aSLionel Sambuc 
1077f4a2713aSLionel Sambuc   // Free all of the memory allocated to the map.  Command line options may only
1078f4a2713aSLionel Sambuc   // be processed once!
1079f4a2713aSLionel Sambuc   Opts.clear();
1080f4a2713aSLionel Sambuc   PositionalOpts.clear();
1081f4a2713aSLionel Sambuc   MoreHelp->clear();
1082f4a2713aSLionel Sambuc 
1083f4a2713aSLionel Sambuc   // If we had an error processing our arguments, don't let the program execute
1084*0a6a1f1dSLionel Sambuc   if (ErrorParsing)
1085*0a6a1f1dSLionel Sambuc     exit(1);
1086f4a2713aSLionel Sambuc }
1087f4a2713aSLionel Sambuc 
1088f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1089f4a2713aSLionel Sambuc // Option Base class implementation
1090f4a2713aSLionel Sambuc //
1091f4a2713aSLionel Sambuc 
error(const Twine & Message,StringRef ArgName)1092f4a2713aSLionel Sambuc bool Option::error(const Twine &Message, StringRef ArgName) {
1093*0a6a1f1dSLionel Sambuc   if (!ArgName.data())
1094*0a6a1f1dSLionel Sambuc     ArgName = ArgStr;
1095f4a2713aSLionel Sambuc   if (ArgName.empty())
1096f4a2713aSLionel Sambuc     errs() << HelpStr; // Be nice for positional arguments
1097f4a2713aSLionel Sambuc   else
1098f4a2713aSLionel Sambuc     errs() << ProgramName << ": for the -" << ArgName;
1099f4a2713aSLionel Sambuc 
1100f4a2713aSLionel Sambuc   errs() << " option: " << Message << "\n";
1101f4a2713aSLionel Sambuc   return true;
1102f4a2713aSLionel Sambuc }
1103f4a2713aSLionel Sambuc 
addOccurrence(unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg)1104*0a6a1f1dSLionel Sambuc bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1105*0a6a1f1dSLionel Sambuc                            bool MultiArg) {
1106f4a2713aSLionel Sambuc   if (!MultiArg)
1107f4a2713aSLionel Sambuc     NumOccurrences++; // Increment the number of times we have been seen
1108f4a2713aSLionel Sambuc 
1109f4a2713aSLionel Sambuc   switch (getNumOccurrencesFlag()) {
1110f4a2713aSLionel Sambuc   case Optional:
1111f4a2713aSLionel Sambuc     if (NumOccurrences > 1)
1112f4a2713aSLionel Sambuc       return error("may only occur zero or one times!", ArgName);
1113f4a2713aSLionel Sambuc     break;
1114f4a2713aSLionel Sambuc   case Required:
1115f4a2713aSLionel Sambuc     if (NumOccurrences > 1)
1116f4a2713aSLionel Sambuc       return error("must occur exactly one time!", ArgName);
1117f4a2713aSLionel Sambuc   // Fall through
1118f4a2713aSLionel Sambuc   case OneOrMore:
1119f4a2713aSLionel Sambuc   case ZeroOrMore:
1120*0a6a1f1dSLionel Sambuc   case ConsumeAfter:
1121*0a6a1f1dSLionel Sambuc     break;
1122f4a2713aSLionel Sambuc   }
1123f4a2713aSLionel Sambuc 
1124f4a2713aSLionel Sambuc   return handleOccurrence(pos, ArgName, Value);
1125f4a2713aSLionel Sambuc }
1126f4a2713aSLionel Sambuc 
1127f4a2713aSLionel Sambuc // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1128f4a2713aSLionel Sambuc // has been specified yet.
1129f4a2713aSLionel Sambuc //
getValueStr(const Option & O,const char * DefaultMsg)1130f4a2713aSLionel Sambuc static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1131*0a6a1f1dSLionel Sambuc   if (O.ValueStr[0] == 0)
1132*0a6a1f1dSLionel Sambuc     return DefaultMsg;
1133f4a2713aSLionel Sambuc   return O.ValueStr;
1134f4a2713aSLionel Sambuc }
1135f4a2713aSLionel Sambuc 
1136f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1137f4a2713aSLionel Sambuc // cl::alias class implementation
1138f4a2713aSLionel Sambuc //
1139f4a2713aSLionel Sambuc 
1140f4a2713aSLionel Sambuc // Return the width of the option tag for printing...
getOptionWidth() const1141*0a6a1f1dSLionel Sambuc size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
1142f4a2713aSLionel Sambuc 
printHelpStr(StringRef HelpStr,size_t Indent,size_t FirstLineIndentedBy)1143f4a2713aSLionel Sambuc static void printHelpStr(StringRef HelpStr, size_t Indent,
1144f4a2713aSLionel Sambuc                          size_t FirstLineIndentedBy) {
1145f4a2713aSLionel Sambuc   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1146f4a2713aSLionel Sambuc   outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1147f4a2713aSLionel Sambuc   while (!Split.second.empty()) {
1148f4a2713aSLionel Sambuc     Split = Split.second.split('\n');
1149f4a2713aSLionel Sambuc     outs().indent(Indent) << Split.first << "\n";
1150f4a2713aSLionel Sambuc   }
1151f4a2713aSLionel Sambuc }
1152f4a2713aSLionel Sambuc 
1153f4a2713aSLionel Sambuc // Print out the option for the alias.
printOptionInfo(size_t GlobalWidth) const1154f4a2713aSLionel Sambuc void alias::printOptionInfo(size_t GlobalWidth) const {
1155f4a2713aSLionel Sambuc   outs() << "  -" << ArgStr;
1156f4a2713aSLionel Sambuc   printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1157f4a2713aSLionel Sambuc }
1158f4a2713aSLionel Sambuc 
1159f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1160f4a2713aSLionel Sambuc // Parser Implementation code...
1161f4a2713aSLionel Sambuc //
1162f4a2713aSLionel Sambuc 
1163f4a2713aSLionel Sambuc // basic_parser implementation
1164f4a2713aSLionel Sambuc //
1165f4a2713aSLionel Sambuc 
1166f4a2713aSLionel Sambuc // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1167f4a2713aSLionel Sambuc size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1168f4a2713aSLionel Sambuc   size_t Len = std::strlen(O.ArgStr);
1169f4a2713aSLionel Sambuc   if (const char *ValName = getValueName())
1170f4a2713aSLionel Sambuc     Len += std::strlen(getValueStr(O, ValName)) + 3;
1171f4a2713aSLionel Sambuc 
1172f4a2713aSLionel Sambuc   return Len + 6;
1173f4a2713aSLionel Sambuc }
1174f4a2713aSLionel Sambuc 
1175f4a2713aSLionel Sambuc // printOptionInfo - Print out information about this option.  The
1176f4a2713aSLionel Sambuc // to-be-maintained width is specified.
1177f4a2713aSLionel Sambuc //
printOptionInfo(const Option & O,size_t GlobalWidth) const1178f4a2713aSLionel Sambuc void basic_parser_impl::printOptionInfo(const Option &O,
1179f4a2713aSLionel Sambuc                                         size_t GlobalWidth) const {
1180f4a2713aSLionel Sambuc   outs() << "  -" << O.ArgStr;
1181f4a2713aSLionel Sambuc 
1182f4a2713aSLionel Sambuc   if (const char *ValName = getValueName())
1183f4a2713aSLionel Sambuc     outs() << "=<" << getValueStr(O, ValName) << '>';
1184f4a2713aSLionel Sambuc 
1185f4a2713aSLionel Sambuc   printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1186f4a2713aSLionel Sambuc }
1187f4a2713aSLionel Sambuc 
printOptionName(const Option & O,size_t GlobalWidth) const1188f4a2713aSLionel Sambuc void basic_parser_impl::printOptionName(const Option &O,
1189f4a2713aSLionel Sambuc                                         size_t GlobalWidth) const {
1190f4a2713aSLionel Sambuc   outs() << "  -" << O.ArgStr;
1191f4a2713aSLionel Sambuc   outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1192f4a2713aSLionel Sambuc }
1193f4a2713aSLionel Sambuc 
1194f4a2713aSLionel Sambuc // parser<bool> implementation
1195f4a2713aSLionel Sambuc //
parse(Option & O,StringRef ArgName,StringRef Arg,bool & Value)1196*0a6a1f1dSLionel Sambuc bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1197*0a6a1f1dSLionel Sambuc                          bool &Value) {
1198f4a2713aSLionel Sambuc   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1199f4a2713aSLionel Sambuc       Arg == "1") {
1200f4a2713aSLionel Sambuc     Value = true;
1201f4a2713aSLionel Sambuc     return false;
1202f4a2713aSLionel Sambuc   }
1203f4a2713aSLionel Sambuc 
1204f4a2713aSLionel Sambuc   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1205f4a2713aSLionel Sambuc     Value = false;
1206f4a2713aSLionel Sambuc     return false;
1207f4a2713aSLionel Sambuc   }
1208f4a2713aSLionel Sambuc   return O.error("'" + Arg +
1209f4a2713aSLionel Sambuc                  "' is invalid value for boolean argument! Try 0 or 1");
1210f4a2713aSLionel Sambuc }
1211f4a2713aSLionel Sambuc 
1212f4a2713aSLionel Sambuc // parser<boolOrDefault> implementation
1213f4a2713aSLionel Sambuc //
parse(Option & O,StringRef ArgName,StringRef Arg,boolOrDefault & Value)1214*0a6a1f1dSLionel Sambuc bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1215*0a6a1f1dSLionel Sambuc                                   boolOrDefault &Value) {
1216f4a2713aSLionel Sambuc   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1217f4a2713aSLionel Sambuc       Arg == "1") {
1218f4a2713aSLionel Sambuc     Value = BOU_TRUE;
1219f4a2713aSLionel Sambuc     return false;
1220f4a2713aSLionel Sambuc   }
1221f4a2713aSLionel Sambuc   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1222f4a2713aSLionel Sambuc     Value = BOU_FALSE;
1223f4a2713aSLionel Sambuc     return false;
1224f4a2713aSLionel Sambuc   }
1225f4a2713aSLionel Sambuc 
1226f4a2713aSLionel Sambuc   return O.error("'" + Arg +
1227f4a2713aSLionel Sambuc                  "' is invalid value for boolean argument! Try 0 or 1");
1228f4a2713aSLionel Sambuc }
1229f4a2713aSLionel Sambuc 
1230f4a2713aSLionel Sambuc // parser<int> implementation
1231f4a2713aSLionel Sambuc //
parse(Option & O,StringRef ArgName,StringRef Arg,int & Value)1232*0a6a1f1dSLionel Sambuc bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1233*0a6a1f1dSLionel Sambuc                         int &Value) {
1234f4a2713aSLionel Sambuc   if (Arg.getAsInteger(0, Value))
1235f4a2713aSLionel Sambuc     return O.error("'" + Arg + "' value invalid for integer argument!");
1236f4a2713aSLionel Sambuc   return false;
1237f4a2713aSLionel Sambuc }
1238f4a2713aSLionel Sambuc 
1239f4a2713aSLionel Sambuc // parser<unsigned> implementation
1240f4a2713aSLionel Sambuc //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned & Value)1241*0a6a1f1dSLionel Sambuc bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1242*0a6a1f1dSLionel Sambuc                              unsigned &Value) {
1243f4a2713aSLionel Sambuc 
1244f4a2713aSLionel Sambuc   if (Arg.getAsInteger(0, Value))
1245f4a2713aSLionel Sambuc     return O.error("'" + Arg + "' value invalid for uint argument!");
1246f4a2713aSLionel Sambuc   return false;
1247f4a2713aSLionel Sambuc }
1248f4a2713aSLionel Sambuc 
1249f4a2713aSLionel Sambuc // parser<unsigned long long> implementation
1250f4a2713aSLionel Sambuc //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long long & Value)1251f4a2713aSLionel Sambuc bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1252*0a6a1f1dSLionel Sambuc                                        StringRef Arg,
1253*0a6a1f1dSLionel Sambuc                                        unsigned long long &Value) {
1254f4a2713aSLionel Sambuc 
1255f4a2713aSLionel Sambuc   if (Arg.getAsInteger(0, Value))
1256f4a2713aSLionel Sambuc     return O.error("'" + Arg + "' value invalid for uint argument!");
1257f4a2713aSLionel Sambuc   return false;
1258f4a2713aSLionel Sambuc }
1259f4a2713aSLionel Sambuc 
1260f4a2713aSLionel Sambuc // parser<double>/parser<float> implementation
1261f4a2713aSLionel Sambuc //
parseDouble(Option & O,StringRef Arg,double & Value)1262f4a2713aSLionel Sambuc static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1263f4a2713aSLionel Sambuc   SmallString<32> TmpStr(Arg.begin(), Arg.end());
1264f4a2713aSLionel Sambuc   const char *ArgStart = TmpStr.c_str();
1265f4a2713aSLionel Sambuc   char *End;
1266f4a2713aSLionel Sambuc   Value = strtod(ArgStart, &End);
1267f4a2713aSLionel Sambuc   if (*End != 0)
1268f4a2713aSLionel Sambuc     return O.error("'" + Arg + "' value invalid for floating point argument!");
1269f4a2713aSLionel Sambuc   return false;
1270f4a2713aSLionel Sambuc }
1271f4a2713aSLionel Sambuc 
parse(Option & O,StringRef ArgName,StringRef Arg,double & Val)1272*0a6a1f1dSLionel Sambuc bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1273*0a6a1f1dSLionel Sambuc                            double &Val) {
1274f4a2713aSLionel Sambuc   return parseDouble(O, Arg, Val);
1275f4a2713aSLionel Sambuc }
1276f4a2713aSLionel Sambuc 
parse(Option & O,StringRef ArgName,StringRef Arg,float & Val)1277*0a6a1f1dSLionel Sambuc bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1278*0a6a1f1dSLionel Sambuc                           float &Val) {
1279f4a2713aSLionel Sambuc   double dVal;
1280f4a2713aSLionel Sambuc   if (parseDouble(O, Arg, dVal))
1281f4a2713aSLionel Sambuc     return true;
1282f4a2713aSLionel Sambuc   Val = (float)dVal;
1283f4a2713aSLionel Sambuc   return false;
1284f4a2713aSLionel Sambuc }
1285f4a2713aSLionel Sambuc 
1286f4a2713aSLionel Sambuc // generic_parser_base implementation
1287f4a2713aSLionel Sambuc //
1288f4a2713aSLionel Sambuc 
1289f4a2713aSLionel Sambuc // findOption - Return the option number corresponding to the specified
1290f4a2713aSLionel Sambuc // argument string.  If the option is not found, getNumOptions() is returned.
1291f4a2713aSLionel Sambuc //
findOption(const char * Name)1292f4a2713aSLionel Sambuc unsigned generic_parser_base::findOption(const char *Name) {
1293f4a2713aSLionel Sambuc   unsigned e = getNumOptions();
1294f4a2713aSLionel Sambuc 
1295f4a2713aSLionel Sambuc   for (unsigned i = 0; i != e; ++i) {
1296f4a2713aSLionel Sambuc     if (strcmp(getOption(i), Name) == 0)
1297f4a2713aSLionel Sambuc       return i;
1298f4a2713aSLionel Sambuc   }
1299f4a2713aSLionel Sambuc   return e;
1300f4a2713aSLionel Sambuc }
1301f4a2713aSLionel Sambuc 
1302f4a2713aSLionel Sambuc // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1303f4a2713aSLionel Sambuc size_t generic_parser_base::getOptionWidth(const Option &O) const {
1304f4a2713aSLionel Sambuc   if (O.hasArgStr()) {
1305f4a2713aSLionel Sambuc     size_t Size = std::strlen(O.ArgStr) + 6;
1306f4a2713aSLionel Sambuc     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1307f4a2713aSLionel Sambuc       Size = std::max(Size, std::strlen(getOption(i)) + 8);
1308f4a2713aSLionel Sambuc     return Size;
1309f4a2713aSLionel Sambuc   } else {
1310f4a2713aSLionel Sambuc     size_t BaseSize = 0;
1311f4a2713aSLionel Sambuc     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1312f4a2713aSLionel Sambuc       BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1313f4a2713aSLionel Sambuc     return BaseSize;
1314f4a2713aSLionel Sambuc   }
1315f4a2713aSLionel Sambuc }
1316f4a2713aSLionel Sambuc 
1317f4a2713aSLionel Sambuc // printOptionInfo - Print out information about this option.  The
1318f4a2713aSLionel Sambuc // to-be-maintained width is specified.
1319f4a2713aSLionel Sambuc //
printOptionInfo(const Option & O,size_t GlobalWidth) const1320f4a2713aSLionel Sambuc void generic_parser_base::printOptionInfo(const Option &O,
1321f4a2713aSLionel Sambuc                                           size_t GlobalWidth) const {
1322f4a2713aSLionel Sambuc   if (O.hasArgStr()) {
1323f4a2713aSLionel Sambuc     outs() << "  -" << O.ArgStr;
1324f4a2713aSLionel Sambuc     printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1325f4a2713aSLionel Sambuc 
1326f4a2713aSLionel Sambuc     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1327f4a2713aSLionel Sambuc       size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1328f4a2713aSLionel Sambuc       outs() << "    =" << getOption(i);
1329f4a2713aSLionel Sambuc       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
1330f4a2713aSLionel Sambuc     }
1331f4a2713aSLionel Sambuc   } else {
1332f4a2713aSLionel Sambuc     if (O.HelpStr[0])
1333f4a2713aSLionel Sambuc       outs() << "  " << O.HelpStr << '\n';
1334f4a2713aSLionel Sambuc     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1335f4a2713aSLionel Sambuc       const char *Option = getOption(i);
1336f4a2713aSLionel Sambuc       outs() << "    -" << Option;
1337f4a2713aSLionel Sambuc       printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1338f4a2713aSLionel Sambuc     }
1339f4a2713aSLionel Sambuc   }
1340f4a2713aSLionel Sambuc }
1341f4a2713aSLionel Sambuc 
1342f4a2713aSLionel Sambuc static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1343f4a2713aSLionel Sambuc 
1344f4a2713aSLionel Sambuc // printGenericOptionDiff - Print the value of this option and it's default.
1345f4a2713aSLionel Sambuc //
1346f4a2713aSLionel Sambuc // "Generic" options have each value mapped to a name.
printGenericOptionDiff(const Option & O,const GenericOptionValue & Value,const GenericOptionValue & Default,size_t GlobalWidth) const1347*0a6a1f1dSLionel Sambuc void generic_parser_base::printGenericOptionDiff(
1348*0a6a1f1dSLionel Sambuc     const Option &O, const GenericOptionValue &Value,
1349*0a6a1f1dSLionel Sambuc     const GenericOptionValue &Default, size_t GlobalWidth) const {
1350f4a2713aSLionel Sambuc   outs() << "  -" << O.ArgStr;
1351f4a2713aSLionel Sambuc   outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1352f4a2713aSLionel Sambuc 
1353f4a2713aSLionel Sambuc   unsigned NumOpts = getNumOptions();
1354f4a2713aSLionel Sambuc   for (unsigned i = 0; i != NumOpts; ++i) {
1355f4a2713aSLionel Sambuc     if (Value.compare(getOptionValue(i)))
1356f4a2713aSLionel Sambuc       continue;
1357f4a2713aSLionel Sambuc 
1358f4a2713aSLionel Sambuc     outs() << "= " << getOption(i);
1359f4a2713aSLionel Sambuc     size_t L = std::strlen(getOption(i));
1360f4a2713aSLionel Sambuc     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1361f4a2713aSLionel Sambuc     outs().indent(NumSpaces) << " (default: ";
1362f4a2713aSLionel Sambuc     for (unsigned j = 0; j != NumOpts; ++j) {
1363f4a2713aSLionel Sambuc       if (Default.compare(getOptionValue(j)))
1364f4a2713aSLionel Sambuc         continue;
1365f4a2713aSLionel Sambuc       outs() << getOption(j);
1366f4a2713aSLionel Sambuc       break;
1367f4a2713aSLionel Sambuc     }
1368f4a2713aSLionel Sambuc     outs() << ")\n";
1369f4a2713aSLionel Sambuc     return;
1370f4a2713aSLionel Sambuc   }
1371f4a2713aSLionel Sambuc   outs() << "= *unknown option value*\n";
1372f4a2713aSLionel Sambuc }
1373f4a2713aSLionel Sambuc 
1374f4a2713aSLionel Sambuc // printOptionDiff - Specializations for printing basic value types.
1375f4a2713aSLionel Sambuc //
1376f4a2713aSLionel Sambuc #define PRINT_OPT_DIFF(T)                                                      \
1377*0a6a1f1dSLionel Sambuc   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1378f4a2713aSLionel Sambuc                                   size_t GlobalWidth) const {                  \
1379f4a2713aSLionel Sambuc     printOptionName(O, GlobalWidth);                                           \
1380f4a2713aSLionel Sambuc     std::string Str;                                                           \
1381f4a2713aSLionel Sambuc     {                                                                          \
1382f4a2713aSLionel Sambuc       raw_string_ostream SS(Str);                                              \
1383f4a2713aSLionel Sambuc       SS << V;                                                                 \
1384f4a2713aSLionel Sambuc     }                                                                          \
1385f4a2713aSLionel Sambuc     outs() << "= " << Str;                                                     \
1386*0a6a1f1dSLionel Sambuc     size_t NumSpaces =                                                         \
1387*0a6a1f1dSLionel Sambuc         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
1388f4a2713aSLionel Sambuc     outs().indent(NumSpaces) << " (default: ";                                 \
1389f4a2713aSLionel Sambuc     if (D.hasValue())                                                          \
1390f4a2713aSLionel Sambuc       outs() << D.getValue();                                                  \
1391f4a2713aSLionel Sambuc     else                                                                       \
1392f4a2713aSLionel Sambuc       outs() << "*no default*";                                                \
1393f4a2713aSLionel Sambuc     outs() << ")\n";                                                           \
1394*0a6a1f1dSLionel Sambuc   }
1395f4a2713aSLionel Sambuc 
1396f4a2713aSLionel Sambuc PRINT_OPT_DIFF(bool)
PRINT_OPT_DIFF(boolOrDefault)1397f4a2713aSLionel Sambuc PRINT_OPT_DIFF(boolOrDefault)
1398f4a2713aSLionel Sambuc PRINT_OPT_DIFF(int)
1399f4a2713aSLionel Sambuc PRINT_OPT_DIFF(unsigned)
1400f4a2713aSLionel Sambuc PRINT_OPT_DIFF(unsigned long long)
1401f4a2713aSLionel Sambuc PRINT_OPT_DIFF(double)
1402f4a2713aSLionel Sambuc PRINT_OPT_DIFF(float)
1403f4a2713aSLionel Sambuc PRINT_OPT_DIFF(char)
1404f4a2713aSLionel Sambuc 
1405*0a6a1f1dSLionel Sambuc void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1406*0a6a1f1dSLionel Sambuc                                           OptionValue<std::string> D,
1407f4a2713aSLionel Sambuc                                           size_t GlobalWidth) const {
1408f4a2713aSLionel Sambuc   printOptionName(O, GlobalWidth);
1409f4a2713aSLionel Sambuc   outs() << "= " << V;
1410f4a2713aSLionel Sambuc   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1411f4a2713aSLionel Sambuc   outs().indent(NumSpaces) << " (default: ";
1412f4a2713aSLionel Sambuc   if (D.hasValue())
1413f4a2713aSLionel Sambuc     outs() << D.getValue();
1414f4a2713aSLionel Sambuc   else
1415f4a2713aSLionel Sambuc     outs() << "*no default*";
1416f4a2713aSLionel Sambuc   outs() << ")\n";
1417f4a2713aSLionel Sambuc }
1418f4a2713aSLionel Sambuc 
1419f4a2713aSLionel Sambuc // Print a placeholder for options that don't yet support printOptionDiff().
printOptionNoValue(const Option & O,size_t GlobalWidth) const1420*0a6a1f1dSLionel Sambuc void basic_parser_impl::printOptionNoValue(const Option &O,
1421*0a6a1f1dSLionel Sambuc                                            size_t GlobalWidth) const {
1422f4a2713aSLionel Sambuc   printOptionName(O, GlobalWidth);
1423f4a2713aSLionel Sambuc   outs() << "= *cannot print option value*\n";
1424f4a2713aSLionel Sambuc }
1425f4a2713aSLionel Sambuc 
1426f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1427f4a2713aSLionel Sambuc // -help and -help-hidden option implementation
1428f4a2713aSLionel Sambuc //
1429f4a2713aSLionel Sambuc 
OptNameCompare(const void * LHS,const void * RHS)1430f4a2713aSLionel Sambuc static int OptNameCompare(const void *LHS, const void *RHS) {
1431f4a2713aSLionel Sambuc   typedef std::pair<const char *, Option *> pair_ty;
1432f4a2713aSLionel Sambuc 
1433f4a2713aSLionel Sambuc   return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
1434f4a2713aSLionel Sambuc }
1435f4a2713aSLionel Sambuc 
1436f4a2713aSLionel Sambuc // Copy Options into a vector so we can sort them as we like.
sortOpts(StringMap<Option * > & OptMap,SmallVectorImpl<std::pair<const char *,Option * >> & Opts,bool ShowHidden)1437*0a6a1f1dSLionel Sambuc static void sortOpts(StringMap<Option *> &OptMap,
1438f4a2713aSLionel Sambuc                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1439f4a2713aSLionel Sambuc                      bool ShowHidden) {
1440f4a2713aSLionel Sambuc   SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1441f4a2713aSLionel Sambuc 
1442f4a2713aSLionel Sambuc   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1443f4a2713aSLionel Sambuc        I != E; ++I) {
1444f4a2713aSLionel Sambuc     // Ignore really-hidden options.
1445f4a2713aSLionel Sambuc     if (I->second->getOptionHiddenFlag() == ReallyHidden)
1446f4a2713aSLionel Sambuc       continue;
1447f4a2713aSLionel Sambuc 
1448f4a2713aSLionel Sambuc     // Unless showhidden is set, ignore hidden flags.
1449f4a2713aSLionel Sambuc     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1450f4a2713aSLionel Sambuc       continue;
1451f4a2713aSLionel Sambuc 
1452f4a2713aSLionel Sambuc     // If we've already seen this option, don't add it to the list again.
1453*0a6a1f1dSLionel Sambuc     if (!OptionSet.insert(I->second).second)
1454f4a2713aSLionel Sambuc       continue;
1455f4a2713aSLionel Sambuc 
1456*0a6a1f1dSLionel Sambuc     Opts.push_back(
1457*0a6a1f1dSLionel Sambuc         std::pair<const char *, Option *>(I->getKey().data(), I->second));
1458f4a2713aSLionel Sambuc   }
1459f4a2713aSLionel Sambuc 
1460f4a2713aSLionel Sambuc   // Sort the options list alphabetically.
1461f4a2713aSLionel Sambuc   qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1462f4a2713aSLionel Sambuc }
1463f4a2713aSLionel Sambuc 
1464f4a2713aSLionel Sambuc namespace {
1465f4a2713aSLionel Sambuc 
1466f4a2713aSLionel Sambuc class HelpPrinter {
1467f4a2713aSLionel Sambuc protected:
1468f4a2713aSLionel Sambuc   const bool ShowHidden;
1469*0a6a1f1dSLionel Sambuc   typedef SmallVector<std::pair<const char *, Option *>, 128>
1470*0a6a1f1dSLionel Sambuc       StrOptionPairVector;
1471f4a2713aSLionel Sambuc   // Print the options. Opts is assumed to be alphabetically sorted.
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)1472f4a2713aSLionel Sambuc   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1473f4a2713aSLionel Sambuc     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1474f4a2713aSLionel Sambuc       Opts[i].second->printOptionInfo(MaxArgLen);
1475f4a2713aSLionel Sambuc   }
1476f4a2713aSLionel Sambuc 
1477f4a2713aSLionel Sambuc public:
HelpPrinter(bool showHidden)1478f4a2713aSLionel Sambuc   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
~HelpPrinter()1479f4a2713aSLionel Sambuc   virtual ~HelpPrinter() {}
1480f4a2713aSLionel Sambuc 
1481f4a2713aSLionel Sambuc   // Invoke the printer.
operator =(bool Value)1482f4a2713aSLionel Sambuc   void operator=(bool Value) {
1483*0a6a1f1dSLionel Sambuc     if (Value == false)
1484*0a6a1f1dSLionel Sambuc       return;
1485f4a2713aSLionel Sambuc 
1486f4a2713aSLionel Sambuc     // Get all the options.
1487f4a2713aSLionel Sambuc     SmallVector<Option *, 4> PositionalOpts;
1488f4a2713aSLionel Sambuc     SmallVector<Option *, 4> SinkOpts;
1489f4a2713aSLionel Sambuc     StringMap<Option *> OptMap;
1490f4a2713aSLionel Sambuc     GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1491f4a2713aSLionel Sambuc 
1492f4a2713aSLionel Sambuc     StrOptionPairVector Opts;
1493f4a2713aSLionel Sambuc     sortOpts(OptMap, Opts, ShowHidden);
1494f4a2713aSLionel Sambuc 
1495f4a2713aSLionel Sambuc     if (ProgramOverview)
1496f4a2713aSLionel Sambuc       outs() << "OVERVIEW: " << ProgramOverview << "\n";
1497f4a2713aSLionel Sambuc 
1498f4a2713aSLionel Sambuc     outs() << "USAGE: " << ProgramName << " [options]";
1499f4a2713aSLionel Sambuc 
1500f4a2713aSLionel Sambuc     // Print out the positional options.
1501*0a6a1f1dSLionel Sambuc     Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
1502f4a2713aSLionel Sambuc     if (!PositionalOpts.empty() &&
1503f4a2713aSLionel Sambuc         PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1504f4a2713aSLionel Sambuc       CAOpt = PositionalOpts[0];
1505f4a2713aSLionel Sambuc 
1506*0a6a1f1dSLionel Sambuc     for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
1507f4a2713aSLionel Sambuc       if (PositionalOpts[i]->ArgStr[0])
1508f4a2713aSLionel Sambuc         outs() << " --" << PositionalOpts[i]->ArgStr;
1509f4a2713aSLionel Sambuc       outs() << " " << PositionalOpts[i]->HelpStr;
1510f4a2713aSLionel Sambuc     }
1511f4a2713aSLionel Sambuc 
1512f4a2713aSLionel Sambuc     // Print the consume after option info if it exists...
1513*0a6a1f1dSLionel Sambuc     if (CAOpt)
1514*0a6a1f1dSLionel Sambuc       outs() << " " << CAOpt->HelpStr;
1515f4a2713aSLionel Sambuc 
1516f4a2713aSLionel Sambuc     outs() << "\n\n";
1517f4a2713aSLionel Sambuc 
1518f4a2713aSLionel Sambuc     // Compute the maximum argument length...
1519f4a2713aSLionel Sambuc     size_t MaxArgLen = 0;
1520f4a2713aSLionel Sambuc     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1521f4a2713aSLionel Sambuc       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1522f4a2713aSLionel Sambuc 
1523f4a2713aSLionel Sambuc     outs() << "OPTIONS:\n";
1524f4a2713aSLionel Sambuc     printOptions(Opts, MaxArgLen);
1525f4a2713aSLionel Sambuc 
1526f4a2713aSLionel Sambuc     // Print any extra help the user has declared.
1527f4a2713aSLionel Sambuc     for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1528f4a2713aSLionel Sambuc                                              E = MoreHelp->end();
1529f4a2713aSLionel Sambuc          I != E; ++I)
1530f4a2713aSLionel Sambuc       outs() << *I;
1531f4a2713aSLionel Sambuc     MoreHelp->clear();
1532f4a2713aSLionel Sambuc 
1533f4a2713aSLionel Sambuc     // Halt the program since help information was printed
1534*0a6a1f1dSLionel Sambuc     exit(0);
1535f4a2713aSLionel Sambuc   }
1536f4a2713aSLionel Sambuc };
1537f4a2713aSLionel Sambuc 
1538f4a2713aSLionel Sambuc class CategorizedHelpPrinter : public HelpPrinter {
1539f4a2713aSLionel Sambuc public:
CategorizedHelpPrinter(bool showHidden)1540f4a2713aSLionel Sambuc   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1541f4a2713aSLionel Sambuc 
1542f4a2713aSLionel Sambuc   // Helper function for printOptions().
1543f4a2713aSLionel Sambuc   // It shall return true if A's name should be lexographically
1544f4a2713aSLionel Sambuc   // ordered before B's name. It returns false otherwise.
OptionCategoryCompare(OptionCategory * A,OptionCategory * B)1545f4a2713aSLionel Sambuc   static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1546*0a6a1f1dSLionel Sambuc     return strcmp(A->getName(), B->getName()) < 0;
1547f4a2713aSLionel Sambuc   }
1548f4a2713aSLionel Sambuc 
1549f4a2713aSLionel Sambuc   // Make sure we inherit our base class's operator=()
1550f4a2713aSLionel Sambuc   using HelpPrinter::operator=;
1551f4a2713aSLionel Sambuc 
1552f4a2713aSLionel Sambuc protected:
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)1553*0a6a1f1dSLionel Sambuc   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1554f4a2713aSLionel Sambuc     std::vector<OptionCategory *> SortedCategories;
1555f4a2713aSLionel Sambuc     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1556f4a2713aSLionel Sambuc 
1557*0a6a1f1dSLionel Sambuc     // Collect registered option categories into vector in preparation for
1558f4a2713aSLionel Sambuc     // sorting.
1559f4a2713aSLionel Sambuc     for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1560f4a2713aSLionel Sambuc                                       E = RegisteredOptionCategories->end();
1561*0a6a1f1dSLionel Sambuc          I != E; ++I) {
1562f4a2713aSLionel Sambuc       SortedCategories.push_back(*I);
1563*0a6a1f1dSLionel Sambuc     }
1564f4a2713aSLionel Sambuc 
1565f4a2713aSLionel Sambuc     // Sort the different option categories alphabetically.
1566f4a2713aSLionel Sambuc     assert(SortedCategories.size() > 0 && "No option categories registered!");
1567f4a2713aSLionel Sambuc     std::sort(SortedCategories.begin(), SortedCategories.end(),
1568f4a2713aSLionel Sambuc               OptionCategoryCompare);
1569f4a2713aSLionel Sambuc 
1570f4a2713aSLionel Sambuc     // Create map to empty vectors.
1571f4a2713aSLionel Sambuc     for (std::vector<OptionCategory *>::const_iterator
1572f4a2713aSLionel Sambuc              I = SortedCategories.begin(),
1573f4a2713aSLionel Sambuc              E = SortedCategories.end();
1574f4a2713aSLionel Sambuc          I != E; ++I)
1575f4a2713aSLionel Sambuc       CategorizedOptions[*I] = std::vector<Option *>();
1576f4a2713aSLionel Sambuc 
1577f4a2713aSLionel Sambuc     // Walk through pre-sorted options and assign into categories.
1578f4a2713aSLionel Sambuc     // Because the options are already alphabetically sorted the
1579f4a2713aSLionel Sambuc     // options within categories will also be alphabetically sorted.
1580f4a2713aSLionel Sambuc     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1581f4a2713aSLionel Sambuc       Option *Opt = Opts[I].second;
1582f4a2713aSLionel Sambuc       assert(CategorizedOptions.count(Opt->Category) > 0 &&
1583f4a2713aSLionel Sambuc              "Option has an unregistered category");
1584f4a2713aSLionel Sambuc       CategorizedOptions[Opt->Category].push_back(Opt);
1585f4a2713aSLionel Sambuc     }
1586f4a2713aSLionel Sambuc 
1587f4a2713aSLionel Sambuc     // Now do printing.
1588f4a2713aSLionel Sambuc     for (std::vector<OptionCategory *>::const_iterator
1589f4a2713aSLionel Sambuc              Category = SortedCategories.begin(),
1590f4a2713aSLionel Sambuc              E = SortedCategories.end();
1591f4a2713aSLionel Sambuc          Category != E; ++Category) {
1592f4a2713aSLionel Sambuc       // Hide empty categories for -help, but show for -help-hidden.
1593f4a2713aSLionel Sambuc       bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1594f4a2713aSLionel Sambuc       if (!ShowHidden && IsEmptyCategory)
1595f4a2713aSLionel Sambuc         continue;
1596f4a2713aSLionel Sambuc 
1597f4a2713aSLionel Sambuc       // Print category information.
1598f4a2713aSLionel Sambuc       outs() << "\n";
1599f4a2713aSLionel Sambuc       outs() << (*Category)->getName() << ":\n";
1600f4a2713aSLionel Sambuc 
1601f4a2713aSLionel Sambuc       // Check if description is set.
1602*0a6a1f1dSLionel Sambuc       if ((*Category)->getDescription() != nullptr)
1603f4a2713aSLionel Sambuc         outs() << (*Category)->getDescription() << "\n\n";
1604f4a2713aSLionel Sambuc       else
1605f4a2713aSLionel Sambuc         outs() << "\n";
1606f4a2713aSLionel Sambuc 
1607f4a2713aSLionel Sambuc       // When using -help-hidden explicitly state if the category has no
1608f4a2713aSLionel Sambuc       // options associated with it.
1609f4a2713aSLionel Sambuc       if (IsEmptyCategory) {
1610f4a2713aSLionel Sambuc         outs() << "  This option category has no options.\n";
1611f4a2713aSLionel Sambuc         continue;
1612f4a2713aSLionel Sambuc       }
1613f4a2713aSLionel Sambuc       // Loop over the options in the category and print.
1614f4a2713aSLionel Sambuc       for (std::vector<Option *>::const_iterator
1615f4a2713aSLionel Sambuc                Opt = CategorizedOptions[*Category].begin(),
1616f4a2713aSLionel Sambuc                E = CategorizedOptions[*Category].end();
1617f4a2713aSLionel Sambuc            Opt != E; ++Opt)
1618f4a2713aSLionel Sambuc         (*Opt)->printOptionInfo(MaxArgLen);
1619f4a2713aSLionel Sambuc     }
1620f4a2713aSLionel Sambuc   }
1621f4a2713aSLionel Sambuc };
1622f4a2713aSLionel Sambuc 
1623f4a2713aSLionel Sambuc // This wraps the Uncategorizing and Categorizing printers and decides
1624f4a2713aSLionel Sambuc // at run time which should be invoked.
1625f4a2713aSLionel Sambuc class HelpPrinterWrapper {
1626f4a2713aSLionel Sambuc private:
1627f4a2713aSLionel Sambuc   HelpPrinter &UncategorizedPrinter;
1628f4a2713aSLionel Sambuc   CategorizedHelpPrinter &CategorizedPrinter;
1629f4a2713aSLionel Sambuc 
1630f4a2713aSLionel Sambuc public:
HelpPrinterWrapper(HelpPrinter & UncategorizedPrinter,CategorizedHelpPrinter & CategorizedPrinter)1631f4a2713aSLionel Sambuc   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1632*0a6a1f1dSLionel Sambuc                               CategorizedHelpPrinter &CategorizedPrinter)
1633*0a6a1f1dSLionel Sambuc       : UncategorizedPrinter(UncategorizedPrinter),
1634f4a2713aSLionel Sambuc         CategorizedPrinter(CategorizedPrinter) {}
1635f4a2713aSLionel Sambuc 
1636f4a2713aSLionel Sambuc   // Invoke the printer.
1637f4a2713aSLionel Sambuc   void operator=(bool Value);
1638f4a2713aSLionel Sambuc };
1639f4a2713aSLionel Sambuc 
1640f4a2713aSLionel Sambuc } // End anonymous namespace
1641f4a2713aSLionel Sambuc 
1642f4a2713aSLionel Sambuc // Declare the four HelpPrinter instances that are used to print out help, or
1643f4a2713aSLionel Sambuc // help-hidden as an uncategorized list or in categories.
1644f4a2713aSLionel Sambuc static HelpPrinter UncategorizedNormalPrinter(false);
1645f4a2713aSLionel Sambuc static HelpPrinter UncategorizedHiddenPrinter(true);
1646f4a2713aSLionel Sambuc static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1647f4a2713aSLionel Sambuc static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1648f4a2713aSLionel Sambuc 
1649f4a2713aSLionel Sambuc // Declare HelpPrinter wrappers that will decide whether or not to invoke
1650f4a2713aSLionel Sambuc // a categorizing help printer
1651f4a2713aSLionel Sambuc static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1652f4a2713aSLionel Sambuc                                                CategorizedNormalPrinter);
1653f4a2713aSLionel Sambuc static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1654f4a2713aSLionel Sambuc                                                CategorizedHiddenPrinter);
1655f4a2713aSLionel Sambuc 
1656f4a2713aSLionel Sambuc // Define uncategorized help printers.
1657f4a2713aSLionel Sambuc // -help-list is hidden by default because if Option categories are being used
1658f4a2713aSLionel Sambuc // then -help behaves the same as -help-list.
1659*0a6a1f1dSLionel Sambuc static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1660*0a6a1f1dSLionel Sambuc     "help-list",
1661f4a2713aSLionel Sambuc     cl::desc("Display list of available options (-help-list-hidden for more)"),
1662f4a2713aSLionel Sambuc     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1663f4a2713aSLionel Sambuc 
1664f4a2713aSLionel Sambuc static cl::opt<HelpPrinter, true, parser<bool>>
1665*0a6a1f1dSLionel Sambuc     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1666*0a6a1f1dSLionel Sambuc           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1667*0a6a1f1dSLionel Sambuc           cl::ValueDisallowed);
1668f4a2713aSLionel Sambuc 
1669f4a2713aSLionel Sambuc // Define uncategorized/categorized help printers. These printers change their
1670f4a2713aSLionel Sambuc // behaviour at runtime depending on whether one or more Option categories have
1671f4a2713aSLionel Sambuc // been declared.
1672f4a2713aSLionel Sambuc static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1673f4a2713aSLionel Sambuc     HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1674f4a2713aSLionel Sambuc         cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1675f4a2713aSLionel Sambuc 
1676f4a2713aSLionel Sambuc static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1677f4a2713aSLionel Sambuc     HHOp("help-hidden", cl::desc("Display all available options"),
1678f4a2713aSLionel Sambuc          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1679f4a2713aSLionel Sambuc 
1680*0a6a1f1dSLionel Sambuc static cl::opt<bool> PrintOptions(
1681*0a6a1f1dSLionel Sambuc     "print-options",
1682f4a2713aSLionel Sambuc     cl::desc("Print non-default options after command line parsing"),
1683f4a2713aSLionel Sambuc     cl::Hidden, cl::init(false));
1684f4a2713aSLionel Sambuc 
1685*0a6a1f1dSLionel Sambuc static cl::opt<bool> PrintAllOptions(
1686*0a6a1f1dSLionel Sambuc     "print-all-options",
1687*0a6a1f1dSLionel Sambuc     cl::desc("Print all option values after command line parsing"), cl::Hidden,
1688*0a6a1f1dSLionel Sambuc     cl::init(false));
1689f4a2713aSLionel Sambuc 
operator =(bool Value)1690f4a2713aSLionel Sambuc void HelpPrinterWrapper::operator=(bool Value) {
1691f4a2713aSLionel Sambuc   if (Value == false)
1692f4a2713aSLionel Sambuc     return;
1693f4a2713aSLionel Sambuc 
1694f4a2713aSLionel Sambuc   // Decide which printer to invoke. If more than one option category is
1695f4a2713aSLionel Sambuc   // registered then it is useful to show the categorized help instead of
1696f4a2713aSLionel Sambuc   // uncategorized help.
1697f4a2713aSLionel Sambuc   if (RegisteredOptionCategories->size() > 1) {
1698f4a2713aSLionel Sambuc     // unhide -help-list option so user can have uncategorized output if they
1699f4a2713aSLionel Sambuc     // want it.
1700f4a2713aSLionel Sambuc     HLOp.setHiddenFlag(NotHidden);
1701f4a2713aSLionel Sambuc 
1702f4a2713aSLionel Sambuc     CategorizedPrinter = true; // Invoke categorized printer
1703*0a6a1f1dSLionel Sambuc   } else
1704f4a2713aSLionel Sambuc     UncategorizedPrinter = true; // Invoke uncategorized printer
1705f4a2713aSLionel Sambuc }
1706f4a2713aSLionel Sambuc 
1707f4a2713aSLionel Sambuc // Print the value of each option.
PrintOptionValues()1708f4a2713aSLionel Sambuc void cl::PrintOptionValues() {
1709*0a6a1f1dSLionel Sambuc   if (!PrintOptions && !PrintAllOptions)
1710*0a6a1f1dSLionel Sambuc     return;
1711f4a2713aSLionel Sambuc 
1712f4a2713aSLionel Sambuc   // Get all the options.
1713f4a2713aSLionel Sambuc   SmallVector<Option *, 4> PositionalOpts;
1714f4a2713aSLionel Sambuc   SmallVector<Option *, 4> SinkOpts;
1715f4a2713aSLionel Sambuc   StringMap<Option *> OptMap;
1716f4a2713aSLionel Sambuc   GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1717f4a2713aSLionel Sambuc 
1718f4a2713aSLionel Sambuc   SmallVector<std::pair<const char *, Option *>, 128> Opts;
1719f4a2713aSLionel Sambuc   sortOpts(OptMap, Opts, /*ShowHidden*/ true);
1720f4a2713aSLionel Sambuc 
1721f4a2713aSLionel Sambuc   // Compute the maximum argument length...
1722f4a2713aSLionel Sambuc   size_t MaxArgLen = 0;
1723f4a2713aSLionel Sambuc   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1724f4a2713aSLionel Sambuc     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1725f4a2713aSLionel Sambuc 
1726f4a2713aSLionel Sambuc   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1727f4a2713aSLionel Sambuc     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1728f4a2713aSLionel Sambuc }
1729f4a2713aSLionel Sambuc 
1730*0a6a1f1dSLionel Sambuc static void (*OverrideVersionPrinter)() = nullptr;
1731f4a2713aSLionel Sambuc 
1732*0a6a1f1dSLionel Sambuc static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1733f4a2713aSLionel Sambuc 
1734f4a2713aSLionel Sambuc namespace {
1735f4a2713aSLionel Sambuc class VersionPrinter {
1736f4a2713aSLionel Sambuc public:
print()1737f4a2713aSLionel Sambuc   void print() {
1738f4a2713aSLionel Sambuc     raw_ostream &OS = outs();
1739f4a2713aSLionel Sambuc     OS << "LLVM (http://llvm.org/):\n"
1740f4a2713aSLionel Sambuc        << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1741f4a2713aSLionel Sambuc #ifdef LLVM_VERSION_INFO
1742*0a6a1f1dSLionel Sambuc     OS << " " << LLVM_VERSION_INFO;
1743f4a2713aSLionel Sambuc #endif
1744f4a2713aSLionel Sambuc     OS << "\n  ";
1745f4a2713aSLionel Sambuc #ifndef __OPTIMIZE__
1746f4a2713aSLionel Sambuc     OS << "DEBUG build";
1747f4a2713aSLionel Sambuc #else
1748f4a2713aSLionel Sambuc     OS << "Optimized build";
1749f4a2713aSLionel Sambuc #endif
1750f4a2713aSLionel Sambuc #ifndef NDEBUG
1751f4a2713aSLionel Sambuc     OS << " with assertions";
1752f4a2713aSLionel Sambuc #endif
1753f4a2713aSLionel Sambuc     std::string CPU = sys::getHostCPUName();
1754*0a6a1f1dSLionel Sambuc     if (CPU == "generic")
1755*0a6a1f1dSLionel Sambuc       CPU = "(unknown)";
1756f4a2713aSLionel Sambuc     OS << ".\n"
1757f4a2713aSLionel Sambuc #if (ENABLE_TIMESTAMPS == 1)
1758f4a2713aSLionel Sambuc        << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
1759f4a2713aSLionel Sambuc #endif
1760f4a2713aSLionel Sambuc        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
1761f4a2713aSLionel Sambuc        << "  Host CPU: " << CPU << '\n';
1762f4a2713aSLionel Sambuc   }
operator =(bool OptionWasSpecified)1763f4a2713aSLionel Sambuc   void operator=(bool OptionWasSpecified) {
1764*0a6a1f1dSLionel Sambuc     if (!OptionWasSpecified)
1765*0a6a1f1dSLionel Sambuc       return;
1766f4a2713aSLionel Sambuc 
1767*0a6a1f1dSLionel Sambuc     if (OverrideVersionPrinter != nullptr) {
1768f4a2713aSLionel Sambuc       (*OverrideVersionPrinter)();
1769*0a6a1f1dSLionel Sambuc       exit(0);
1770f4a2713aSLionel Sambuc     }
1771f4a2713aSLionel Sambuc     print();
1772f4a2713aSLionel Sambuc 
1773f4a2713aSLionel Sambuc     // Iterate over any registered extra printers and call them to add further
1774f4a2713aSLionel Sambuc     // information.
1775*0a6a1f1dSLionel Sambuc     if (ExtraVersionPrinters != nullptr) {
1776f4a2713aSLionel Sambuc       outs() << '\n';
1777f4a2713aSLionel Sambuc       for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1778f4a2713aSLionel Sambuc                                              E = ExtraVersionPrinters->end();
1779f4a2713aSLionel Sambuc            I != E; ++I)
1780f4a2713aSLionel Sambuc         (*I)();
1781f4a2713aSLionel Sambuc     }
1782f4a2713aSLionel Sambuc 
1783*0a6a1f1dSLionel Sambuc     exit(0);
1784f4a2713aSLionel Sambuc   }
1785f4a2713aSLionel Sambuc };
1786f4a2713aSLionel Sambuc } // End anonymous namespace
1787f4a2713aSLionel Sambuc 
1788f4a2713aSLionel Sambuc // Define the --version option that prints out the LLVM version for the tool
1789f4a2713aSLionel Sambuc static VersionPrinter VersionPrinterInstance;
1790f4a2713aSLionel Sambuc 
1791f4a2713aSLionel Sambuc static cl::opt<VersionPrinter, true, parser<bool>>
1792f4a2713aSLionel Sambuc     VersOp("version", cl::desc("Display the version of this program"),
1793f4a2713aSLionel Sambuc            cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1794f4a2713aSLionel Sambuc 
1795f4a2713aSLionel Sambuc // Utility function for printing the help message.
PrintHelpMessage(bool Hidden,bool Categorized)1796f4a2713aSLionel Sambuc void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1797f4a2713aSLionel Sambuc   // This looks weird, but it actually prints the help message. The Printers are
1798f4a2713aSLionel Sambuc   // types of HelpPrinter and the help gets printed when its operator= is
1799f4a2713aSLionel Sambuc   // invoked. That's because the "normal" usages of the help printer is to be
1800f4a2713aSLionel Sambuc   // assigned true/false depending on whether -help or -help-hidden was given or
1801f4a2713aSLionel Sambuc   // not.  Since we're circumventing that we have to make it look like -help or
1802f4a2713aSLionel Sambuc   // -help-hidden were given, so we assign true.
1803f4a2713aSLionel Sambuc 
1804f4a2713aSLionel Sambuc   if (!Hidden && !Categorized)
1805f4a2713aSLionel Sambuc     UncategorizedNormalPrinter = true;
1806f4a2713aSLionel Sambuc   else if (!Hidden && Categorized)
1807f4a2713aSLionel Sambuc     CategorizedNormalPrinter = true;
1808f4a2713aSLionel Sambuc   else if (Hidden && !Categorized)
1809f4a2713aSLionel Sambuc     UncategorizedHiddenPrinter = true;
1810f4a2713aSLionel Sambuc   else
1811f4a2713aSLionel Sambuc     CategorizedHiddenPrinter = true;
1812f4a2713aSLionel Sambuc }
1813f4a2713aSLionel Sambuc 
1814f4a2713aSLionel Sambuc /// Utility function for printing version number.
PrintVersionMessage()1815*0a6a1f1dSLionel Sambuc void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1816f4a2713aSLionel Sambuc 
SetVersionPrinter(void (* func)())1817*0a6a1f1dSLionel Sambuc void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1818f4a2713aSLionel Sambuc 
AddExtraVersionPrinter(void (* func)())1819f4a2713aSLionel Sambuc void cl::AddExtraVersionPrinter(void (*func)()) {
1820*0a6a1f1dSLionel Sambuc   if (!ExtraVersionPrinters)
1821f4a2713aSLionel Sambuc     ExtraVersionPrinters = new std::vector<void (*)()>;
1822f4a2713aSLionel Sambuc 
1823f4a2713aSLionel Sambuc   ExtraVersionPrinters->push_back(func);
1824f4a2713aSLionel Sambuc }
1825f4a2713aSLionel Sambuc 
getRegisteredOptions(StringMap<Option * > & Map)1826*0a6a1f1dSLionel Sambuc void cl::getRegisteredOptions(StringMap<Option *> &Map) {
1827f4a2713aSLionel Sambuc   // Get all the options.
1828f4a2713aSLionel Sambuc   SmallVector<Option *, 4> PositionalOpts; // NOT USED
1829f4a2713aSLionel Sambuc   SmallVector<Option *, 4> SinkOpts; // NOT USED
1830f4a2713aSLionel Sambuc   assert(Map.size() == 0 && "StringMap must be empty");
1831f4a2713aSLionel Sambuc   GetOptionInfo(PositionalOpts, SinkOpts, Map);
1832f4a2713aSLionel Sambuc   return;
1833f4a2713aSLionel Sambuc }
1834*0a6a1f1dSLionel Sambuc 
LLVMParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)1835*0a6a1f1dSLionel Sambuc void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1836*0a6a1f1dSLionel Sambuc                                  const char *Overview) {
1837*0a6a1f1dSLionel Sambuc   llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1838*0a6a1f1dSLionel Sambuc }
1839