blob: e5264e593bd6980985c4e56a99687a8eb94d5b21 [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
Caroline Ticed9105c22010-12-10 00:26:54 +000096bool
97Args::GetQuotedCommandString (std::string &command)
98{
99 command.clear ();
100 int argc = GetArgumentCount ();
101 for (int i = 0; i < argc; ++i)
102 {
103 if (i > 0)
104 command += ' ';
105 char quote_char = m_args_quote_char[i];
106 if (quote_char != '\0')
107 {
108 command += quote_char;
109 command += m_argv[i];
110 command += quote_char;
111 }
112 else
113 command += m_argv[i];
114 }
115 return argc > 0;
116}
117
Chris Lattner24943d22010-06-08 16:52:24 +0000118void
119Args::SetCommandString (const char *command, size_t len)
120{
121 // Use std::string to make sure we get a NULL terminated string we can use
122 // as "command" could point to a string within a large string....
123 std::string null_terminated_command(command, len);
124 SetCommandString(null_terminated_command.c_str());
125}
126
127void
128Args::SetCommandString (const char *command)
129{
130 m_args.clear();
131 m_argv.clear();
132 if (command && command[0])
133 {
134 const char *arg_start;
135 const char *next_arg_start;
136 for (arg_start = command, next_arg_start = NULL;
137 arg_start && arg_start[0];
138 arg_start = next_arg_start, next_arg_start = NULL)
139 {
140 // Skip any leading space characters
141 arg_start = ::strspn (arg_start, k_space_characters) + arg_start;
142
143 // If there were only space characters to the end of the line, then
144 // we're done.
145 if (*arg_start == '\0')
146 break;
147
148 std::string arg;
149 const char *arg_end = NULL;
150
151 switch (*arg_start)
152 {
153 case '\'':
154 case '"':
155 case '`':
156 {
157 // Look for either a quote character, or the backslash
158 // character
159 const char quote_char = *arg_start;
160 char find_chars[3] = { quote_char, '\\' , '\0'};
161 bool is_backtick = (quote_char == '`');
162 if (quote_char == '"' || quote_char == '`')
163 m_args_quote_char.push_back(quote_char);
164 else
165 m_args_quote_char.push_back('\0');
166
167 while (*arg_start != '\0')
168 {
169 arg_end = ::strcspn (arg_start + 1, find_chars) + arg_start + 1;
170
171 if (*arg_end == '\0')
172 {
173 arg.append (arg_start);
174 break;
175 }
176
177 // Watch out for quote characters prefixed with '\'
178 if (*arg_end == '\\')
179 {
180 if (arg_end[1] == quote_char)
181 {
182 // The character following the '\' is our quote
183 // character so strip the backslash character
184 arg.append (arg_start, arg_end);
185 }
186 else
187 {
188 // The character following the '\' is NOT our
189 // quote character, so include the backslash
190 // and continue
191 arg.append (arg_start, arg_end + 1);
192 }
193 arg_start = arg_end + 1;
194 continue;
195 }
196 else
197 {
198 arg.append (arg_start, arg_end + 1);
199 next_arg_start = arg_end + 1;
200 break;
201 }
202 }
203
204 // Skip single and double quotes, but leave backtick quotes
205 if (!is_backtick)
206 {
207 char first_c = arg[0];
208 arg.erase(0,1);
209 // Only erase the last character if it is the same as the first.
210 // Otherwise, we're parsing an incomplete command line, and we
211 // would be stripping off the last character of that string.
212 if (arg[arg.size() - 1] == first_c)
213 arg.erase(arg.size() - 1, 1);
214 }
215 }
216 break;
217 default:
218 {
219 m_args_quote_char.push_back('\0');
220 // Look for the next non-escaped space character
221 while (*arg_start != '\0')
222 {
223 arg_end = ::strcspn (arg_start, k_space_characters_with_slash) + arg_start;
224
225 if (arg_end == NULL)
226 {
227 arg.append(arg_start);
228 break;
229 }
230
231 if (*arg_end == '\\')
232 {
233 // Append up to the '\' char
234 arg.append (arg_start, arg_end);
235
236 if (arg_end[1] == '\0')
237 break;
238
239 // Append the character following the '\' if it isn't
240 // the end of the string
241 arg.append (1, arg_end[1]);
242 arg_start = arg_end + 2;
243 continue;
244 }
245 else
246 {
247 arg.append (arg_start, arg_end);
248 next_arg_start = arg_end;
249 break;
250 }
251 }
252 }
253 break;
254 }
255
256 m_args.push_back(arg);
257 }
258 }
259 UpdateArgvFromArgs();
260}
261
262void
263Args::UpdateArgsAfterOptionParsing()
264{
265 // Now m_argv might be out of date with m_args, so we need to fix that
266 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
267 arg_sstr_collection::iterator args_pos;
268 arg_quote_char_collection::iterator quotes_pos;
269
270 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
271 argv_pos != argv_end && args_pos != m_args.end();
272 ++argv_pos)
273 {
274 const char *argv_cstr = *argv_pos;
275 if (argv_cstr == NULL)
276 break;
277
278 while (args_pos != m_args.end())
279 {
280 const char *args_cstr = args_pos->c_str();
281 if (args_cstr == argv_cstr)
282 {
283 // We found the argument that matches the C string in the
284 // vector, so we can now look for the next one
285 ++args_pos;
286 ++quotes_pos;
287 break;
288 }
289 else
290 {
291 quotes_pos = m_args_quote_char.erase (quotes_pos);
292 args_pos = m_args.erase (args_pos);
293 }
294 }
295 }
296
297 if (args_pos != m_args.end())
298 m_args.erase (args_pos, m_args.end());
299
300 if (quotes_pos != m_args_quote_char.end())
301 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
302}
303
304void
305Args::UpdateArgvFromArgs()
306{
307 m_argv.clear();
308 arg_sstr_collection::const_iterator pos, end = m_args.end();
309 for (pos = m_args.begin(); pos != end; ++pos)
310 m_argv.push_back(pos->c_str());
311 m_argv.push_back(NULL);
312}
313
314size_t
315Args::GetArgumentCount() const
316{
317 if (m_argv.empty())
318 return 0;
319 return m_argv.size() - 1;
320}
321
322const char *
323Args::GetArgumentAtIndex (size_t idx) const
324{
325 if (idx < m_argv.size())
326 return m_argv[idx];
327 return NULL;
328}
329
330char
331Args::GetArgumentQuoteCharAtIndex (size_t idx) const
332{
333 if (idx < m_args_quote_char.size())
334 return m_args_quote_char[idx];
335 return '\0';
336}
337
338char **
339Args::GetArgumentVector()
340{
341 if (!m_argv.empty())
342 return (char **)&m_argv[0];
343 return NULL;
344}
345
346const char **
347Args::GetConstArgumentVector() const
348{
349 if (!m_argv.empty())
350 return (const char **)&m_argv[0];
351 return NULL;
352}
353
354void
355Args::Shift ()
356{
357 // Don't pop the last NULL terminator from the argv array
358 if (m_argv.size() > 1)
359 {
360 m_argv.erase(m_argv.begin());
361 m_args.pop_front();
362 m_args_quote_char.erase(m_args_quote_char.begin());
363 }
364}
365
366const char *
367Args::Unshift (const char *arg_cstr, char quote_char)
368{
369 m_args.push_front(arg_cstr);
370 m_argv.insert(m_argv.begin(), m_args.front().c_str());
371 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
372 return GetArgumentAtIndex (0);
373}
374
375void
376Args::AppendArguments (const Args &rhs)
377{
378 const size_t rhs_argc = rhs.GetArgumentCount();
379 for (size_t i=0; i<rhs_argc; ++i)
380 AppendArgument(rhs.GetArgumentAtIndex(i));
381}
382
383const char *
384Args::AppendArgument (const char *arg_cstr, char quote_char)
385{
386 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
387}
388
389const char *
390Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
391{
392 // Since we are using a std::list to hold onto the copied C string and
393 // we don't have direct access to the elements, we have to iterate to
394 // find the value.
395 arg_sstr_collection::iterator pos, end = m_args.end();
396 size_t i = idx;
397 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
398 --i;
399
400 pos = m_args.insert(pos, arg_cstr);
401
402
403 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
404
405 UpdateArgvFromArgs();
406 return GetArgumentAtIndex(idx);
407}
408
409const char *
410Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
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 pos->assign(arg_cstr);
423 assert(idx < m_argv.size() - 1);
424 m_argv[idx] = pos->c_str();
425 m_args_quote_char[idx] = quote_char;
426 return GetArgumentAtIndex(idx);
427 }
428 return NULL;
429}
430
431void
432Args::DeleteArgumentAtIndex (size_t idx)
433{
434 // Since we are using a std::list to hold onto the copied C string and
435 // we don't have direct access to the elements, we have to iterate to
436 // find the value.
437 arg_sstr_collection::iterator pos, end = m_args.end();
438 size_t i = idx;
439 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
440 --i;
441
442 if (pos != end)
443 {
444 m_args.erase (pos);
445 assert(idx < m_argv.size() - 1);
446 m_argv.erase(m_argv.begin() + idx);
447 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
448 }
449}
450
451void
452Args::SetArguments (int argc, const char **argv)
453{
454 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
455 // no need to clear it here.
456 m_args.clear();
457 m_args_quote_char.clear();
458
459 // Make a copy of the arguments in our internal buffer
460 size_t i;
461 // First copy each string
462 for (i=0; i<argc; ++i)
463 {
464 m_args.push_back (argv[i]);
465 if ((argv[i][0] == '"') || (argv[i][0] == '`'))
466 m_args_quote_char.push_back (argv[i][0]);
467 else
468 m_args_quote_char.push_back ('\0');
469 }
470
471 UpdateArgvFromArgs();
472}
473
474
475Error
476Args::ParseOptions (Options &options)
477{
478 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000479 Error error;
480 struct option *long_options = options.GetLongOptions();
481 if (long_options == NULL)
482 {
483 error.SetErrorStringWithFormat("Invalid long options.\n");
484 return error;
485 }
486
Greg Claytonbef15832010-07-14 00:18:15 +0000487 for (int i=0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000488 {
489 if (long_options[i].flag == NULL)
490 {
491 sstr << (char)long_options[i].val;
492 switch (long_options[i].has_arg)
493 {
494 default:
495 case no_argument: break;
496 case required_argument: sstr << ':'; break;
497 case optional_argument: sstr << "::"; break;
498 }
499 }
500 }
Eli Friedmanef2bc872010-06-13 19:18:49 +0000501#ifdef __GLIBC__
502 optind = 0;
503#else
Chris Lattner24943d22010-06-08 16:52:24 +0000504 optreset = 1;
505 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000506#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000507 int val;
508 while (1)
509 {
510 int long_options_index = -1;
511 val = ::getopt_long(GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
512 &long_options_index);
513 if (val == -1)
514 break;
515
516 // Did we get an error?
517 if (val == '?')
518 {
519 error.SetErrorStringWithFormat("Unknown or ambiguous option.\n");
520 break;
521 }
522 // The option auto-set itself
523 if (val == 0)
524 continue;
525
526 ((Options *) &options)->OptionSeen (val);
527
528 // Lookup the long option index
529 if (long_options_index == -1)
530 {
531 for (int i=0;
532 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
533 ++i)
534 {
535 if (long_options[i].val == val)
536 {
537 long_options_index = i;
538 break;
539 }
540 }
541 }
542 // Call the callback with the option
543 if (long_options_index >= 0)
544 {
545 error = options.SetOptionValue(long_options_index,
546 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
547 }
548 else
549 {
550 error.SetErrorStringWithFormat("Invalid option with value '%i'.\n", val);
551 }
552 if (error.Fail())
553 break;
554 }
555
556 // Update our ARGV now that get options has consumed all the options
557 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
558 UpdateArgsAfterOptionParsing ();
559 return error;
560}
561
562void
563Args::Clear ()
564{
565 m_args.clear ();
566 m_argv.clear ();
567 m_args_quote_char.clear();
568}
569
570int32_t
571Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
572{
573 if (s && s[0])
574 {
575 char *end = NULL;
576 int32_t uval = ::strtol (s, &end, base);
577 if (*end == '\0')
578 {
579 if (success_ptr) *success_ptr = true;
580 return uval; // All characters were used, return the result
581 }
582 }
583 if (success_ptr) *success_ptr = false;
584 return fail_value;
585}
586
587uint32_t
588Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
589{
590 if (s && s[0])
591 {
592 char *end = NULL;
593 uint32_t uval = ::strtoul (s, &end, base);
594 if (*end == '\0')
595 {
596 if (success_ptr) *success_ptr = true;
597 return uval; // All characters were used, return the result
598 }
599 }
600 if (success_ptr) *success_ptr = false;
601 return fail_value;
602}
603
604
605int64_t
606Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
607{
608 if (s && s[0])
609 {
610 char *end = NULL;
611 int64_t uval = ::strtoll (s, &end, base);
612 if (*end == '\0')
613 {
614 if (success_ptr) *success_ptr = true;
615 return uval; // All characters were used, return the result
616 }
617 }
618 if (success_ptr) *success_ptr = false;
619 return fail_value;
620}
621
622uint64_t
623Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
624{
625 if (s && s[0])
626 {
627 char *end = NULL;
628 uint64_t uval = ::strtoull (s, &end, base);
629 if (*end == '\0')
630 {
631 if (success_ptr) *success_ptr = true;
632 return uval; // All characters were used, return the result
633 }
634 }
635 if (success_ptr) *success_ptr = false;
636 return fail_value;
637}
638
639lldb::addr_t
640Args::StringToAddress (const char *s, lldb::addr_t fail_value, bool *success_ptr)
641{
642 if (s && s[0])
643 {
644 char *end = NULL;
645 lldb::addr_t addr = ::strtoull (s, &end, 0);
646 if (*end == '\0')
647 {
648 if (success_ptr) *success_ptr = true;
649 return addr; // All characters were used, return the result
650 }
651 // Try base 16 with no prefix...
652 addr = ::strtoull (s, &end, 16);
653 if (*end == '\0')
654 {
655 if (success_ptr) *success_ptr = true;
656 return addr; // All characters were used, return the result
657 }
658 }
659 if (success_ptr) *success_ptr = false;
660 return fail_value;
661}
662
663bool
664Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
665{
666 if (s && s[0])
667 {
668 if (::strcasecmp (s, "false") == 0 ||
669 ::strcasecmp (s, "off") == 0 ||
670 ::strcasecmp (s, "no") == 0 ||
671 ::strcmp (s, "0") == 0)
672 {
673 if (success_ptr)
674 *success_ptr = true;
675 return false;
676 }
677 else
678 if (::strcasecmp (s, "true") == 0 ||
679 ::strcasecmp (s, "on") == 0 ||
680 ::strcasecmp (s, "yes") == 0 ||
681 ::strcmp (s, "1") == 0)
682 {
683 if (success_ptr) *success_ptr = true;
684 return true;
685 }
686 }
687 if (success_ptr) *success_ptr = false;
688 return fail_value;
689}
690
691int32_t
692Args::StringToOptionEnum (const char *s, lldb::OptionEnumValueElement *enum_values, int32_t fail_value, bool *success_ptr)
693{
694 if (enum_values && s && s[0])
695 {
696 for (int i = 0; enum_values[i].string_value != NULL ; i++)
697 {
698 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
699 {
700 if (success_ptr) *success_ptr = true;
701 return enum_values[i].value;
702 }
703 }
704 }
705 if (success_ptr) *success_ptr = false;
706
707 return fail_value;
708}
709
710ScriptLanguage
711Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
712{
713 if (s && s[0])
714 {
715 if ((::strcasecmp (s, "python") == 0) ||
716 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
717 {
718 if (success_ptr) *success_ptr = true;
719 return eScriptLanguagePython;
720 }
721 if (::strcasecmp (s, "none"))
722 {
723 if (success_ptr) *success_ptr = true;
724 return eScriptLanguageNone;
725 }
726 }
727 if (success_ptr) *success_ptr = false;
728 return fail_value;
729}
730
731Error
732Args::StringToFormat
733(
734 const char *s,
735 lldb::Format &format
736)
737{
738 format = eFormatInvalid;
739 Error error;
740
741 if (s && s[0])
742 {
743 switch (s[0])
744 {
745 case 'y': format = eFormatBytes; break;
746 case 'Y': format = eFormatBytesWithASCII; break;
747 case 'b': format = eFormatBinary; break;
748 case 'B': format = eFormatBoolean; break;
749 case 'c': format = eFormatChar; break;
750 case 'C': format = eFormatCharPrintable; break;
751 case 'o': format = eFormatOctal; break;
752 case 'i':
753 case 'd': format = eFormatDecimal; break;
754 case 'u': format = eFormatUnsigned; break;
755 case 'x': format = eFormatHex; break;
756 case 'f':
757 case 'e':
758 case 'g': format = eFormatFloat; break;
759 case 'p': format = eFormatPointer; break;
760 case 's': format = eFormatCString; break;
761 default:
762 error.SetErrorStringWithFormat("Invalid format character '%c'. Valid values are:\n"
763 " b - binary\n"
764 " B - boolean\n"
765 " c - char\n"
766 " C - printable char\n"
767 " d - signed decimal\n"
768 " e - float\n"
769 " f - float\n"
770 " g - float\n"
771 " i - signed decimal\n"
772 " o - octal\n"
773 " s - c-string\n"
774 " u - unsigned decimal\n"
775 " x - hex\n"
776 " y - bytes\n"
777 " Y - bytes with ASCII\n", s[0]);
778 break;
779 }
780
781 if (error.Fail())
782 return error;
783 }
784 else
785 {
786 error.SetErrorStringWithFormat("%s option string.\n", s ? "empty" : "invalid");
787 }
788 return error;
789}
790
791void
792Args::LongestCommonPrefix (std::string &common_prefix)
793{
794 arg_sstr_collection::iterator pos, end = m_args.end();
795 pos = m_args.begin();
796 if (pos == end)
797 common_prefix.clear();
798 else
799 common_prefix = (*pos);
800
801 for (++pos; pos != end; ++pos)
802 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000803 size_t new_size = (*pos).size();
Chris Lattner24943d22010-06-08 16:52:24 +0000804
805 // First trim common_prefix if it is longer than the current element:
806 if (common_prefix.size() > new_size)
807 common_prefix.erase (new_size);
808
809 // Then trim it at the first disparity:
810
Greg Clayton54e7afa2010-07-09 20:39:50 +0000811 for (size_t i = 0; i < common_prefix.size(); i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000812 {
813 if ((*pos)[i] != common_prefix[i])
814 {
815 common_prefix.erase(i);
816 break;
817 }
818 }
819
820 // If we've emptied the common prefix, we're done.
821 if (common_prefix.empty())
822 break;
823 }
824}
825
Caroline Tice44c841d2010-12-07 19:58:26 +0000826size_t
827Args::FindArgumentIndexForOption (struct option *long_options, int long_options_index)
828{
829 char short_buffer[3];
830 char long_buffer[255];
831 ::snprintf (short_buffer, sizeof (short_buffer), "-%c", (char) long_options[long_options_index].val);
832 ::snprintf (long_buffer, sizeof (long_buffer), "--%s", long_options[long_options_index].name);
833 size_t end = GetArgumentCount ();
834 size_t idx = 0;
835 while (idx < end)
836 {
837 if ((::strncmp (GetArgumentAtIndex (idx), short_buffer, strlen (short_buffer)) == 0)
838 || (::strncmp (GetArgumentAtIndex (idx), long_buffer, strlen (long_buffer)) == 0))
839 {
840 return idx;
841 }
842 ++idx;
843 }
844
845 return end;
846}
847
848bool
849Args::IsPositionalArgument (const char *arg)
850{
851 if (arg == NULL)
852 return false;
853
854 bool is_positional = true;
855 char *cptr = (char *) arg;
856
857 if (cptr[0] == '%')
858 {
859 ++cptr;
860 while (isdigit (cptr[0]))
861 ++cptr;
862 if (cptr[0] != '\0')
863 is_positional = false;
864 }
865 else
866 is_positional = false;
867
868 return is_positional;
869}
870
Chris Lattner24943d22010-06-08 16:52:24 +0000871void
Caroline Tice5e0894e2010-10-12 17:45:19 +0000872Args::ParseAliasOptions (Options &options,
873 CommandReturnObject &result,
Caroline Ticee0da7a52010-12-09 22:52:49 +0000874 OptionArgVector *option_arg_vector,
875 std::string &raw_input_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000876{
877 StreamString sstr;
878 int i;
879 struct option *long_options = options.GetLongOptions();
880
881 if (long_options == NULL)
882 {
883 result.AppendError ("invalid long options");
884 result.SetStatus (eReturnStatusFailed);
885 return;
886 }
887
888 for (i = 0; long_options[i].name != NULL; ++i)
889 {
890 if (long_options[i].flag == NULL)
891 {
892 sstr << (char) long_options[i].val;
893 switch (long_options[i].has_arg)
894 {
895 default:
896 case no_argument:
897 break;
898 case required_argument:
899 sstr << ":";
900 break;
901 case optional_argument:
902 sstr << "::";
903 break;
904 }
905 }
906 }
907
Eli Friedmanef2bc872010-06-13 19:18:49 +0000908#ifdef __GLIBC__
909 optind = 0;
910#else
Chris Lattner24943d22010-06-08 16:52:24 +0000911 optreset = 1;
912 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000913#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000914 int val;
915 while (1)
916 {
917 int long_options_index = -1;
918 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
919 &long_options_index);
920
921 if (val == -1)
922 break;
923
924 if (val == '?')
925 {
926 result.AppendError ("unknown or ambiguous option");
927 result.SetStatus (eReturnStatusFailed);
928 break;
929 }
930
931 if (val == 0)
932 continue;
933
934 ((Options *) &options)->OptionSeen (val);
935
936 // Look up the long option index
937 if (long_options_index == -1)
938 {
939 for (int j = 0;
940 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
941 ++j)
942 {
943 if (long_options[j].val == val)
944 {
945 long_options_index = j;
946 break;
947 }
948 }
949 }
950
951 // See if the option takes an argument, and see if one was supplied.
952 if (long_options_index >= 0)
953 {
954 StreamString option_str;
955 option_str.Printf ("-%c", (char) val);
956
957 switch (long_options[long_options_index].has_arg)
958 {
959 case no_argument:
Caroline Tice44c841d2010-12-07 19:58:26 +0000960 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
961 OptionArgValue (no_argument, "<no-argument>")));
Caroline Tice2160c3f2010-09-12 04:48:45 +0000962 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Chris Lattner24943d22010-06-08 16:52:24 +0000963 break;
964 case required_argument:
965 if (optarg != NULL)
966 {
967 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +0000968 OptionArgValue (required_argument,
969 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +0000970 result.SetStatus (eReturnStatusSuccessFinishNoResult);
971 }
972 else
973 {
974 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
975 option_str.GetData());
976 result.SetStatus (eReturnStatusFailed);
977 }
978 break;
979 case optional_argument:
980 if (optarg != NULL)
981 {
982 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +0000983 OptionArgValue (optional_argument,
984 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +0000985 result.SetStatus (eReturnStatusSuccessFinishNoResult);
986 }
987 else
988 {
989 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +0000990 OptionArgValue (optional_argument, "<no-argument>")));
Chris Lattner24943d22010-06-08 16:52:24 +0000991 result.SetStatus (eReturnStatusSuccessFinishNoResult);
992 }
993 break;
994 default:
995 result.AppendErrorWithFormat
996 ("error with options table; invalid value in has_arg field for option '%c'.\n",
997 (char) val);
998 result.SetStatus (eReturnStatusFailed);
999 break;
1000 }
1001 }
1002 else
1003 {
1004 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val);
1005 result.SetStatus (eReturnStatusFailed);
1006 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001007
1008 if (long_options_index >= 0)
1009 {
1010 // 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 +00001011 // supplied. Remove option (and argument, if given) from the argument list. Also remove them from
1012 // the raw_input_string, if one was passed in.
Caroline Tice44c841d2010-12-07 19:58:26 +00001013 size_t idx = FindArgumentIndexForOption (long_options, long_options_index);
1014 if (idx < GetArgumentCount())
1015 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001016 if (raw_input_string.size() > 0)
1017 {
1018 const char *tmp_arg = GetArgumentAtIndex (idx);
1019 size_t pos = raw_input_string.find (tmp_arg);
1020 if (pos != std::string::npos)
1021 raw_input_string.erase (pos, strlen (tmp_arg));
1022 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001023 ReplaceArgumentAtIndex (idx, "");
1024 if ((long_options[long_options_index].has_arg != no_argument)
1025 && (optarg != NULL)
1026 && (idx+1 < GetArgumentCount())
1027 && (strcmp (optarg, GetArgumentAtIndex(idx+1)) == 0))
Caroline Ticee0da7a52010-12-09 22:52:49 +00001028 {
1029 if (raw_input_string.size() > 0)
1030 {
1031 const char *tmp_arg = GetArgumentAtIndex (idx+1);
1032 size_t pos = raw_input_string.find (tmp_arg);
1033 if (pos != std::string::npos)
1034 raw_input_string.erase (pos, strlen (tmp_arg));
1035 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001036 ReplaceArgumentAtIndex (idx+1, "");
Caroline Ticee0da7a52010-12-09 22:52:49 +00001037 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001038 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001039 }
1040
Chris Lattner24943d22010-06-08 16:52:24 +00001041 if (!result.Succeeded())
1042 break;
1043 }
1044}
1045
1046void
1047Args::ParseArgsForCompletion
1048(
1049 Options &options,
Jim Inghamadb84292010-06-24 20:31:04 +00001050 OptionElementVector &option_element_vector,
1051 uint32_t cursor_index
Chris Lattner24943d22010-06-08 16:52:24 +00001052)
1053{
1054 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001055 struct option *long_options = options.GetLongOptions();
1056 option_element_vector.clear();
1057
1058 if (long_options == NULL)
1059 {
1060 return;
1061 }
1062
1063 // Leading : tells getopt to return a : for a missing option argument AND
1064 // to suppress error messages.
1065
1066 sstr << ":";
Greg Claytonbef15832010-07-14 00:18:15 +00001067 for (int i = 0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001068 {
1069 if (long_options[i].flag == NULL)
1070 {
1071 sstr << (char) long_options[i].val;
1072 switch (long_options[i].has_arg)
1073 {
1074 default:
1075 case no_argument:
1076 break;
1077 case required_argument:
1078 sstr << ":";
1079 break;
1080 case optional_argument:
1081 sstr << "::";
1082 break;
1083 }
1084 }
1085 }
1086
Eli Friedmanef2bc872010-06-13 19:18:49 +00001087#ifdef __GLIBC__
1088 optind = 0;
1089#else
Chris Lattner24943d22010-06-08 16:52:24 +00001090 optreset = 1;
1091 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001092#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001093 opterr = 0;
1094
1095 int val;
1096 const OptionDefinition *opt_defs = options.GetDefinitions();
1097
Jim Inghamadb84292010-06-24 20:31:04 +00001098 // Fooey... getopt_long permutes the GetArgumentVector to move the options to the front.
Chris Lattner24943d22010-06-08 16:52:24 +00001099 // So we have to build another Arg and pass that to getopt_long so it doesn't
Jim Inghamadb84292010-06-24 20:31:04 +00001100 // change the one we have.
Chris Lattner24943d22010-06-08 16:52:24 +00001101
Greg Clayton54e7afa2010-07-09 20:39:50 +00001102 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001103
Jim Inghamadb84292010-06-24 20:31:04 +00001104 bool failed_once = false;
1105 uint32_t dash_dash_pos = -1;
1106
Chris Lattner24943d22010-06-08 16:52:24 +00001107 while (1)
1108 {
1109 bool missing_argument = false;
1110 int parse_start = optind;
1111 int long_options_index = -1;
Jim Inghamadb84292010-06-24 20:31:04 +00001112
Greg Clayton54e7afa2010-07-09 20:39:50 +00001113 val = ::getopt_long (dummy_vec.size() - 1,
Greg Clayton53d68e72010-07-20 22:52:08 +00001114 (char *const *) &dummy_vec.front(),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001115 sstr.GetData(),
1116 long_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001117 &long_options_index);
1118
1119 if (val == -1)
Jim Inghamadb84292010-06-24 20:31:04 +00001120 {
1121 // When we're completing a "--" which is the last option on line,
1122 if (failed_once)
1123 break;
1124
1125 failed_once = true;
1126
1127 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1128 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1129 // user might want to complete options by long name. I make this work by checking whether the
1130 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1131 // I let it pass to getopt_long which will terminate the option parsing.
1132 // Note, in either case we continue parsing the line so we can figure out what other options
1133 // were passed. This will be useful when we come to restricting completions based on what other
1134 // options we've seen on the line.
Chris Lattner24943d22010-06-08 16:52:24 +00001135
Jim Inghamadb84292010-06-24 20:31:04 +00001136 if (optind < dummy_vec.size() - 1
1137 && (strcmp (dummy_vec[optind-1], "--") == 0))
1138 {
1139 dash_dash_pos = optind - 1;
1140 if (optind - 1 == cursor_index)
1141 {
1142 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1143 OptionArgElement::eBareDoubleDash));
1144 continue;
1145 }
1146 else
1147 break;
1148 }
1149 else
1150 break;
1151 }
Chris Lattner24943d22010-06-08 16:52:24 +00001152 else if (val == '?')
1153 {
Jim Inghamadb84292010-06-24 20:31:04 +00001154 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1155 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001156 continue;
1157 }
1158 else if (val == 0)
1159 {
1160 continue;
1161 }
1162 else if (val == ':')
1163 {
1164 // This is a missing argument.
1165 val = optopt;
1166 missing_argument = true;
1167 }
1168
1169 ((Options *) &options)->OptionSeen (val);
1170
1171 // Look up the long option index
1172 if (long_options_index == -1)
1173 {
1174 for (int j = 0;
1175 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1176 ++j)
1177 {
1178 if (long_options[j].val == val)
1179 {
1180 long_options_index = j;
1181 break;
1182 }
1183 }
1184 }
1185
1186 // See if the option takes an argument, and see if one was supplied.
1187 if (long_options_index >= 0)
1188 {
1189 int opt_defs_index = -1;
1190 for (int i = 0; ; i++)
1191 {
1192 if (opt_defs[i].short_option == 0)
1193 break;
1194 else if (opt_defs[i].short_option == val)
1195 {
1196 opt_defs_index = i;
1197 break;
1198 }
1199 }
1200
1201 switch (long_options[long_options_index].has_arg)
1202 {
1203 case no_argument:
1204 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1205 break;
1206 case required_argument:
1207 if (optarg != NULL)
1208 {
1209 int arg_index;
1210 if (missing_argument)
1211 arg_index = -1;
1212 else
Jim Inghamadb84292010-06-24 20:31:04 +00001213 arg_index = optind - 1;
Chris Lattner24943d22010-06-08 16:52:24 +00001214
Jim Inghamadb84292010-06-24 20:31:04 +00001215 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
Chris Lattner24943d22010-06-08 16:52:24 +00001216 }
1217 else
1218 {
Jim Inghamadb84292010-06-24 20:31:04 +00001219 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
Chris Lattner24943d22010-06-08 16:52:24 +00001220 }
1221 break;
1222 case optional_argument:
1223 if (optarg != NULL)
1224 {
Jim Inghamadb84292010-06-24 20:31:04 +00001225 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001226 }
1227 else
1228 {
Jim Inghamadb84292010-06-24 20:31:04 +00001229 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001230 }
1231 break;
1232 default:
1233 // The options table is messed up. Here we'll just continue
Jim Inghamadb84292010-06-24 20:31:04 +00001234 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1235 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001236 break;
1237 }
1238 }
1239 else
1240 {
Jim Inghamadb84292010-06-24 20:31:04 +00001241 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1242 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001243 }
1244 }
Jim Inghamadb84292010-06-24 20:31:04 +00001245
1246 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1247 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long just ignores
1248 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1249
1250 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1251 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1252 {
1253 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1254 OptionArgElement::eBareDash));
1255
1256 }
Chris Lattner24943d22010-06-08 16:52:24 +00001257}