blob: 50b43b1678ca7e6a3faec6c569cfaf848a3e1bf5 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Args.cpp ------------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <getopt.h>
Eli Friedman27cd8892010-06-09 10:59:23 +000012#include <cstdlib>
Chris Lattner24943d22010-06-08 16:52:24 +000013// C++ Includes
14// Other libraries and framework includes
15// Project includes
Jim Ingham84cdc152010-06-15 19:49:27 +000016#include "lldb/Interpreter/Args.h"
Greg Clayton3182eff2011-06-23 21:22:24 +000017#include "lldb/Core/FormatManager.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Stream.h"
19#include "lldb/Core/StreamFile.h"
20#include "lldb/Core/StreamString.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000021#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022#include "lldb/Interpreter/CommandReturnObject.h"
23
Chris Lattner24943d22010-06-08 16:52:24 +000024using namespace lldb;
25using namespace lldb_private;
26
Chris Lattner24943d22010-06-08 16:52:24 +000027//----------------------------------------------------------------------
28// Args constructor
29//----------------------------------------------------------------------
30Args::Args (const char *command) :
31 m_args(),
Greg Claytonb72d0f02011-04-12 05:54:46 +000032 m_argv(),
33 m_args_quote_char()
Chris Lattner24943d22010-06-08 16:52:24 +000034{
Greg Clayton928d1302010-12-19 03:41:24 +000035 if (command)
36 SetCommandString (command);
Chris Lattner24943d22010-06-08 16:52:24 +000037}
38
39
40Args::Args (const char *command, size_t len) :
41 m_args(),
Greg Claytonb72d0f02011-04-12 05:54:46 +000042 m_argv(),
43 m_args_quote_char()
Chris Lattner24943d22010-06-08 16:52:24 +000044{
Greg Clayton928d1302010-12-19 03:41:24 +000045 if (command && len)
46 SetCommandString (command, len);
Chris Lattner24943d22010-06-08 16:52:24 +000047}
48
Chris Lattner24943d22010-06-08 16:52:24 +000049//----------------------------------------------------------------------
Greg Claytonb72d0f02011-04-12 05:54:46 +000050// We have to be very careful on the copy constructor of this class
51// to make sure we copy all of the string values, but we can't copy the
52// rhs.m_argv into m_argv since it will point to the "const char *" c
53// strings in rhs.m_args. We need to copy the string list and update our
54// own m_argv appropriately.
55//----------------------------------------------------------------------
56Args::Args (const Args &rhs) :
57 m_args (rhs.m_args),
58 m_argv (),
59 m_args_quote_char(rhs.m_args_quote_char)
60{
61 UpdateArgvFromArgs();
62}
63
64//----------------------------------------------------------------------
65// We have to be very careful on the copy constructor of this class
66// to make sure we copy all of the string values, but we can't copy the
67// rhs.m_argv into m_argv since it will point to the "const char *" c
68// strings in rhs.m_args. We need to copy the string list and update our
69// own m_argv appropriately.
70//----------------------------------------------------------------------
71const Args &
72Args::operator= (const Args &rhs)
73{
74 // Make sure we aren't assigning to self
75 if (this != &rhs)
76 {
77 m_args = rhs.m_args;
78 m_args_quote_char = rhs.m_args_quote_char;
79 UpdateArgvFromArgs();
80 }
81 return *this;
82}
83
84//----------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +000085// Destructor
86//----------------------------------------------------------------------
87Args::~Args ()
88{
89}
90
91void
92Args::Dump (Stream *s)
93{
94// int argc = GetArgumentCount();
95//
96// arg_sstr_collection::const_iterator pos, begin = m_args.begin(), end = m_args.end();
97// for (pos = m_args.begin(); pos != end; ++pos)
98// {
99// s->Indent();
100// s->Printf("args[%zu]=%s\n", std::distance(begin, pos), pos->c_str());
101// }
102// s->EOL();
103 const int argc = m_argv.size();
104 for (int i=0; i<argc; ++i)
105 {
106 s->Indent();
107 const char *arg_cstr = m_argv[i];
108 if (arg_cstr)
109 s->Printf("argv[%i]=\"%s\"\n", i, arg_cstr);
110 else
111 s->Printf("argv[%i]=NULL\n", i);
112 }
113 s->EOL();
114}
115
116bool
117Args::GetCommandString (std::string &command)
118{
119 command.clear();
120 int argc = GetArgumentCount();
121 for (int i=0; i<argc; ++i)
122 {
123 if (i > 0)
124 command += ' ';
125 command += m_argv[i];
126 }
127 return argc > 0;
128}
129
Caroline Ticed9105c22010-12-10 00:26:54 +0000130bool
131Args::GetQuotedCommandString (std::string &command)
132{
133 command.clear ();
Greg Clayton928d1302010-12-19 03:41:24 +0000134 size_t argc = GetArgumentCount ();
135 for (size_t i = 0; i < argc; ++i)
Caroline Ticed9105c22010-12-10 00:26:54 +0000136 {
137 if (i > 0)
Greg Clayton928d1302010-12-19 03:41:24 +0000138 command.append (1, ' ');
139 char quote_char = GetArgumentQuoteCharAtIndex(i);
140 if (quote_char)
Caroline Ticed9105c22010-12-10 00:26:54 +0000141 {
Greg Clayton928d1302010-12-19 03:41:24 +0000142 command.append (1, quote_char);
143 command.append (m_argv[i]);
144 command.append (1, quote_char);
Caroline Ticed9105c22010-12-10 00:26:54 +0000145 }
146 else
Greg Clayton928d1302010-12-19 03:41:24 +0000147 command.append (m_argv[i]);
Caroline Ticed9105c22010-12-10 00:26:54 +0000148 }
149 return argc > 0;
150}
151
Chris Lattner24943d22010-06-08 16:52:24 +0000152void
153Args::SetCommandString (const char *command, size_t len)
154{
155 // Use std::string to make sure we get a NULL terminated string we can use
156 // as "command" could point to a string within a large string....
157 std::string null_terminated_command(command, len);
158 SetCommandString(null_terminated_command.c_str());
159}
160
161void
162Args::SetCommandString (const char *command)
163{
164 m_args.clear();
165 m_argv.clear();
Greg Clayton928d1302010-12-19 03:41:24 +0000166 m_args_quote_char.clear();
167
Chris Lattner24943d22010-06-08 16:52:24 +0000168 if (command && command[0])
169 {
Greg Clayton928d1302010-12-19 03:41:24 +0000170 static const char *k_space_separators = " \t";
171 static const char *k_space_separators_with_slash_and_quotes = " \t \\'\"`";
172 const char *arg_end = NULL;
173 const char *arg_pos;
174 for (arg_pos = command;
175 arg_pos && arg_pos[0];
176 arg_pos = arg_end)
Chris Lattner24943d22010-06-08 16:52:24 +0000177 {
Greg Clayton928d1302010-12-19 03:41:24 +0000178 // Skip any leading space separators
179 const char *arg_start = ::strspn (arg_pos, k_space_separators) + arg_pos;
180
181 // If there were only space separators to the end of the line, then
Chris Lattner24943d22010-06-08 16:52:24 +0000182 // we're done.
183 if (*arg_start == '\0')
184 break;
185
Greg Clayton5d187e52011-01-08 20:28:42 +0000186 // Arguments can be split into multiple discontiguous pieces,
Greg Clayton928d1302010-12-19 03:41:24 +0000187 // for example:
188 // "Hello ""World"
189 // this would result in a single argument "Hello World" (without/
190 // the quotes) since the quotes would be removed and there is
191 // not space between the strings. So we need to keep track of the
192 // current start of each argument piece in "arg_piece_start"
193 const char *arg_piece_start = arg_start;
194 arg_pos = arg_piece_start;
195
Chris Lattner24943d22010-06-08 16:52:24 +0000196 std::string arg;
Greg Clayton928d1302010-12-19 03:41:24 +0000197 // Since we can have multiple quotes that form a single command
198 // in a command like: "Hello "world'!' (which will make a single
199 // argument "Hello world!") we remember the first quote character
200 // we encounter and use that for the quote character.
201 char first_quote_char = '\0';
202 char quote_char = '\0';
203 bool arg_complete = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000204
Greg Clayton928d1302010-12-19 03:41:24 +0000205 do
Chris Lattner24943d22010-06-08 16:52:24 +0000206 {
Greg Clayton928d1302010-12-19 03:41:24 +0000207 arg_end = ::strcspn (arg_pos, k_space_separators_with_slash_and_quotes) + arg_pos;
208
209 switch (arg_end[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000210 {
Greg Clayton928d1302010-12-19 03:41:24 +0000211 default:
212 assert (!"Unhandled case statement, we must handle this...");
213 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000214
Greg Clayton928d1302010-12-19 03:41:24 +0000215 case '\0':
216 // End of C string
217 if (arg_piece_start && arg_piece_start[0])
218 arg.append (arg_piece_start);
219 arg_complete = true;
220 break;
221
222 case '\\':
223 // Backslash character
224 switch (arg_end[1])
Chris Lattner24943d22010-06-08 16:52:24 +0000225 {
Greg Clayton928d1302010-12-19 03:41:24 +0000226 case '\0':
227 arg.append (arg_piece_start);
228 arg_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000229 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000230
Greg Clayton928d1302010-12-19 03:41:24 +0000231 default:
232 arg_pos = arg_end + 2;
233 break;
234 }
235 break;
236
237 case '"':
238 case '\'':
239 case '`':
240 // Quote characters
241 if (quote_char)
242 {
243 // We found a quote character while inside a quoted
244 // character argument. If it matches our current quote
245 // character, this ends the effect of the quotes. If it
246 // doesn't we ignore it.
247 if (quote_char == arg_end[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000248 {
Greg Clayton928d1302010-12-19 03:41:24 +0000249 arg.append (arg_piece_start, arg_end - arg_piece_start);
250 // Clear the quote character and let parsing
251 // continue (we need to watch for things like:
252 // "Hello ""World"
253 // "Hello "World
254 // "Hello "'World'
255 // All of which will result in a single argument "Hello World"
256 quote_char = '\0'; // Note that we are no longer inside quotes
257 arg_pos = arg_end + 1; // Skip the quote character
258 arg_piece_start = arg_pos; // Note we are starting from later in the string
259 }
260 else
261 {
262 // different quote, skip it and keep going
263 arg_pos = arg_end + 1;
264 }
265 }
266 else
267 {
268 // We found the start of a quote scope.
Greg Clayton5d187e52011-01-08 20:28:42 +0000269 // Make sure there isn't a string that precedes
Greg Clayton928d1302010-12-19 03:41:24 +0000270 // the start of a quote scope like:
271 // Hello" World"
272 // If so, then add the "Hello" to the arg
273 if (arg_end > arg_piece_start)
274 arg.append (arg_piece_start, arg_end - arg_piece_start);
275
276 // Enter into a quote scope
277 quote_char = arg_end[0];
278
279 if (first_quote_char == '\0')
280 first_quote_char = quote_char;
281
282 arg_pos = arg_end;
283
284 if (quote_char != '`')
285 ++arg_pos; // Skip the quote character if it is not a backtick
286
287 arg_piece_start = arg_pos; // Note we are starting from later in the string
288
289 // Skip till the next quote character
290 const char *end_quote = ::strchr (arg_piece_start, quote_char);
291 while (end_quote && end_quote[-1] == '\\')
292 {
293 // Don't skip the quote character if it is
294 // preceded by a '\' character
295 end_quote = ::strchr (end_quote + 1, quote_char);
296 }
297
298 if (end_quote)
299 {
300 if (end_quote > arg_piece_start)
Chris Lattner24943d22010-06-08 16:52:24 +0000301 {
Greg Clayton928d1302010-12-19 03:41:24 +0000302 // Keep the backtick quote on commands
303 if (quote_char == '`')
304 arg.append (arg_piece_start, end_quote + 1 - arg_piece_start);
305 else
306 arg.append (arg_piece_start, end_quote - arg_piece_start);
307 }
308
309 // If the next character is a space or the end of
310 // string, this argument is complete...
311 if (end_quote[1] == ' ' || end_quote[1] == '\t' || end_quote[1] == '\0')
312 {
313 arg_complete = true;
314 arg_end = end_quote + 1;
Chris Lattner24943d22010-06-08 16:52:24 +0000315 }
316 else
317 {
Greg Clayton928d1302010-12-19 03:41:24 +0000318 arg_pos = end_quote + 1;
319 arg_piece_start = arg_pos;
Chris Lattner24943d22010-06-08 16:52:24 +0000320 }
Greg Clayton928d1302010-12-19 03:41:24 +0000321 quote_char = '\0';
Chris Lattner24943d22010-06-08 16:52:24 +0000322 }
323 }
Greg Clayton928d1302010-12-19 03:41:24 +0000324 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000325
Greg Clayton928d1302010-12-19 03:41:24 +0000326 case ' ':
327 case '\t':
328 if (quote_char)
Chris Lattner24943d22010-06-08 16:52:24 +0000329 {
Greg Clayton928d1302010-12-19 03:41:24 +0000330 // We are currently processing a quoted character and found
331 // a space character, skip any spaces and keep trying to find
332 // the end of the argument.
333 arg_pos = ::strspn (arg_end, k_space_separators) + arg_end;
Chris Lattner24943d22010-06-08 16:52:24 +0000334 }
Greg Clayton928d1302010-12-19 03:41:24 +0000335 else
Chris Lattner24943d22010-06-08 16:52:24 +0000336 {
Greg Clayton928d1302010-12-19 03:41:24 +0000337 // We are not inside any quotes, we just found a space after an
338 // argument
339 if (arg_end > arg_piece_start)
340 arg.append (arg_piece_start, arg_end - arg_piece_start);
341 arg_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000342 }
Greg Clayton928d1302010-12-19 03:41:24 +0000343 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000344 }
Greg Clayton928d1302010-12-19 03:41:24 +0000345 } while (!arg_complete);
Chris Lattner24943d22010-06-08 16:52:24 +0000346
347 m_args.push_back(arg);
Greg Clayton928d1302010-12-19 03:41:24 +0000348 m_args_quote_char.push_back (first_quote_char);
Chris Lattner24943d22010-06-08 16:52:24 +0000349 }
Greg Clayton928d1302010-12-19 03:41:24 +0000350 UpdateArgvFromArgs();
Chris Lattner24943d22010-06-08 16:52:24 +0000351 }
Chris Lattner24943d22010-06-08 16:52:24 +0000352}
353
354void
355Args::UpdateArgsAfterOptionParsing()
356{
357 // Now m_argv might be out of date with m_args, so we need to fix that
358 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
359 arg_sstr_collection::iterator args_pos;
360 arg_quote_char_collection::iterator quotes_pos;
361
362 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
363 argv_pos != argv_end && args_pos != m_args.end();
364 ++argv_pos)
365 {
366 const char *argv_cstr = *argv_pos;
367 if (argv_cstr == NULL)
368 break;
369
370 while (args_pos != m_args.end())
371 {
372 const char *args_cstr = args_pos->c_str();
373 if (args_cstr == argv_cstr)
374 {
375 // We found the argument that matches the C string in the
376 // vector, so we can now look for the next one
377 ++args_pos;
378 ++quotes_pos;
379 break;
380 }
381 else
382 {
383 quotes_pos = m_args_quote_char.erase (quotes_pos);
384 args_pos = m_args.erase (args_pos);
385 }
386 }
387 }
388
389 if (args_pos != m_args.end())
390 m_args.erase (args_pos, m_args.end());
391
392 if (quotes_pos != m_args_quote_char.end())
393 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
394}
395
396void
397Args::UpdateArgvFromArgs()
398{
399 m_argv.clear();
400 arg_sstr_collection::const_iterator pos, end = m_args.end();
401 for (pos = m_args.begin(); pos != end; ++pos)
402 m_argv.push_back(pos->c_str());
403 m_argv.push_back(NULL);
Greg Clayton928d1302010-12-19 03:41:24 +0000404 // Make sure we have enough arg quote chars in the array
405 if (m_args_quote_char.size() < m_args.size())
406 m_args_quote_char.resize (m_argv.size());
Chris Lattner24943d22010-06-08 16:52:24 +0000407}
408
409size_t
410Args::GetArgumentCount() const
411{
412 if (m_argv.empty())
413 return 0;
414 return m_argv.size() - 1;
415}
416
417const char *
418Args::GetArgumentAtIndex (size_t idx) const
419{
420 if (idx < m_argv.size())
421 return m_argv[idx];
422 return NULL;
423}
424
425char
426Args::GetArgumentQuoteCharAtIndex (size_t idx) const
427{
428 if (idx < m_args_quote_char.size())
429 return m_args_quote_char[idx];
430 return '\0';
431}
432
433char **
434Args::GetArgumentVector()
435{
436 if (!m_argv.empty())
437 return (char **)&m_argv[0];
438 return NULL;
439}
440
441const char **
442Args::GetConstArgumentVector() const
443{
444 if (!m_argv.empty())
445 return (const char **)&m_argv[0];
446 return NULL;
447}
448
449void
450Args::Shift ()
451{
452 // Don't pop the last NULL terminator from the argv array
453 if (m_argv.size() > 1)
454 {
455 m_argv.erase(m_argv.begin());
456 m_args.pop_front();
Greg Clayton928d1302010-12-19 03:41:24 +0000457 if (!m_args_quote_char.empty())
458 m_args_quote_char.erase(m_args_quote_char.begin());
Chris Lattner24943d22010-06-08 16:52:24 +0000459 }
460}
461
462const char *
463Args::Unshift (const char *arg_cstr, char quote_char)
464{
465 m_args.push_front(arg_cstr);
466 m_argv.insert(m_argv.begin(), m_args.front().c_str());
467 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
468 return GetArgumentAtIndex (0);
469}
470
471void
472Args::AppendArguments (const Args &rhs)
473{
474 const size_t rhs_argc = rhs.GetArgumentCount();
475 for (size_t i=0; i<rhs_argc; ++i)
476 AppendArgument(rhs.GetArgumentAtIndex(i));
477}
478
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000479void
480Args::AppendArguments (const char **argv)
481{
482 if (argv)
483 {
484 for (uint32_t i=0; argv[i]; ++i)
485 AppendArgument(argv[i]);
486 }
487}
488
Chris Lattner24943d22010-06-08 16:52:24 +0000489const char *
490Args::AppendArgument (const char *arg_cstr, char quote_char)
491{
492 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
493}
494
495const char *
496Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
497{
498 // Since we are using a std::list to hold onto the copied C string and
499 // we don't have direct access to the elements, we have to iterate to
500 // find the value.
501 arg_sstr_collection::iterator pos, end = m_args.end();
502 size_t i = idx;
503 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
504 --i;
505
506 pos = m_args.insert(pos, arg_cstr);
507
Greg Clayton928d1302010-12-19 03:41:24 +0000508 if (idx >= m_args_quote_char.size())
509 {
510 m_args_quote_char.resize(idx + 1);
511 m_args_quote_char[idx] = quote_char;
512 }
513 else
514 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
Chris Lattner24943d22010-06-08 16:52:24 +0000515
516 UpdateArgvFromArgs();
517 return GetArgumentAtIndex(idx);
518}
519
520const char *
521Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
522{
523 // Since we are using a std::list to hold onto the copied C string and
524 // we don't have direct access to the elements, we have to iterate to
525 // find the value.
526 arg_sstr_collection::iterator pos, end = m_args.end();
527 size_t i = idx;
528 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
529 --i;
530
531 if (pos != end)
532 {
533 pos->assign(arg_cstr);
534 assert(idx < m_argv.size() - 1);
535 m_argv[idx] = pos->c_str();
Greg Clayton928d1302010-12-19 03:41:24 +0000536 if (idx >= m_args_quote_char.size())
537 m_args_quote_char.resize(idx + 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000538 m_args_quote_char[idx] = quote_char;
539 return GetArgumentAtIndex(idx);
540 }
541 return NULL;
542}
543
544void
545Args::DeleteArgumentAtIndex (size_t idx)
546{
547 // Since we are using a std::list to hold onto the copied C string and
548 // we don't have direct access to the elements, we have to iterate to
549 // find the value.
550 arg_sstr_collection::iterator pos, end = m_args.end();
551 size_t i = idx;
552 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
553 --i;
554
555 if (pos != end)
556 {
557 m_args.erase (pos);
558 assert(idx < m_argv.size() - 1);
559 m_argv.erase(m_argv.begin() + idx);
Greg Clayton928d1302010-12-19 03:41:24 +0000560 if (idx < m_args_quote_char.size())
561 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
Chris Lattner24943d22010-06-08 16:52:24 +0000562 }
563}
564
565void
566Args::SetArguments (int argc, const char **argv)
567{
568 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
569 // no need to clear it here.
570 m_args.clear();
571 m_args_quote_char.clear();
572
Chris Lattner24943d22010-06-08 16:52:24 +0000573 // First copy each string
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000574 for (size_t i=0; i<argc; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000575 {
576 m_args.push_back (argv[i]);
Greg Clayton928d1302010-12-19 03:41:24 +0000577 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
Chris Lattner24943d22010-06-08 16:52:24 +0000578 m_args_quote_char.push_back (argv[i][0]);
579 else
580 m_args_quote_char.push_back ('\0');
581 }
582
583 UpdateArgvFromArgs();
584}
585
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000586void
587Args::SetArguments (const char **argv)
588{
589 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
590 // no need to clear it here.
591 m_args.clear();
592 m_args_quote_char.clear();
593
594 if (argv)
595 {
596 // First copy each string
597 for (size_t i=0; argv[i]; ++i)
598 {
599 m_args.push_back (argv[i]);
600 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
601 m_args_quote_char.push_back (argv[i][0]);
602 else
603 m_args_quote_char.push_back ('\0');
604 }
605 }
606
607 UpdateArgvFromArgs();
608}
609
Chris Lattner24943d22010-06-08 16:52:24 +0000610
611Error
612Args::ParseOptions (Options &options)
613{
614 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000615 Error error;
616 struct option *long_options = options.GetLongOptions();
617 if (long_options == NULL)
618 {
Greg Clayton9c236732011-10-26 00:56:27 +0000619 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner24943d22010-06-08 16:52:24 +0000620 return error;
621 }
622
Greg Claytonbef15832010-07-14 00:18:15 +0000623 for (int i=0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000624 {
625 if (long_options[i].flag == NULL)
626 {
627 sstr << (char)long_options[i].val;
628 switch (long_options[i].has_arg)
629 {
630 default:
631 case no_argument: break;
632 case required_argument: sstr << ':'; break;
633 case optional_argument: sstr << "::"; break;
634 }
635 }
636 }
Eli Friedmanef2bc872010-06-13 19:18:49 +0000637#ifdef __GLIBC__
638 optind = 0;
639#else
Chris Lattner24943d22010-06-08 16:52:24 +0000640 optreset = 1;
641 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000642#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000643 int val;
644 while (1)
645 {
646 int long_options_index = -1;
647 val = ::getopt_long(GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
648 &long_options_index);
649 if (val == -1)
650 break;
651
652 // Did we get an error?
653 if (val == '?')
654 {
Greg Clayton9c236732011-10-26 00:56:27 +0000655 error.SetErrorStringWithFormat("unknown or ambiguous option");
Chris Lattner24943d22010-06-08 16:52:24 +0000656 break;
657 }
658 // The option auto-set itself
659 if (val == 0)
660 continue;
661
662 ((Options *) &options)->OptionSeen (val);
663
664 // Lookup the long option index
665 if (long_options_index == -1)
666 {
667 for (int i=0;
668 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
669 ++i)
670 {
671 if (long_options[i].val == val)
672 {
673 long_options_index = i;
674 break;
675 }
676 }
677 }
678 // Call the callback with the option
679 if (long_options_index >= 0)
680 {
681 error = options.SetOptionValue(long_options_index,
682 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
683 }
684 else
685 {
Greg Clayton9c236732011-10-26 00:56:27 +0000686 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
Chris Lattner24943d22010-06-08 16:52:24 +0000687 }
688 if (error.Fail())
689 break;
690 }
691
692 // Update our ARGV now that get options has consumed all the options
693 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
694 UpdateArgsAfterOptionParsing ();
695 return error;
696}
697
698void
699Args::Clear ()
700{
701 m_args.clear ();
702 m_argv.clear ();
703 m_args_quote_char.clear();
704}
705
706int32_t
707Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
708{
709 if (s && s[0])
710 {
711 char *end = NULL;
712 int32_t uval = ::strtol (s, &end, base);
713 if (*end == '\0')
714 {
715 if (success_ptr) *success_ptr = true;
716 return uval; // All characters were used, return the result
717 }
718 }
719 if (success_ptr) *success_ptr = false;
720 return fail_value;
721}
722
723uint32_t
724Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
725{
726 if (s && s[0])
727 {
728 char *end = NULL;
729 uint32_t uval = ::strtoul (s, &end, base);
730 if (*end == '\0')
731 {
732 if (success_ptr) *success_ptr = true;
733 return uval; // All characters were used, return the result
734 }
735 }
736 if (success_ptr) *success_ptr = false;
737 return fail_value;
738}
739
740
741int64_t
742Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
743{
744 if (s && s[0])
745 {
746 char *end = NULL;
747 int64_t uval = ::strtoll (s, &end, base);
748 if (*end == '\0')
749 {
750 if (success_ptr) *success_ptr = true;
751 return uval; // All characters were used, return the result
752 }
753 }
754 if (success_ptr) *success_ptr = false;
755 return fail_value;
756}
757
758uint64_t
759Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
760{
761 if (s && s[0])
762 {
763 char *end = NULL;
764 uint64_t uval = ::strtoull (s, &end, base);
765 if (*end == '\0')
766 {
767 if (success_ptr) *success_ptr = true;
768 return uval; // All characters were used, return the result
769 }
770 }
771 if (success_ptr) *success_ptr = false;
772 return fail_value;
773}
774
775lldb::addr_t
776Args::StringToAddress (const char *s, lldb::addr_t fail_value, bool *success_ptr)
777{
778 if (s && s[0])
779 {
780 char *end = NULL;
781 lldb::addr_t addr = ::strtoull (s, &end, 0);
782 if (*end == '\0')
783 {
784 if (success_ptr) *success_ptr = true;
785 return addr; // All characters were used, return the result
786 }
787 // Try base 16 with no prefix...
788 addr = ::strtoull (s, &end, 16);
789 if (*end == '\0')
790 {
791 if (success_ptr) *success_ptr = true;
792 return addr; // All characters were used, return the result
793 }
794 }
795 if (success_ptr) *success_ptr = false;
796 return fail_value;
797}
798
799bool
800Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
801{
802 if (s && s[0])
803 {
804 if (::strcasecmp (s, "false") == 0 ||
805 ::strcasecmp (s, "off") == 0 ||
806 ::strcasecmp (s, "no") == 0 ||
807 ::strcmp (s, "0") == 0)
808 {
809 if (success_ptr)
810 *success_ptr = true;
811 return false;
812 }
813 else
814 if (::strcasecmp (s, "true") == 0 ||
815 ::strcasecmp (s, "on") == 0 ||
816 ::strcasecmp (s, "yes") == 0 ||
817 ::strcmp (s, "1") == 0)
818 {
819 if (success_ptr) *success_ptr = true;
820 return true;
821 }
822 }
823 if (success_ptr) *success_ptr = false;
824 return fail_value;
825}
826
Greg Claytonb1888f22011-03-19 01:12:21 +0000827const char *
828Args::StringToVersion (const char *s, uint32_t &major, uint32_t &minor, uint32_t &update)
829{
830 major = UINT32_MAX;
831 minor = UINT32_MAX;
832 update = UINT32_MAX;
833
834 if (s && s[0])
835 {
836 char *pos = NULL;
837 uint32_t uval32;
838 uval32 = ::strtoul (s, &pos, 0);
839 if (pos == s)
840 return s;
841 major = uval32;
842 if (*pos == '\0')
843 {
844 return pos; // Decoded major and got end of string
845 }
846 else if (*pos == '.')
847 {
848 const char *minor_cstr = pos + 1;
849 uval32 = ::strtoul (minor_cstr, &pos, 0);
850 if (pos == minor_cstr)
851 return pos; // Didn't get any digits for the minor version...
852 minor = uval32;
853 if (*pos == '.')
854 {
855 const char *update_cstr = pos + 1;
856 uval32 = ::strtoul (update_cstr, &pos, 0);
857 if (pos == update_cstr)
858 return pos;
859 update = uval32;
860 }
861 return pos;
862 }
863 }
864 return 0;
865}
866
867
Chris Lattner24943d22010-06-08 16:52:24 +0000868int32_t
Greg Clayton61aca5d2011-10-07 18:58:12 +0000869Args::StringToOptionEnum (const char *s, OptionEnumValueElement *enum_values, int32_t fail_value, Error &error)
Chris Lattner24943d22010-06-08 16:52:24 +0000870{
Greg Clayton61aca5d2011-10-07 18:58:12 +0000871 if (enum_values)
Chris Lattner24943d22010-06-08 16:52:24 +0000872 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000873 if (s && s[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000874 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000875 for (int i = 0; enum_values[i].string_value != NULL ; i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000876 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000877 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
878 {
879 error.Clear();
880 return enum_values[i].value;
881 }
Chris Lattner24943d22010-06-08 16:52:24 +0000882 }
883 }
Greg Clayton61aca5d2011-10-07 18:58:12 +0000884
885 StreamString strm;
886 strm.PutCString ("invalid enumeration value, valid values are: ");
887 for (int i = 0; enum_values[i].string_value != NULL; i++)
888 {
889 strm.Printf ("%s\"%s\"",
890 i > 0 ? ", " : "",
891 enum_values[i].string_value);
892 }
893 error.SetErrorString(strm.GetData());
Chris Lattner24943d22010-06-08 16:52:24 +0000894 }
Greg Clayton61aca5d2011-10-07 18:58:12 +0000895 else
896 {
897 error.SetErrorString ("invalid enumeration argument");
898 }
Chris Lattner24943d22010-06-08 16:52:24 +0000899 return fail_value;
900}
901
902ScriptLanguage
903Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
904{
905 if (s && s[0])
906 {
907 if ((::strcasecmp (s, "python") == 0) ||
908 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
909 {
910 if (success_ptr) *success_ptr = true;
911 return eScriptLanguagePython;
912 }
913 if (::strcasecmp (s, "none"))
914 {
915 if (success_ptr) *success_ptr = true;
916 return eScriptLanguageNone;
917 }
918 }
919 if (success_ptr) *success_ptr = false;
920 return fail_value;
921}
922
923Error
924Args::StringToFormat
925(
926 const char *s,
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000927 lldb::Format &format,
928 uint32_t *byte_size_ptr
Chris Lattner24943d22010-06-08 16:52:24 +0000929)
930{
931 format = eFormatInvalid;
932 Error error;
933
934 if (s && s[0])
935 {
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000936 if (byte_size_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +0000937 {
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000938 if (isdigit (s[0]))
939 {
940 char *format_char = NULL;
941 unsigned long byte_size = ::strtoul (s, &format_char, 0);
942 if (byte_size != ULONG_MAX)
943 *byte_size_ptr = byte_size;
944 s = format_char;
945 }
946 else
947 *byte_size_ptr = 0;
948 }
949
Greg Clayton3182eff2011-06-23 21:22:24 +0000950 const bool partial_match_ok = true;
951 if (!FormatManager::GetFormatFromCString (s, partial_match_ok, format))
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000952 {
Greg Clayton3182eff2011-06-23 21:22:24 +0000953 StreamString error_strm;
954 error_strm.Printf ("Invalid format character or name '%s'. Valid values are:\n", s);
Peter Collingbournef4d4fcc2011-06-24 01:12:22 +0000955 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000956 {
Greg Clayton3182eff2011-06-23 21:22:24 +0000957 char format_char = FormatManager::GetFormatAsFormatChar(f);
958 if (format_char)
959 error_strm.Printf ("'%c' or ", format_char);
960
961 error_strm.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
962 error_strm.EOL();
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000963 }
Greg Clayton3182eff2011-06-23 21:22:24 +0000964
965 if (byte_size_ptr)
966 error_strm.PutCString ("An optional byte size can precede the format character.\n");
967 error.SetErrorString(error_strm.GetString().c_str());
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000968 }
Chris Lattner24943d22010-06-08 16:52:24 +0000969
970 if (error.Fail())
971 return error;
972 }
973 else
974 {
Greg Clayton9c236732011-10-26 00:56:27 +0000975 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
Chris Lattner24943d22010-06-08 16:52:24 +0000976 }
977 return error;
978}
979
980void
981Args::LongestCommonPrefix (std::string &common_prefix)
982{
983 arg_sstr_collection::iterator pos, end = m_args.end();
984 pos = m_args.begin();
985 if (pos == end)
986 common_prefix.clear();
987 else
988 common_prefix = (*pos);
989
990 for (++pos; pos != end; ++pos)
991 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000992 size_t new_size = (*pos).size();
Chris Lattner24943d22010-06-08 16:52:24 +0000993
994 // First trim common_prefix if it is longer than the current element:
995 if (common_prefix.size() > new_size)
996 common_prefix.erase (new_size);
997
998 // Then trim it at the first disparity:
999
Greg Clayton54e7afa2010-07-09 20:39:50 +00001000 for (size_t i = 0; i < common_prefix.size(); i++)
Chris Lattner24943d22010-06-08 16:52:24 +00001001 {
1002 if ((*pos)[i] != common_prefix[i])
1003 {
1004 common_prefix.erase(i);
1005 break;
1006 }
1007 }
1008
1009 // If we've emptied the common prefix, we're done.
1010 if (common_prefix.empty())
1011 break;
1012 }
1013}
1014
Caroline Tice44c841d2010-12-07 19:58:26 +00001015size_t
1016Args::FindArgumentIndexForOption (struct option *long_options, int long_options_index)
1017{
1018 char short_buffer[3];
1019 char long_buffer[255];
1020 ::snprintf (short_buffer, sizeof (short_buffer), "-%c", (char) long_options[long_options_index].val);
1021 ::snprintf (long_buffer, sizeof (long_buffer), "--%s", long_options[long_options_index].name);
1022 size_t end = GetArgumentCount ();
1023 size_t idx = 0;
1024 while (idx < end)
1025 {
1026 if ((::strncmp (GetArgumentAtIndex (idx), short_buffer, strlen (short_buffer)) == 0)
1027 || (::strncmp (GetArgumentAtIndex (idx), long_buffer, strlen (long_buffer)) == 0))
1028 {
1029 return idx;
1030 }
1031 ++idx;
1032 }
1033
1034 return end;
1035}
1036
1037bool
1038Args::IsPositionalArgument (const char *arg)
1039{
1040 if (arg == NULL)
1041 return false;
1042
1043 bool is_positional = true;
1044 char *cptr = (char *) arg;
1045
1046 if (cptr[0] == '%')
1047 {
1048 ++cptr;
1049 while (isdigit (cptr[0]))
1050 ++cptr;
1051 if (cptr[0] != '\0')
1052 is_positional = false;
1053 }
1054 else
1055 is_positional = false;
1056
1057 return is_positional;
1058}
1059
Chris Lattner24943d22010-06-08 16:52:24 +00001060void
Caroline Tice5e0894e2010-10-12 17:45:19 +00001061Args::ParseAliasOptions (Options &options,
1062 CommandReturnObject &result,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001063 OptionArgVector *option_arg_vector,
1064 std::string &raw_input_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001065{
1066 StreamString sstr;
1067 int i;
1068 struct option *long_options = options.GetLongOptions();
1069
1070 if (long_options == NULL)
1071 {
1072 result.AppendError ("invalid long options");
1073 result.SetStatus (eReturnStatusFailed);
1074 return;
1075 }
1076
1077 for (i = 0; long_options[i].name != NULL; ++i)
1078 {
1079 if (long_options[i].flag == NULL)
1080 {
1081 sstr << (char) long_options[i].val;
1082 switch (long_options[i].has_arg)
1083 {
1084 default:
1085 case no_argument:
1086 break;
1087 case required_argument:
1088 sstr << ":";
1089 break;
1090 case optional_argument:
1091 sstr << "::";
1092 break;
1093 }
1094 }
1095 }
1096
Eli Friedmanef2bc872010-06-13 19:18:49 +00001097#ifdef __GLIBC__
1098 optind = 0;
1099#else
Chris Lattner24943d22010-06-08 16:52:24 +00001100 optreset = 1;
1101 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001102#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001103 int val;
1104 while (1)
1105 {
1106 int long_options_index = -1;
1107 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
1108 &long_options_index);
1109
1110 if (val == -1)
1111 break;
1112
1113 if (val == '?')
1114 {
1115 result.AppendError ("unknown or ambiguous option");
1116 result.SetStatus (eReturnStatusFailed);
1117 break;
1118 }
1119
1120 if (val == 0)
1121 continue;
1122
1123 ((Options *) &options)->OptionSeen (val);
1124
1125 // Look up the long option index
1126 if (long_options_index == -1)
1127 {
1128 for (int j = 0;
1129 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1130 ++j)
1131 {
1132 if (long_options[j].val == val)
1133 {
1134 long_options_index = j;
1135 break;
1136 }
1137 }
1138 }
1139
1140 // See if the option takes an argument, and see if one was supplied.
1141 if (long_options_index >= 0)
1142 {
1143 StreamString option_str;
1144 option_str.Printf ("-%c", (char) val);
1145
1146 switch (long_options[long_options_index].has_arg)
1147 {
1148 case no_argument:
Caroline Tice44c841d2010-12-07 19:58:26 +00001149 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1150 OptionArgValue (no_argument, "<no-argument>")));
Caroline Tice2160c3f2010-09-12 04:48:45 +00001151 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Chris Lattner24943d22010-06-08 16:52:24 +00001152 break;
1153 case required_argument:
1154 if (optarg != NULL)
1155 {
1156 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001157 OptionArgValue (required_argument,
1158 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001159 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1160 }
1161 else
1162 {
1163 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
1164 option_str.GetData());
1165 result.SetStatus (eReturnStatusFailed);
1166 }
1167 break;
1168 case optional_argument:
1169 if (optarg != NULL)
1170 {
1171 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001172 OptionArgValue (optional_argument,
1173 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001174 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1175 }
1176 else
1177 {
1178 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001179 OptionArgValue (optional_argument, "<no-argument>")));
Chris Lattner24943d22010-06-08 16:52:24 +00001180 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1181 }
1182 break;
1183 default:
1184 result.AppendErrorWithFormat
1185 ("error with options table; invalid value in has_arg field for option '%c'.\n",
1186 (char) val);
1187 result.SetStatus (eReturnStatusFailed);
1188 break;
1189 }
1190 }
1191 else
1192 {
1193 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val);
1194 result.SetStatus (eReturnStatusFailed);
1195 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001196
1197 if (long_options_index >= 0)
1198 {
1199 // Find option in the argument list; also see if it was supposed to take an argument and if one was
Caroline Ticee0da7a52010-12-09 22:52:49 +00001200 // supplied. Remove option (and argument, if given) from the argument list. Also remove them from
1201 // the raw_input_string, if one was passed in.
Caroline Tice44c841d2010-12-07 19:58:26 +00001202 size_t idx = FindArgumentIndexForOption (long_options, long_options_index);
1203 if (idx < GetArgumentCount())
1204 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001205 if (raw_input_string.size() > 0)
1206 {
1207 const char *tmp_arg = GetArgumentAtIndex (idx);
1208 size_t pos = raw_input_string.find (tmp_arg);
1209 if (pos != std::string::npos)
1210 raw_input_string.erase (pos, strlen (tmp_arg));
1211 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001212 ReplaceArgumentAtIndex (idx, "");
1213 if ((long_options[long_options_index].has_arg != no_argument)
1214 && (optarg != NULL)
1215 && (idx+1 < GetArgumentCount())
1216 && (strcmp (optarg, GetArgumentAtIndex(idx+1)) == 0))
Caroline Ticee0da7a52010-12-09 22:52:49 +00001217 {
1218 if (raw_input_string.size() > 0)
1219 {
1220 const char *tmp_arg = GetArgumentAtIndex (idx+1);
1221 size_t pos = raw_input_string.find (tmp_arg);
1222 if (pos != std::string::npos)
1223 raw_input_string.erase (pos, strlen (tmp_arg));
1224 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001225 ReplaceArgumentAtIndex (idx+1, "");
Caroline Ticee0da7a52010-12-09 22:52:49 +00001226 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001227 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001228 }
1229
Chris Lattner24943d22010-06-08 16:52:24 +00001230 if (!result.Succeeded())
1231 break;
1232 }
1233}
1234
1235void
1236Args::ParseArgsForCompletion
1237(
1238 Options &options,
Jim Inghamadb84292010-06-24 20:31:04 +00001239 OptionElementVector &option_element_vector,
1240 uint32_t cursor_index
Chris Lattner24943d22010-06-08 16:52:24 +00001241)
1242{
1243 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001244 struct option *long_options = options.GetLongOptions();
1245 option_element_vector.clear();
1246
1247 if (long_options == NULL)
1248 {
1249 return;
1250 }
1251
1252 // Leading : tells getopt to return a : for a missing option argument AND
1253 // to suppress error messages.
1254
1255 sstr << ":";
Greg Claytonbef15832010-07-14 00:18:15 +00001256 for (int i = 0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001257 {
1258 if (long_options[i].flag == NULL)
1259 {
1260 sstr << (char) long_options[i].val;
1261 switch (long_options[i].has_arg)
1262 {
1263 default:
1264 case no_argument:
1265 break;
1266 case required_argument:
1267 sstr << ":";
1268 break;
1269 case optional_argument:
1270 sstr << "::";
1271 break;
1272 }
1273 }
1274 }
1275
Eli Friedmanef2bc872010-06-13 19:18:49 +00001276#ifdef __GLIBC__
1277 optind = 0;
1278#else
Chris Lattner24943d22010-06-08 16:52:24 +00001279 optreset = 1;
1280 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001281#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001282 opterr = 0;
1283
1284 int val;
1285 const OptionDefinition *opt_defs = options.GetDefinitions();
1286
Jim Inghamadb84292010-06-24 20:31:04 +00001287 // Fooey... getopt_long permutes the GetArgumentVector to move the options to the front.
Chris Lattner24943d22010-06-08 16:52:24 +00001288 // So we have to build another Arg and pass that to getopt_long so it doesn't
Jim Inghamadb84292010-06-24 20:31:04 +00001289 // change the one we have.
Chris Lattner24943d22010-06-08 16:52:24 +00001290
Greg Clayton54e7afa2010-07-09 20:39:50 +00001291 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001292
Jim Inghamadb84292010-06-24 20:31:04 +00001293 bool failed_once = false;
1294 uint32_t dash_dash_pos = -1;
1295
Chris Lattner24943d22010-06-08 16:52:24 +00001296 while (1)
1297 {
1298 bool missing_argument = false;
1299 int parse_start = optind;
1300 int long_options_index = -1;
Jim Inghamadb84292010-06-24 20:31:04 +00001301
Greg Clayton54e7afa2010-07-09 20:39:50 +00001302 val = ::getopt_long (dummy_vec.size() - 1,
Greg Clayton53d68e72010-07-20 22:52:08 +00001303 (char *const *) &dummy_vec.front(),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001304 sstr.GetData(),
1305 long_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001306 &long_options_index);
1307
1308 if (val == -1)
Jim Inghamadb84292010-06-24 20:31:04 +00001309 {
1310 // When we're completing a "--" which is the last option on line,
1311 if (failed_once)
1312 break;
1313
1314 failed_once = true;
1315
1316 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1317 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1318 // user might want to complete options by long name. I make this work by checking whether the
1319 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1320 // I let it pass to getopt_long which will terminate the option parsing.
1321 // Note, in either case we continue parsing the line so we can figure out what other options
1322 // were passed. This will be useful when we come to restricting completions based on what other
1323 // options we've seen on the line.
Chris Lattner24943d22010-06-08 16:52:24 +00001324
Jim Inghamadb84292010-06-24 20:31:04 +00001325 if (optind < dummy_vec.size() - 1
1326 && (strcmp (dummy_vec[optind-1], "--") == 0))
1327 {
1328 dash_dash_pos = optind - 1;
1329 if (optind - 1 == cursor_index)
1330 {
1331 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1332 OptionArgElement::eBareDoubleDash));
1333 continue;
1334 }
1335 else
1336 break;
1337 }
1338 else
1339 break;
1340 }
Chris Lattner24943d22010-06-08 16:52:24 +00001341 else if (val == '?')
1342 {
Jim Inghamadb84292010-06-24 20:31:04 +00001343 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1344 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001345 continue;
1346 }
1347 else if (val == 0)
1348 {
1349 continue;
1350 }
1351 else if (val == ':')
1352 {
1353 // This is a missing argument.
1354 val = optopt;
1355 missing_argument = true;
1356 }
1357
1358 ((Options *) &options)->OptionSeen (val);
1359
1360 // Look up the long option index
1361 if (long_options_index == -1)
1362 {
1363 for (int j = 0;
1364 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1365 ++j)
1366 {
1367 if (long_options[j].val == val)
1368 {
1369 long_options_index = j;
1370 break;
1371 }
1372 }
1373 }
1374
1375 // See if the option takes an argument, and see if one was supplied.
1376 if (long_options_index >= 0)
1377 {
1378 int opt_defs_index = -1;
1379 for (int i = 0; ; i++)
1380 {
1381 if (opt_defs[i].short_option == 0)
1382 break;
1383 else if (opt_defs[i].short_option == val)
1384 {
1385 opt_defs_index = i;
1386 break;
1387 }
1388 }
1389
1390 switch (long_options[long_options_index].has_arg)
1391 {
1392 case no_argument:
1393 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1394 break;
1395 case required_argument:
1396 if (optarg != NULL)
1397 {
1398 int arg_index;
1399 if (missing_argument)
1400 arg_index = -1;
1401 else
Jim Inghamadb84292010-06-24 20:31:04 +00001402 arg_index = optind - 1;
Chris Lattner24943d22010-06-08 16:52:24 +00001403
Jim Inghamadb84292010-06-24 20:31:04 +00001404 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
Chris Lattner24943d22010-06-08 16:52:24 +00001405 }
1406 else
1407 {
Jim Inghamadb84292010-06-24 20:31:04 +00001408 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
Chris Lattner24943d22010-06-08 16:52:24 +00001409 }
1410 break;
1411 case optional_argument:
1412 if (optarg != NULL)
1413 {
Jim Inghamadb84292010-06-24 20:31:04 +00001414 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001415 }
1416 else
1417 {
Jim Inghamadb84292010-06-24 20:31:04 +00001418 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001419 }
1420 break;
1421 default:
1422 // The options table is messed up. Here we'll just continue
Jim Inghamadb84292010-06-24 20:31:04 +00001423 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1424 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001425 break;
1426 }
1427 }
1428 else
1429 {
Jim Inghamadb84292010-06-24 20:31:04 +00001430 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1431 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001432 }
1433 }
Jim Inghamadb84292010-06-24 20:31:04 +00001434
1435 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1436 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long just ignores
1437 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1438
1439 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1440 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1441 {
1442 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1443 OptionArgElement::eBareDash));
1444
1445 }
Chris Lattner24943d22010-06-08 16:52:24 +00001446}