1 //===-- source/Host/common/OptionParser.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 #include "lldb/Host/OptionParser.h"
11 
12 #ifdef _MSC_VER
13 #include "../windows/msvc/getopt.inc"
14 #else
15 #ifdef _WIN32
16 #define _BSD_SOURCE // Required so that getopt.h defines optreset
17 #endif
18 #include <getopt.h>
19 #endif
20 
21 using namespace lldb_private;
22 
23 void
24 OptionParser::Prepare()
25 {
26 #ifdef __GLIBC__
27     optind = 0;
28 #else
29     optreset = 1;
30     optind = 1;
31 #endif
32 }
33 
34 void
35 OptionParser::EnableError(bool error)
36 {
37     opterr = error ? 1 : 0;
38 }
39 
40 int
41 OptionParser::Parse (int argc,
42                      char * const argv [],
43                      const char *optstring,
44                      const Option *longopts,
45                      int *longindex)
46 {
47     return getopt_long_only(argc, argv, optstring, (const option*)longopts, longindex);
48 }
49 
50 char*
51 OptionParser::GetOptionArgument()
52 {
53     return optarg;
54 }
55 
56 int
57 OptionParser::GetOptionIndex()
58 {
59     return optind;
60 }
61 
62 int
63 OptionParser::GetOptionErrorCause()
64 {
65     return optopt;
66 }
67 
68 std::string
69 OptionParser::GetShortOptionString(struct option *long_options)
70 {
71     std::string s;
72     int i=0;
73     bool done = false;
74     while (!done)
75     {
76         if (long_options[i].name    == 0 &&
77             long_options[i].has_arg == 0 &&
78             long_options[i].flag    == 0 &&
79             long_options[i].val     == 0)
80         {
81             done = true;
82         }
83         else
84         {
85             if (long_options[i].flag == NULL &&
86                 isalpha(long_options[i].val))
87             {
88                 s.append(1, (char)long_options[i].val);
89                 switch (long_options[i].has_arg)
90                 {
91                     default:
92                     case no_argument:
93                         break;
94 
95                     case optional_argument:
96                         s.append(2, ':');
97                         break;
98                     case required_argument:
99                         s.append(1, ':');
100                         break;
101                 }
102             }
103             ++i;
104         }
105     }
106     return s;
107 }
108