blob: 059a69a36f7aefc845a7dacb057a725c2631f0fc [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"
Chris Lattner24943d22010-06-08 16:52:24 +000017#include "lldb/Core/Stream.h"
18#include "lldb/Core/StreamFile.h"
19#include "lldb/Core/StreamString.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000020#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000021#include "lldb/Interpreter/CommandReturnObject.h"
22
Chris Lattner24943d22010-06-08 16:52:24 +000023using namespace lldb;
24using namespace lldb_private;
25
26static const char *k_space_characters = "\t\n\v\f\r ";
27static const char *k_space_characters_with_slash = "\t\n\v\f\r \\";
28
29
30//----------------------------------------------------------------------
31// Args constructor
32//----------------------------------------------------------------------
33Args::Args (const char *command) :
34 m_args(),
35 m_argv()
36{
37 SetCommandString (command);
38}
39
40
41Args::Args (const char *command, size_t len) :
42 m_args(),
43 m_argv()
44{
45 SetCommandString (command, len);
46}
47
48
49
50//----------------------------------------------------------------------
51// Destructor
52//----------------------------------------------------------------------
53Args::~Args ()
54{
55}
56
57void
58Args::Dump (Stream *s)
59{
60// int argc = GetArgumentCount();
61//
62// arg_sstr_collection::const_iterator pos, begin = m_args.begin(), end = m_args.end();
63// for (pos = m_args.begin(); pos != end; ++pos)
64// {
65// s->Indent();
66// s->Printf("args[%zu]=%s\n", std::distance(begin, pos), pos->c_str());
67// }
68// s->EOL();
69 const int argc = m_argv.size();
70 for (int i=0; i<argc; ++i)
71 {
72 s->Indent();
73 const char *arg_cstr = m_argv[i];
74 if (arg_cstr)
75 s->Printf("argv[%i]=\"%s\"\n", i, arg_cstr);
76 else
77 s->Printf("argv[%i]=NULL\n", i);
78 }
79 s->EOL();
80}
81
82bool
83Args::GetCommandString (std::string &command)
84{
85 command.clear();
86 int argc = GetArgumentCount();
87 for (int i=0; i<argc; ++i)
88 {
89 if (i > 0)
90 command += ' ';
91 command += m_argv[i];
92 }
93 return argc > 0;
94}
95
96void
97Args::SetCommandString (const char *command, size_t len)
98{
99 // Use std::string to make sure we get a NULL terminated string we can use
100 // as "command" could point to a string within a large string....
101 std::string null_terminated_command(command, len);
102 SetCommandString(null_terminated_command.c_str());
103}
104
105void
106Args::SetCommandString (const char *command)
107{
108 m_args.clear();
109 m_argv.clear();
110 if (command && command[0])
111 {
112 const char *arg_start;
113 const char *next_arg_start;
114 for (arg_start = command, next_arg_start = NULL;
115 arg_start && arg_start[0];
116 arg_start = next_arg_start, next_arg_start = NULL)
117 {
118 // Skip any leading space characters
119 arg_start = ::strspn (arg_start, k_space_characters) + arg_start;
120
121 // If there were only space characters to the end of the line, then
122 // we're done.
123 if (*arg_start == '\0')
124 break;
125
126 std::string arg;
127 const char *arg_end = NULL;
128
129 switch (*arg_start)
130 {
131 case '\'':
132 case '"':
133 case '`':
134 {
135 // Look for either a quote character, or the backslash
136 // character
137 const char quote_char = *arg_start;
138 char find_chars[3] = { quote_char, '\\' , '\0'};
139 bool is_backtick = (quote_char == '`');
140 if (quote_char == '"' || quote_char == '`')
141 m_args_quote_char.push_back(quote_char);
142 else
143 m_args_quote_char.push_back('\0');
144
145 while (*arg_start != '\0')
146 {
147 arg_end = ::strcspn (arg_start + 1, find_chars) + arg_start + 1;
148
149 if (*arg_end == '\0')
150 {
151 arg.append (arg_start);
152 break;
153 }
154
155 // Watch out for quote characters prefixed with '\'
156 if (*arg_end == '\\')
157 {
158 if (arg_end[1] == quote_char)
159 {
160 // The character following the '\' is our quote
161 // character so strip the backslash character
162 arg.append (arg_start, arg_end);
163 }
164 else
165 {
166 // The character following the '\' is NOT our
167 // quote character, so include the backslash
168 // and continue
169 arg.append (arg_start, arg_end + 1);
170 }
171 arg_start = arg_end + 1;
172 continue;
173 }
174 else
175 {
176 arg.append (arg_start, arg_end + 1);
177 next_arg_start = arg_end + 1;
178 break;
179 }
180 }
181
182 // Skip single and double quotes, but leave backtick quotes
183 if (!is_backtick)
184 {
185 char first_c = arg[0];
186 arg.erase(0,1);
187 // Only erase the last character if it is the same as the first.
188 // Otherwise, we're parsing an incomplete command line, and we
189 // would be stripping off the last character of that string.
190 if (arg[arg.size() - 1] == first_c)
191 arg.erase(arg.size() - 1, 1);
192 }
193 }
194 break;
195 default:
196 {
197 m_args_quote_char.push_back('\0');
198 // Look for the next non-escaped space character
199 while (*arg_start != '\0')
200 {
201 arg_end = ::strcspn (arg_start, k_space_characters_with_slash) + arg_start;
202
203 if (arg_end == NULL)
204 {
205 arg.append(arg_start);
206 break;
207 }
208
209 if (*arg_end == '\\')
210 {
211 // Append up to the '\' char
212 arg.append (arg_start, arg_end);
213
214 if (arg_end[1] == '\0')
215 break;
216
217 // Append the character following the '\' if it isn't
218 // the end of the string
219 arg.append (1, arg_end[1]);
220 arg_start = arg_end + 2;
221 continue;
222 }
223 else
224 {
225 arg.append (arg_start, arg_end);
226 next_arg_start = arg_end;
227 break;
228 }
229 }
230 }
231 break;
232 }
233
234 m_args.push_back(arg);
235 }
236 }
237 UpdateArgvFromArgs();
238}
239
240void
241Args::UpdateArgsAfterOptionParsing()
242{
243 // Now m_argv might be out of date with m_args, so we need to fix that
244 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
245 arg_sstr_collection::iterator args_pos;
246 arg_quote_char_collection::iterator quotes_pos;
247
248 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
249 argv_pos != argv_end && args_pos != m_args.end();
250 ++argv_pos)
251 {
252 const char *argv_cstr = *argv_pos;
253 if (argv_cstr == NULL)
254 break;
255
256 while (args_pos != m_args.end())
257 {
258 const char *args_cstr = args_pos->c_str();
259 if (args_cstr == argv_cstr)
260 {
261 // We found the argument that matches the C string in the
262 // vector, so we can now look for the next one
263 ++args_pos;
264 ++quotes_pos;
265 break;
266 }
267 else
268 {
269 quotes_pos = m_args_quote_char.erase (quotes_pos);
270 args_pos = m_args.erase (args_pos);
271 }
272 }
273 }
274
275 if (args_pos != m_args.end())
276 m_args.erase (args_pos, m_args.end());
277
278 if (quotes_pos != m_args_quote_char.end())
279 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
280}
281
282void
283Args::UpdateArgvFromArgs()
284{
285 m_argv.clear();
286 arg_sstr_collection::const_iterator pos, end = m_args.end();
287 for (pos = m_args.begin(); pos != end; ++pos)
288 m_argv.push_back(pos->c_str());
289 m_argv.push_back(NULL);
290}
291
292size_t
293Args::GetArgumentCount() const
294{
295 if (m_argv.empty())
296 return 0;
297 return m_argv.size() - 1;
298}
299
300const char *
301Args::GetArgumentAtIndex (size_t idx) const
302{
303 if (idx < m_argv.size())
304 return m_argv[idx];
305 return NULL;
306}
307
308char
309Args::GetArgumentQuoteCharAtIndex (size_t idx) const
310{
311 if (idx < m_args_quote_char.size())
312 return m_args_quote_char[idx];
313 return '\0';
314}
315
316char **
317Args::GetArgumentVector()
318{
319 if (!m_argv.empty())
320 return (char **)&m_argv[0];
321 return NULL;
322}
323
324const char **
325Args::GetConstArgumentVector() const
326{
327 if (!m_argv.empty())
328 return (const char **)&m_argv[0];
329 return NULL;
330}
331
332void
333Args::Shift ()
334{
335 // Don't pop the last NULL terminator from the argv array
336 if (m_argv.size() > 1)
337 {
338 m_argv.erase(m_argv.begin());
339 m_args.pop_front();
340 m_args_quote_char.erase(m_args_quote_char.begin());
341 }
342}
343
344const char *
345Args::Unshift (const char *arg_cstr, char quote_char)
346{
347 m_args.push_front(arg_cstr);
348 m_argv.insert(m_argv.begin(), m_args.front().c_str());
349 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
350 return GetArgumentAtIndex (0);
351}
352
353void
354Args::AppendArguments (const Args &rhs)
355{
356 const size_t rhs_argc = rhs.GetArgumentCount();
357 for (size_t i=0; i<rhs_argc; ++i)
358 AppendArgument(rhs.GetArgumentAtIndex(i));
359}
360
361const char *
362Args::AppendArgument (const char *arg_cstr, char quote_char)
363{
364 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
365}
366
367const char *
368Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
369{
370 // Since we are using a std::list to hold onto the copied C string and
371 // we don't have direct access to the elements, we have to iterate to
372 // find the value.
373 arg_sstr_collection::iterator pos, end = m_args.end();
374 size_t i = idx;
375 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
376 --i;
377
378 pos = m_args.insert(pos, arg_cstr);
379
380
381 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
382
383 UpdateArgvFromArgs();
384 return GetArgumentAtIndex(idx);
385}
386
387const char *
388Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
389{
390 // Since we are using a std::list to hold onto the copied C string and
391 // we don't have direct access to the elements, we have to iterate to
392 // find the value.
393 arg_sstr_collection::iterator pos, end = m_args.end();
394 size_t i = idx;
395 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
396 --i;
397
398 if (pos != end)
399 {
400 pos->assign(arg_cstr);
401 assert(idx < m_argv.size() - 1);
402 m_argv[idx] = pos->c_str();
403 m_args_quote_char[idx] = quote_char;
404 return GetArgumentAtIndex(idx);
405 }
406 return NULL;
407}
408
409void
410Args::DeleteArgumentAtIndex (size_t idx)
411{
412 // Since we are using a std::list to hold onto the copied C string and
413 // we don't have direct access to the elements, we have to iterate to
414 // find the value.
415 arg_sstr_collection::iterator pos, end = m_args.end();
416 size_t i = idx;
417 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
418 --i;
419
420 if (pos != end)
421 {
422 m_args.erase (pos);
423 assert(idx < m_argv.size() - 1);
424 m_argv.erase(m_argv.begin() + idx);
425 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
426 }
427}
428
429void
430Args::SetArguments (int argc, const char **argv)
431{
432 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
433 // no need to clear it here.
434 m_args.clear();
435 m_args_quote_char.clear();
436
437 // Make a copy of the arguments in our internal buffer
438 size_t i;
439 // First copy each string
440 for (i=0; i<argc; ++i)
441 {
442 m_args.push_back (argv[i]);
443 if ((argv[i][0] == '"') || (argv[i][0] == '`'))
444 m_args_quote_char.push_back (argv[i][0]);
445 else
446 m_args_quote_char.push_back ('\0');
447 }
448
449 UpdateArgvFromArgs();
450}
451
452
453Error
454Args::ParseOptions (Options &options)
455{
456 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000457 Error error;
458 struct option *long_options = options.GetLongOptions();
459 if (long_options == NULL)
460 {
461 error.SetErrorStringWithFormat("Invalid long options.\n");
462 return error;
463 }
464
Greg Claytonbef15832010-07-14 00:18:15 +0000465 for (int i=0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000466 {
467 if (long_options[i].flag == NULL)
468 {
469 sstr << (char)long_options[i].val;
470 switch (long_options[i].has_arg)
471 {
472 default:
473 case no_argument: break;
474 case required_argument: sstr << ':'; break;
475 case optional_argument: sstr << "::"; break;
476 }
477 }
478 }
Eli Friedmanef2bc872010-06-13 19:18:49 +0000479#ifdef __GLIBC__
480 optind = 0;
481#else
Chris Lattner24943d22010-06-08 16:52:24 +0000482 optreset = 1;
483 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000484#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000485 int val;
486 while (1)
487 {
488 int long_options_index = -1;
489 val = ::getopt_long(GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
490 &long_options_index);
491 if (val == -1)
492 break;
493
494 // Did we get an error?
495 if (val == '?')
496 {
497 error.SetErrorStringWithFormat("Unknown or ambiguous option.\n");
498 break;
499 }
500 // The option auto-set itself
501 if (val == 0)
502 continue;
503
504 ((Options *) &options)->OptionSeen (val);
505
506 // Lookup the long option index
507 if (long_options_index == -1)
508 {
509 for (int i=0;
510 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
511 ++i)
512 {
513 if (long_options[i].val == val)
514 {
515 long_options_index = i;
516 break;
517 }
518 }
519 }
520 // Call the callback with the option
521 if (long_options_index >= 0)
522 {
523 error = options.SetOptionValue(long_options_index,
524 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
525 }
526 else
527 {
528 error.SetErrorStringWithFormat("Invalid option with value '%i'.\n", val);
529 }
530 if (error.Fail())
531 break;
532 }
533
534 // Update our ARGV now that get options has consumed all the options
535 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
536 UpdateArgsAfterOptionParsing ();
537 return error;
538}
539
540void
541Args::Clear ()
542{
543 m_args.clear ();
544 m_argv.clear ();
545 m_args_quote_char.clear();
546}
547
548int32_t
549Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
550{
551 if (s && s[0])
552 {
553 char *end = NULL;
554 int32_t uval = ::strtol (s, &end, base);
555 if (*end == '\0')
556 {
557 if (success_ptr) *success_ptr = true;
558 return uval; // All characters were used, return the result
559 }
560 }
561 if (success_ptr) *success_ptr = false;
562 return fail_value;
563}
564
565uint32_t
566Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
567{
568 if (s && s[0])
569 {
570 char *end = NULL;
571 uint32_t uval = ::strtoul (s, &end, base);
572 if (*end == '\0')
573 {
574 if (success_ptr) *success_ptr = true;
575 return uval; // All characters were used, return the result
576 }
577 }
578 if (success_ptr) *success_ptr = false;
579 return fail_value;
580}
581
582
583int64_t
584Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
585{
586 if (s && s[0])
587 {
588 char *end = NULL;
589 int64_t uval = ::strtoll (s, &end, base);
590 if (*end == '\0')
591 {
592 if (success_ptr) *success_ptr = true;
593 return uval; // All characters were used, return the result
594 }
595 }
596 if (success_ptr) *success_ptr = false;
597 return fail_value;
598}
599
600uint64_t
601Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
602{
603 if (s && s[0])
604 {
605 char *end = NULL;
606 uint64_t uval = ::strtoull (s, &end, base);
607 if (*end == '\0')
608 {
609 if (success_ptr) *success_ptr = true;
610 return uval; // All characters were used, return the result
611 }
612 }
613 if (success_ptr) *success_ptr = false;
614 return fail_value;
615}
616
617lldb::addr_t
618Args::StringToAddress (const char *s, lldb::addr_t fail_value, bool *success_ptr)
619{
620 if (s && s[0])
621 {
622 char *end = NULL;
623 lldb::addr_t addr = ::strtoull (s, &end, 0);
624 if (*end == '\0')
625 {
626 if (success_ptr) *success_ptr = true;
627 return addr; // All characters were used, return the result
628 }
629 // Try base 16 with no prefix...
630 addr = ::strtoull (s, &end, 16);
631 if (*end == '\0')
632 {
633 if (success_ptr) *success_ptr = true;
634 return addr; // All characters were used, return the result
635 }
636 }
637 if (success_ptr) *success_ptr = false;
638 return fail_value;
639}
640
641bool
642Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
643{
644 if (s && s[0])
645 {
646 if (::strcasecmp (s, "false") == 0 ||
647 ::strcasecmp (s, "off") == 0 ||
648 ::strcasecmp (s, "no") == 0 ||
649 ::strcmp (s, "0") == 0)
650 {
651 if (success_ptr)
652 *success_ptr = true;
653 return false;
654 }
655 else
656 if (::strcasecmp (s, "true") == 0 ||
657 ::strcasecmp (s, "on") == 0 ||
658 ::strcasecmp (s, "yes") == 0 ||
659 ::strcmp (s, "1") == 0)
660 {
661 if (success_ptr) *success_ptr = true;
662 return true;
663 }
664 }
665 if (success_ptr) *success_ptr = false;
666 return fail_value;
667}
668
669int32_t
670Args::StringToOptionEnum (const char *s, lldb::OptionEnumValueElement *enum_values, int32_t fail_value, bool *success_ptr)
671{
672 if (enum_values && s && s[0])
673 {
674 for (int i = 0; enum_values[i].string_value != NULL ; i++)
675 {
676 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
677 {
678 if (success_ptr) *success_ptr = true;
679 return enum_values[i].value;
680 }
681 }
682 }
683 if (success_ptr) *success_ptr = false;
684
685 return fail_value;
686}
687
688ScriptLanguage
689Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
690{
691 if (s && s[0])
692 {
693 if ((::strcasecmp (s, "python") == 0) ||
694 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
695 {
696 if (success_ptr) *success_ptr = true;
697 return eScriptLanguagePython;
698 }
699 if (::strcasecmp (s, "none"))
700 {
701 if (success_ptr) *success_ptr = true;
702 return eScriptLanguageNone;
703 }
704 }
705 if (success_ptr) *success_ptr = false;
706 return fail_value;
707}
708
709Error
710Args::StringToFormat
711(
712 const char *s,
713 lldb::Format &format
714)
715{
716 format = eFormatInvalid;
717 Error error;
718
719 if (s && s[0])
720 {
721 switch (s[0])
722 {
723 case 'y': format = eFormatBytes; break;
724 case 'Y': format = eFormatBytesWithASCII; break;
725 case 'b': format = eFormatBinary; break;
726 case 'B': format = eFormatBoolean; break;
727 case 'c': format = eFormatChar; break;
728 case 'C': format = eFormatCharPrintable; break;
729 case 'o': format = eFormatOctal; break;
730 case 'i':
731 case 'd': format = eFormatDecimal; break;
732 case 'u': format = eFormatUnsigned; break;
733 case 'x': format = eFormatHex; break;
734 case 'f':
735 case 'e':
736 case 'g': format = eFormatFloat; break;
737 case 'p': format = eFormatPointer; break;
738 case 's': format = eFormatCString; break;
739 default:
740 error.SetErrorStringWithFormat("Invalid format character '%c'. Valid values are:\n"
741 " b - binary\n"
742 " B - boolean\n"
743 " c - char\n"
744 " C - printable char\n"
745 " d - signed decimal\n"
746 " e - float\n"
747 " f - float\n"
748 " g - float\n"
749 " i - signed decimal\n"
750 " o - octal\n"
751 " s - c-string\n"
752 " u - unsigned decimal\n"
753 " x - hex\n"
754 " y - bytes\n"
755 " Y - bytes with ASCII\n", s[0]);
756 break;
757 }
758
759 if (error.Fail())
760 return error;
761 }
762 else
763 {
764 error.SetErrorStringWithFormat("%s option string.\n", s ? "empty" : "invalid");
765 }
766 return error;
767}
768
769void
770Args::LongestCommonPrefix (std::string &common_prefix)
771{
772 arg_sstr_collection::iterator pos, end = m_args.end();
773 pos = m_args.begin();
774 if (pos == end)
775 common_prefix.clear();
776 else
777 common_prefix = (*pos);
778
779 for (++pos; pos != end; ++pos)
780 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000781 size_t new_size = (*pos).size();
Chris Lattner24943d22010-06-08 16:52:24 +0000782
783 // First trim common_prefix if it is longer than the current element:
784 if (common_prefix.size() > new_size)
785 common_prefix.erase (new_size);
786
787 // Then trim it at the first disparity:
788
Greg Clayton54e7afa2010-07-09 20:39:50 +0000789 for (size_t i = 0; i < common_prefix.size(); i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000790 {
791 if ((*pos)[i] != common_prefix[i])
792 {
793 common_prefix.erase(i);
794 break;
795 }
796 }
797
798 // If we've emptied the common prefix, we're done.
799 if (common_prefix.empty())
800 break;
801 }
802}
803
804void
805Args::ParseAliasOptions
806(
807 Options &options,
808 CommandReturnObject &result,
809 OptionArgVector *option_arg_vector
810)
811{
812 StreamString sstr;
813 int i;
814 struct option *long_options = options.GetLongOptions();
815
816 if (long_options == NULL)
817 {
818 result.AppendError ("invalid long options");
819 result.SetStatus (eReturnStatusFailed);
820 return;
821 }
822
823 for (i = 0; long_options[i].name != NULL; ++i)
824 {
825 if (long_options[i].flag == NULL)
826 {
827 sstr << (char) long_options[i].val;
828 switch (long_options[i].has_arg)
829 {
830 default:
831 case no_argument:
832 break;
833 case required_argument:
834 sstr << ":";
835 break;
836 case optional_argument:
837 sstr << "::";
838 break;
839 }
840 }
841 }
842
Eli Friedmanef2bc872010-06-13 19:18:49 +0000843#ifdef __GLIBC__
844 optind = 0;
845#else
Chris Lattner24943d22010-06-08 16:52:24 +0000846 optreset = 1;
847 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000848#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000849 int val;
850 while (1)
851 {
852 int long_options_index = -1;
853 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
854 &long_options_index);
855
856 if (val == -1)
857 break;
858
859 if (val == '?')
860 {
861 result.AppendError ("unknown or ambiguous option");
862 result.SetStatus (eReturnStatusFailed);
863 break;
864 }
865
866 if (val == 0)
867 continue;
868
869 ((Options *) &options)->OptionSeen (val);
870
871 // Look up the long option index
872 if (long_options_index == -1)
873 {
874 for (int j = 0;
875 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
876 ++j)
877 {
878 if (long_options[j].val == val)
879 {
880 long_options_index = j;
881 break;
882 }
883 }
884 }
885
886 // See if the option takes an argument, and see if one was supplied.
887 if (long_options_index >= 0)
888 {
889 StreamString option_str;
890 option_str.Printf ("-%c", (char) val);
891
892 switch (long_options[long_options_index].has_arg)
893 {
894 case no_argument:
895 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()), "<no-argument>"));
896 break;
897 case required_argument:
898 if (optarg != NULL)
899 {
900 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
901 std::string (optarg)));
902 result.SetStatus (eReturnStatusSuccessFinishNoResult);
903 }
904 else
905 {
906 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
907 option_str.GetData());
908 result.SetStatus (eReturnStatusFailed);
909 }
910 break;
911 case optional_argument:
912 if (optarg != NULL)
913 {
914 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
915 std::string (optarg)));
916 result.SetStatus (eReturnStatusSuccessFinishNoResult);
917 }
918 else
919 {
920 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
921 "<no-argument>"));
922 result.SetStatus (eReturnStatusSuccessFinishNoResult);
923 }
924 break;
925 default:
926 result.AppendErrorWithFormat
927 ("error with options table; invalid value in has_arg field for option '%c'.\n",
928 (char) val);
929 result.SetStatus (eReturnStatusFailed);
930 break;
931 }
932 }
933 else
934 {
935 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val);
936 result.SetStatus (eReturnStatusFailed);
937 }
938 if (!result.Succeeded())
939 break;
940 }
941}
942
943void
944Args::ParseArgsForCompletion
945(
946 Options &options,
Jim Inghamadb84292010-06-24 20:31:04 +0000947 OptionElementVector &option_element_vector,
948 uint32_t cursor_index
Chris Lattner24943d22010-06-08 16:52:24 +0000949)
950{
951 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000952 struct option *long_options = options.GetLongOptions();
953 option_element_vector.clear();
954
955 if (long_options == NULL)
956 {
957 return;
958 }
959
960 // Leading : tells getopt to return a : for a missing option argument AND
961 // to suppress error messages.
962
963 sstr << ":";
Greg Claytonbef15832010-07-14 00:18:15 +0000964 for (int i = 0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000965 {
966 if (long_options[i].flag == NULL)
967 {
968 sstr << (char) long_options[i].val;
969 switch (long_options[i].has_arg)
970 {
971 default:
972 case no_argument:
973 break;
974 case required_argument:
975 sstr << ":";
976 break;
977 case optional_argument:
978 sstr << "::";
979 break;
980 }
981 }
982 }
983
Eli Friedmanef2bc872010-06-13 19:18:49 +0000984#ifdef __GLIBC__
985 optind = 0;
986#else
Chris Lattner24943d22010-06-08 16:52:24 +0000987 optreset = 1;
988 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000989#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000990 opterr = 0;
991
992 int val;
993 const OptionDefinition *opt_defs = options.GetDefinitions();
994
Jim Inghamadb84292010-06-24 20:31:04 +0000995 // Fooey... getopt_long permutes the GetArgumentVector to move the options to the front.
Chris Lattner24943d22010-06-08 16:52:24 +0000996 // So we have to build another Arg and pass that to getopt_long so it doesn't
Jim Inghamadb84292010-06-24 20:31:04 +0000997 // change the one we have.
Chris Lattner24943d22010-06-08 16:52:24 +0000998
Greg Clayton54e7afa2010-07-09 20:39:50 +0000999 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001000
Jim Inghamadb84292010-06-24 20:31:04 +00001001 bool failed_once = false;
1002 uint32_t dash_dash_pos = -1;
1003
Chris Lattner24943d22010-06-08 16:52:24 +00001004 while (1)
1005 {
1006 bool missing_argument = false;
1007 int parse_start = optind;
1008 int long_options_index = -1;
Jim Inghamadb84292010-06-24 20:31:04 +00001009
Greg Clayton54e7afa2010-07-09 20:39:50 +00001010 val = ::getopt_long (dummy_vec.size() - 1,
Greg Clayton53d68e72010-07-20 22:52:08 +00001011 (char *const *) &dummy_vec.front(),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001012 sstr.GetData(),
1013 long_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001014 &long_options_index);
1015
1016 if (val == -1)
Jim Inghamadb84292010-06-24 20:31:04 +00001017 {
1018 // When we're completing a "--" which is the last option on line,
1019 if (failed_once)
1020 break;
1021
1022 failed_once = true;
1023
1024 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1025 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1026 // user might want to complete options by long name. I make this work by checking whether the
1027 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1028 // I let it pass to getopt_long which will terminate the option parsing.
1029 // Note, in either case we continue parsing the line so we can figure out what other options
1030 // were passed. This will be useful when we come to restricting completions based on what other
1031 // options we've seen on the line.
Chris Lattner24943d22010-06-08 16:52:24 +00001032
Jim Inghamadb84292010-06-24 20:31:04 +00001033 if (optind < dummy_vec.size() - 1
1034 && (strcmp (dummy_vec[optind-1], "--") == 0))
1035 {
1036 dash_dash_pos = optind - 1;
1037 if (optind - 1 == cursor_index)
1038 {
1039 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1040 OptionArgElement::eBareDoubleDash));
1041 continue;
1042 }
1043 else
1044 break;
1045 }
1046 else
1047 break;
1048 }
Chris Lattner24943d22010-06-08 16:52:24 +00001049 else if (val == '?')
1050 {
Jim Inghamadb84292010-06-24 20:31:04 +00001051 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1052 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001053 continue;
1054 }
1055 else if (val == 0)
1056 {
1057 continue;
1058 }
1059 else if (val == ':')
1060 {
1061 // This is a missing argument.
1062 val = optopt;
1063 missing_argument = true;
1064 }
1065
1066 ((Options *) &options)->OptionSeen (val);
1067
1068 // Look up the long option index
1069 if (long_options_index == -1)
1070 {
1071 for (int j = 0;
1072 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1073 ++j)
1074 {
1075 if (long_options[j].val == val)
1076 {
1077 long_options_index = j;
1078 break;
1079 }
1080 }
1081 }
1082
1083 // See if the option takes an argument, and see if one was supplied.
1084 if (long_options_index >= 0)
1085 {
1086 int opt_defs_index = -1;
1087 for (int i = 0; ; i++)
1088 {
1089 if (opt_defs[i].short_option == 0)
1090 break;
1091 else if (opt_defs[i].short_option == val)
1092 {
1093 opt_defs_index = i;
1094 break;
1095 }
1096 }
1097
1098 switch (long_options[long_options_index].has_arg)
1099 {
1100 case no_argument:
1101 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1102 break;
1103 case required_argument:
1104 if (optarg != NULL)
1105 {
1106 int arg_index;
1107 if (missing_argument)
1108 arg_index = -1;
1109 else
Jim Inghamadb84292010-06-24 20:31:04 +00001110 arg_index = optind - 1;
Chris Lattner24943d22010-06-08 16:52:24 +00001111
Jim Inghamadb84292010-06-24 20:31:04 +00001112 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
Chris Lattner24943d22010-06-08 16:52:24 +00001113 }
1114 else
1115 {
Jim Inghamadb84292010-06-24 20:31:04 +00001116 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
Chris Lattner24943d22010-06-08 16:52:24 +00001117 }
1118 break;
1119 case optional_argument:
1120 if (optarg != NULL)
1121 {
Jim Inghamadb84292010-06-24 20:31:04 +00001122 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001123 }
1124 else
1125 {
Jim Inghamadb84292010-06-24 20:31:04 +00001126 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001127 }
1128 break;
1129 default:
1130 // The options table is messed up. Here we'll just continue
Jim Inghamadb84292010-06-24 20:31:04 +00001131 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1132 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001133 break;
1134 }
1135 }
1136 else
1137 {
Jim Inghamadb84292010-06-24 20:31:04 +00001138 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1139 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001140 }
1141 }
Jim Inghamadb84292010-06-24 20:31:04 +00001142
1143 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1144 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long just ignores
1145 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1146
1147 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1148 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1149 {
1150 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1151 OptionArgElement::eBareDash));
1152
1153 }
Chris Lattner24943d22010-06-08 16:52:24 +00001154}