File: flags.cpp

package info (click to toggle)
spirv-tools 2025.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 28,588 kB
  • sloc: cpp: 470,407; javascript: 5,893; python: 3,326; ansic: 488; sh: 450; ruby: 88; makefile: 18; lisp: 9
file content (244 lines) | stat: -rw-r--r-- 7,045 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Copyright (c) 2023 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "flags.h"

#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <regex>
#include <string>
#include <unordered_set>
#include <variant>
#include <vector>

namespace flags {

std::vector<std::string> positional_arguments;

namespace {

using token_t = const char*;
using token_iterator_t = token_t*;

// Extracts the flag name from a potential token.
// This function only looks for a '=', to split the flag name from the value for
// long-form flags. Returns the name of the flag, prefixed with the hyphen(s).
inline std::string get_flag_name(const std::string& flag, bool is_short_flag) {
  if (is_short_flag) {
    return flag;
  }

  size_t equal_index = flag.find('=');
  if (equal_index == std::string::npos) {
    return flag;
  }
  return flag.substr(0, equal_index);
}

// Parse a boolean flag. Returns `true` if the parsing succeeded, `false`
// otherwise.
bool parse_bool_flag(Flag<bool>& flag, bool is_short_flag,
                     const std::string& token) {
  if (is_short_flag) {
    flag.value() = true;
    return true;
  }

  const std::string raw_flag(token);
  size_t equal_index = raw_flag.find('=');
  if (equal_index == std::string::npos) {
    flag.value() = true;
    return true;
  }

  const std::string value = raw_flag.substr(equal_index + 1);
  if (value == "true") {
    flag.value() = true;
    return true;
  }

  if (value == "false") {
    flag.value() = false;
    return true;
  }

  return false;
}

// Parse a uint32_t flag value.
bool parse_flag_value(Flag<uint32_t>& flag, const std::string& value) {
  std::regex unsigned_pattern("^ *[0-9]+ *$");
  if (!std::regex_match(value, unsigned_pattern)) {
    std::cerr << "'" << value << "' is not a unsigned number." << std::endl;
    return false;
  }

  errno = 0;
  char* end_ptr = nullptr;
  const uint64_t number = strtoull(value.c_str(), &end_ptr, 10);
  if (end_ptr == nullptr || end_ptr != value.c_str() + value.size() ||
      errno == EINVAL) {
    std::cerr << "'" << value << "' is not a unsigned number." << std::endl;
    return false;
  }

  if (errno == ERANGE || number > static_cast<size_t>(UINT32_MAX)) {
    std::cerr << "'" << value << "' cannot be represented as a 32bit unsigned."
              << std::endl;
    return false;
  }

  flag.value() = static_cast<uint32_t>(number);
  return true;
}

// "Parse" a string flag value (assigns it, cannot fail).
bool parse_flag_value(Flag<std::string>& flag, const std::string& value) {
  flag.value() = value;
  return true;
}

// Parse a potential multi-token flag. Moves the iterator to the last flag's
// token if it's a multi-token flag. Returns `true` if the parsing succeeded.
// The iterator is moved to the last parsed token.
template <typename T>
bool parse_flag(Flag<T>& flag, bool is_short_flag, const char*** iterator) {
  const std::string raw_flag(**iterator);
  std::string raw_value;
  const size_t equal_index = raw_flag.find('=');

  if (is_short_flag || equal_index == std::string::npos) {
    if ((*iterator)[1] == nullptr) {
      return false;
    }

    // This is a bi-token flag. Moving iterator to the last parsed token.
    raw_value = (*iterator)[1];
    *iterator += 1;
  } else {
    // This is a mono-token flag, no need to move the iterator.
    raw_value = raw_flag.substr(equal_index + 1);
  }

  return parse_flag_value(flag, raw_value);
}

}  // namespace

// This is the function to expand if you want to support a new type.
bool FlagList::parse_flag_info(FlagInfo& info, token_iterator_t* iterator) {
  bool success = false;

  std::visit(
      [&](auto&& item) {
        using T = std::decay_t<decltype(item.get())>;
        if constexpr (std::is_same_v<T, Flag<bool>>) {
          success = parse_bool_flag(item.get(), info.is_short, **iterator);
        } else if constexpr (std::is_same_v<T, Flag<std::string>>) {
          success = parse_flag(item.get(), info.is_short, iterator);
        } else if constexpr (std::is_same_v<T, Flag<uint32_t>>) {
          success = parse_flag(item.get(), info.is_short, iterator);
        } else {
          static_assert(always_false_v<T>, "Unsupported flag type.");
        }
      },
      info.flag);

  return success;
}

bool FlagList::parse(token_t* argv) {
  flags::positional_arguments.clear();
  std::unordered_set<const FlagInfo*> parsed_flags;

  bool ignore_flags = false;
  for (const char** it = argv + 1; *it != nullptr; it++) {
    if (ignore_flags) {
      flags::positional_arguments.emplace_back(*it);
      continue;
    }

    // '--' alone is used to mark the end of the flags.
    if (std::strcmp(*it, "--") == 0) {
      ignore_flags = true;
      continue;
    }

    // '-' alone is not a flag, but often used to say 'stdin'.
    if (std::strcmp(*it, "-") == 0) {
      flags::positional_arguments.emplace_back(*it);
      continue;
    }

    const std::string raw_flag(*it);
    if (raw_flag.size() == 0) {
      continue;
    }

    if (raw_flag[0] != '-') {
      flags::positional_arguments.emplace_back(*it);
      continue;
    }

    // Only case left: flags (long and shorts).
    if (raw_flag.size() < 2) {
      std::cerr << "Unknown flag " << raw_flag << std::endl;
      return false;
    }
    const bool is_short_flag = std::strncmp(*it, "--", 2) != 0;
    const std::string flag_name = get_flag_name(raw_flag, is_short_flag);

    auto needle = std::find_if(
        get_flags().begin(), get_flags().end(),
        [&flag_name](const auto& item) { return item.name == flag_name; });
    if (needle == get_flags().end()) {
      std::cerr << "Unknown flag " << flag_name << std::endl;
      return false;
    }

    if (parsed_flags.count(&*needle) != 0) {
      std::cerr << "The flag " << flag_name << " was specified multiple times."
                << std::endl;
      return false;
    }
    parsed_flags.insert(&*needle);

    if (!parse_flag_info(*needle, &it)) {
      std::cerr << "Invalid usage for flag " << flag_name << std::endl;
      return false;
    }
  }

  // Check that we parsed all required flags.
  for (const auto& flag : get_flags()) {
    if (!flag.required) {
      continue;
    }

    if (parsed_flags.count(&flag) == 0) {
      std::cerr << "Missing required flag " << flag.name << std::endl;
      return false;
    }
  }

  return true;
}

// Just the public wrapper around the parse function.
bool Parse(const char** argv) { return FlagList::parse(argv); }

}  // namespace flags