blob: 78c1003e5756a10ef6211e6a8c3d750db57c8233 [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;
457 int i;
458 Error error;
459 struct option *long_options = options.GetLongOptions();
460 if (long_options == NULL)
461 {
462 error.SetErrorStringWithFormat("Invalid long options.\n");
463 return error;
464 }
465
466 for (i=0; long_options[i].name != NULL; ++i)
467 {
468 if (long_options[i].flag == NULL)
469 {
470 sstr << (char)long_options[i].val;
471 switch (long_options[i].has_arg)
472 {
473 default:
474 case no_argument: break;
475 case required_argument: sstr << ':'; break;
476 case optional_argument: sstr << "::"; break;
477 }
478 }
479 }
Eli Friedmanef2bc872010-06-13 19:18:49 +0000480#ifdef __GLIBC__
481 optind = 0;
482#else
Chris Lattner24943d22010-06-08 16:52:24 +0000483 optreset = 1;
484 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000485#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000486 int val;
487 while (1)
488 {
489 int long_options_index = -1;
490 val = ::getopt_long(GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
491 &long_options_index);
492 if (val == -1)
493 break;
494
495 // Did we get an error?
496 if (val == '?')
497 {
498 error.SetErrorStringWithFormat("Unknown or ambiguous option.\n");
499 break;
500 }
501 // The option auto-set itself
502 if (val == 0)
503 continue;
504
505 ((Options *) &options)->OptionSeen (val);
506
507 // Lookup the long option index
508 if (long_options_index == -1)
509 {
510 for (int i=0;
511 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
512 ++i)
513 {
514 if (long_options[i].val == val)
515 {
516 long_options_index = i;
517 break;
518 }
519 }
520 }
521 // Call the callback with the option
522 if (long_options_index >= 0)
523 {
524 error = options.SetOptionValue(long_options_index,
525 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
526 }
527 else
528 {
529 error.SetErrorStringWithFormat("Invalid option with value '%i'.\n", val);
530 }
531 if (error.Fail())
532 break;
533 }
534
535 // Update our ARGV now that get options has consumed all the options
536 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
537 UpdateArgsAfterOptionParsing ();
538 return error;
539}
540
541void
542Args::Clear ()
543{
544 m_args.clear ();
545 m_argv.clear ();
546 m_args_quote_char.clear();
547}
548
549int32_t
550Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
551{
552 if (s && s[0])
553 {
554 char *end = NULL;
555 int32_t uval = ::strtol (s, &end, base);
556 if (*end == '\0')
557 {
558 if (success_ptr) *success_ptr = true;
559 return uval; // All characters were used, return the result
560 }
561 }
562 if (success_ptr) *success_ptr = false;
563 return fail_value;
564}
565
566uint32_t
567Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
568{
569 if (s && s[0])
570 {
571 char *end = NULL;
572 uint32_t uval = ::strtoul (s, &end, base);
573 if (*end == '\0')
574 {
575 if (success_ptr) *success_ptr = true;
576 return uval; // All characters were used, return the result
577 }
578 }
579 if (success_ptr) *success_ptr = false;
580 return fail_value;
581}
582
583
584int64_t
585Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
586{
587 if (s && s[0])
588 {
589 char *end = NULL;
590 int64_t uval = ::strtoll (s, &end, base);
591 if (*end == '\0')
592 {
593 if (success_ptr) *success_ptr = true;
594 return uval; // All characters were used, return the result
595 }
596 }
597 if (success_ptr) *success_ptr = false;
598 return fail_value;
599}
600
601uint64_t
602Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
603{
604 if (s && s[0])
605 {
606 char *end = NULL;
607 uint64_t uval = ::strtoull (s, &end, base);
608 if (*end == '\0')
609 {
610 if (success_ptr) *success_ptr = true;
611 return uval; // All characters were used, return the result
612 }
613 }
614 if (success_ptr) *success_ptr = false;
615 return fail_value;
616}
617
618lldb::addr_t
619Args::StringToAddress (const char *s, lldb::addr_t fail_value, bool *success_ptr)
620{
621 if (s && s[0])
622 {
623 char *end = NULL;
624 lldb::addr_t addr = ::strtoull (s, &end, 0);
625 if (*end == '\0')
626 {
627 if (success_ptr) *success_ptr = true;
628 return addr; // All characters were used, return the result
629 }
630 // Try base 16 with no prefix...
631 addr = ::strtoull (s, &end, 16);
632 if (*end == '\0')
633 {
634 if (success_ptr) *success_ptr = true;
635 return addr; // All characters were used, return the result
636 }
637 }
638 if (success_ptr) *success_ptr = false;
639 return fail_value;
640}
641
642bool
643Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
644{
645 if (s && s[0])
646 {
647 if (::strcasecmp (s, "false") == 0 ||
648 ::strcasecmp (s, "off") == 0 ||
649 ::strcasecmp (s, "no") == 0 ||
650 ::strcmp (s, "0") == 0)
651 {
652 if (success_ptr)
653 *success_ptr = true;
654 return false;
655 }
656 else
657 if (::strcasecmp (s, "true") == 0 ||
658 ::strcasecmp (s, "on") == 0 ||
659 ::strcasecmp (s, "yes") == 0 ||
660 ::strcmp (s, "1") == 0)
661 {
662 if (success_ptr) *success_ptr = true;
663 return true;
664 }
665 }
666 if (success_ptr) *success_ptr = false;
667 return fail_value;
668}
669
670int32_t
671Args::StringToOptionEnum (const char *s, lldb::OptionEnumValueElement *enum_values, int32_t fail_value, bool *success_ptr)
672{
673 if (enum_values && s && s[0])
674 {
675 for (int i = 0; enum_values[i].string_value != NULL ; i++)
676 {
677 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
678 {
679 if (success_ptr) *success_ptr = true;
680 return enum_values[i].value;
681 }
682 }
683 }
684 if (success_ptr) *success_ptr = false;
685
686 return fail_value;
687}
688
689ScriptLanguage
690Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
691{
692 if (s && s[0])
693 {
694 if ((::strcasecmp (s, "python") == 0) ||
695 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
696 {
697 if (success_ptr) *success_ptr = true;
698 return eScriptLanguagePython;
699 }
700 if (::strcasecmp (s, "none"))
701 {
702 if (success_ptr) *success_ptr = true;
703 return eScriptLanguageNone;
704 }
705 }
706 if (success_ptr) *success_ptr = false;
707 return fail_value;
708}
709
710Error
711Args::StringToFormat
712(
713 const char *s,
714 lldb::Format &format
715)
716{
717 format = eFormatInvalid;
718 Error error;
719
720 if (s && s[0])
721 {
722 switch (s[0])
723 {
724 case 'y': format = eFormatBytes; break;
725 case 'Y': format = eFormatBytesWithASCII; break;
726 case 'b': format = eFormatBinary; break;
727 case 'B': format = eFormatBoolean; break;
728 case 'c': format = eFormatChar; break;
729 case 'C': format = eFormatCharPrintable; break;
730 case 'o': format = eFormatOctal; break;
731 case 'i':
732 case 'd': format = eFormatDecimal; break;
733 case 'u': format = eFormatUnsigned; break;
734 case 'x': format = eFormatHex; break;
735 case 'f':
736 case 'e':
737 case 'g': format = eFormatFloat; break;
738 case 'p': format = eFormatPointer; break;
739 case 's': format = eFormatCString; break;
740 default:
741 error.SetErrorStringWithFormat("Invalid format character '%c'. Valid values are:\n"
742 " b - binary\n"
743 " B - boolean\n"
744 " c - char\n"
745 " C - printable char\n"
746 " d - signed decimal\n"
747 " e - float\n"
748 " f - float\n"
749 " g - float\n"
750 " i - signed decimal\n"
751 " o - octal\n"
752 " s - c-string\n"
753 " u - unsigned decimal\n"
754 " x - hex\n"
755 " y - bytes\n"
756 " Y - bytes with ASCII\n", s[0]);
757 break;
758 }
759
760 if (error.Fail())
761 return error;
762 }
763 else
764 {
765 error.SetErrorStringWithFormat("%s option string.\n", s ? "empty" : "invalid");
766 }
767 return error;
768}
769
770void
771Args::LongestCommonPrefix (std::string &common_prefix)
772{
773 arg_sstr_collection::iterator pos, end = m_args.end();
774 pos = m_args.begin();
775 if (pos == end)
776 common_prefix.clear();
777 else
778 common_prefix = (*pos);
779
780 for (++pos; pos != end; ++pos)
781 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000782 size_t new_size = (*pos).size();
Chris Lattner24943d22010-06-08 16:52:24 +0000783
784 // First trim common_prefix if it is longer than the current element:
785 if (common_prefix.size() > new_size)
786 common_prefix.erase (new_size);
787
788 // Then trim it at the first disparity:
789
Greg Clayton54e7afa2010-07-09 20:39:50 +0000790 for (size_t i = 0; i < common_prefix.size(); i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000791 {
792 if ((*pos)[i] != common_prefix[i])
793 {
794 common_prefix.erase(i);
795 break;
796 }
797 }
798
799 // If we've emptied the common prefix, we're done.
800 if (common_prefix.empty())
801 break;
802 }
803}
804
805void
806Args::ParseAliasOptions
807(
808 Options &options,
809 CommandReturnObject &result,
810 OptionArgVector *option_arg_vector
811)
812{
813 StreamString sstr;
814 int i;
815 struct option *long_options = options.GetLongOptions();
816
817 if (long_options == NULL)
818 {
819 result.AppendError ("invalid long options");
820 result.SetStatus (eReturnStatusFailed);
821 return;
822 }
823
824 for (i = 0; long_options[i].name != NULL; ++i)
825 {
826 if (long_options[i].flag == NULL)
827 {
828 sstr << (char) long_options[i].val;
829 switch (long_options[i].has_arg)
830 {
831 default:
832 case no_argument:
833 break;
834 case required_argument:
835 sstr << ":";
836 break;
837 case optional_argument:
838 sstr << "::";
839 break;
840 }
841 }
842 }
843
Eli Friedmanef2bc872010-06-13 19:18:49 +0000844#ifdef __GLIBC__
845 optind = 0;
846#else
Chris Lattner24943d22010-06-08 16:52:24 +0000847 optreset = 1;
848 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000849#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000850 int val;
851 while (1)
852 {
853 int long_options_index = -1;
854 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
855 &long_options_index);
856
857 if (val == -1)
858 break;
859
860 if (val == '?')
861 {
862 result.AppendError ("unknown or ambiguous option");
863 result.SetStatus (eReturnStatusFailed);
864 break;
865 }
866
867 if (val == 0)
868 continue;
869
870 ((Options *) &options)->OptionSeen (val);
871
872 // Look up the long option index
873 if (long_options_index == -1)
874 {
875 for (int j = 0;
876 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
877 ++j)
878 {
879 if (long_options[j].val == val)
880 {
881 long_options_index = j;
882 break;
883 }
884 }
885 }
886
887 // See if the option takes an argument, and see if one was supplied.
888 if (long_options_index >= 0)
889 {
890 StreamString option_str;
891 option_str.Printf ("-%c", (char) val);
892
893 switch (long_options[long_options_index].has_arg)
894 {
895 case no_argument:
896 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()), "<no-argument>"));
897 break;
898 case required_argument:
899 if (optarg != NULL)
900 {
901 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
902 std::string (optarg)));
903 result.SetStatus (eReturnStatusSuccessFinishNoResult);
904 }
905 else
906 {
907 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
908 option_str.GetData());
909 result.SetStatus (eReturnStatusFailed);
910 }
911 break;
912 case optional_argument:
913 if (optarg != NULL)
914 {
915 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
916 std::string (optarg)));
917 result.SetStatus (eReturnStatusSuccessFinishNoResult);
918 }
919 else
920 {
921 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
922 "<no-argument>"));
923 result.SetStatus (eReturnStatusSuccessFinishNoResult);
924 }
925 break;
926 default:
927 result.AppendErrorWithFormat
928 ("error with options table; invalid value in has_arg field for option '%c'.\n",
929 (char) val);
930 result.SetStatus (eReturnStatusFailed);
931 break;
932 }
933 }
934 else
935 {
936 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val);
937 result.SetStatus (eReturnStatusFailed);
938 }
939 if (!result.Succeeded())
940 break;
941 }
942}
943
944void
945Args::ParseArgsForCompletion
946(
947 Options &options,
Jim Inghamadb84292010-06-24 20:31:04 +0000948 OptionElementVector &option_element_vector,
949 uint32_t cursor_index
Chris Lattner24943d22010-06-08 16:52:24 +0000950)
951{
952 StreamString sstr;
953 int i;
954 struct option *long_options = options.GetLongOptions();
955 option_element_vector.clear();
956
957 if (long_options == NULL)
958 {
959 return;
960 }
961
962 // Leading : tells getopt to return a : for a missing option argument AND
963 // to suppress error messages.
964
965 sstr << ":";
966 for (i = 0; long_options[i].name != NULL; ++i)
967 {
968 if (long_options[i].flag == NULL)
969 {
970 sstr << (char) long_options[i].val;
971 switch (long_options[i].has_arg)
972 {
973 default:
974 case no_argument:
975 break;
976 case required_argument:
977 sstr << ":";
978 break;
979 case optional_argument:
980 sstr << "::";
981 break;
982 }
983 }
984 }
985
Eli Friedmanef2bc872010-06-13 19:18:49 +0000986#ifdef __GLIBC__
987 optind = 0;
988#else
Chris Lattner24943d22010-06-08 16:52:24 +0000989 optreset = 1;
990 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000991#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000992 opterr = 0;
993
994 int val;
995 const OptionDefinition *opt_defs = options.GetDefinitions();
996
Jim Inghamadb84292010-06-24 20:31:04 +0000997 // Fooey... getopt_long permutes the GetArgumentVector to move the options to the front.
Chris Lattner24943d22010-06-08 16:52:24 +0000998 // So we have to build another Arg and pass that to getopt_long so it doesn't
Jim Inghamadb84292010-06-24 20:31:04 +0000999 // change the one we have.
Chris Lattner24943d22010-06-08 16:52:24 +00001000
Greg Clayton54e7afa2010-07-09 20:39:50 +00001001 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001002
Jim Inghamadb84292010-06-24 20:31:04 +00001003 bool failed_once = false;
1004 uint32_t dash_dash_pos = -1;
1005
Chris Lattner24943d22010-06-08 16:52:24 +00001006 while (1)
1007 {
1008 bool missing_argument = false;
1009 int parse_start = optind;
1010 int long_options_index = -1;
Jim Inghamadb84292010-06-24 20:31:04 +00001011
Greg Clayton54e7afa2010-07-09 20:39:50 +00001012 val = ::getopt_long (dummy_vec.size() - 1,
1013 (char *const *) dummy_vec.data(),
1014 sstr.GetData(),
1015 long_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001016 &long_options_index);
1017
1018 if (val == -1)
Jim Inghamadb84292010-06-24 20:31:04 +00001019 {
1020 // When we're completing a "--" which is the last option on line,
1021 if (failed_once)
1022 break;
1023
1024 failed_once = true;
1025
1026 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1027 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1028 // user might want to complete options by long name. I make this work by checking whether the
1029 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1030 // I let it pass to getopt_long which will terminate the option parsing.
1031 // Note, in either case we continue parsing the line so we can figure out what other options
1032 // were passed. This will be useful when we come to restricting completions based on what other
1033 // options we've seen on the line.
Chris Lattner24943d22010-06-08 16:52:24 +00001034
Jim Inghamadb84292010-06-24 20:31:04 +00001035 if (optind < dummy_vec.size() - 1
1036 && (strcmp (dummy_vec[optind-1], "--") == 0))
1037 {
1038 dash_dash_pos = optind - 1;
1039 if (optind - 1 == cursor_index)
1040 {
1041 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1042 OptionArgElement::eBareDoubleDash));
1043 continue;
1044 }
1045 else
1046 break;
1047 }
1048 else
1049 break;
1050 }
Chris Lattner24943d22010-06-08 16:52:24 +00001051 else if (val == '?')
1052 {
Jim Inghamadb84292010-06-24 20:31:04 +00001053 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1054 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001055 continue;
1056 }
1057 else if (val == 0)
1058 {
1059 continue;
1060 }
1061 else if (val == ':')
1062 {
1063 // This is a missing argument.
1064 val = optopt;
1065 missing_argument = true;
1066 }
1067
1068 ((Options *) &options)->OptionSeen (val);
1069
1070 // Look up the long option index
1071 if (long_options_index == -1)
1072 {
1073 for (int j = 0;
1074 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1075 ++j)
1076 {
1077 if (long_options[j].val == val)
1078 {
1079 long_options_index = j;
1080 break;
1081 }
1082 }
1083 }
1084
1085 // See if the option takes an argument, and see if one was supplied.
1086 if (long_options_index >= 0)
1087 {
1088 int opt_defs_index = -1;
1089 for (int i = 0; ; i++)
1090 {
1091 if (opt_defs[i].short_option == 0)
1092 break;
1093 else if (opt_defs[i].short_option == val)
1094 {
1095 opt_defs_index = i;
1096 break;
1097 }
1098 }
1099
1100 switch (long_options[long_options_index].has_arg)
1101 {
1102 case no_argument:
1103 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1104 break;
1105 case required_argument:
1106 if (optarg != NULL)
1107 {
1108 int arg_index;
1109 if (missing_argument)
1110 arg_index = -1;
1111 else
Jim Inghamadb84292010-06-24 20:31:04 +00001112 arg_index = optind - 1;
Chris Lattner24943d22010-06-08 16:52:24 +00001113
Jim Inghamadb84292010-06-24 20:31:04 +00001114 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
Chris Lattner24943d22010-06-08 16:52:24 +00001115 }
1116 else
1117 {
Jim Inghamadb84292010-06-24 20:31:04 +00001118 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
Chris Lattner24943d22010-06-08 16:52:24 +00001119 }
1120 break;
1121 case optional_argument:
1122 if (optarg != NULL)
1123 {
Jim Inghamadb84292010-06-24 20:31:04 +00001124 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001125 }
1126 else
1127 {
Jim Inghamadb84292010-06-24 20:31:04 +00001128 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001129 }
1130 break;
1131 default:
1132 // The options table is messed up. Here we'll just continue
Jim Inghamadb84292010-06-24 20:31:04 +00001133 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1134 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001135 break;
1136 }
1137 }
1138 else
1139 {
Jim Inghamadb84292010-06-24 20:31:04 +00001140 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1141 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001142 }
1143 }
Jim Inghamadb84292010-06-24 20:31:04 +00001144
1145 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1146 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long just ignores
1147 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1148
1149 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1150 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1151 {
1152 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1153 OptionArgElement::eBareDash));
1154
1155 }
Chris Lattner24943d22010-06-08 16:52:24 +00001156}