File: amd_options.cpp

package info (click to toggle)
rocr-runtime 6.4.3%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,928 kB
  • sloc: cpp: 126,824; ansic: 41,837; lisp: 1,225; asm: 905; sh: 452; python: 117; makefile: 59
file content (383 lines) | stat: -rw-r--r-- 11,757 bytes parent folder | download | duplicates (3)
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
////////////////////////////////////////////////////////////////////////////////
//
// The University of Illinois/NCSA
// Open Source License (NCSA)
//
// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved.
//
// Developed by:
//
//                 AMD Research and AMD HSA Software Development
//
//                 Advanced Micro Devices, Inc.
//
//                 www.amd.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal with the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
//  - Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimers.
//  - Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimers in
//    the documentation and/or other materials provided with the distribution.
//  - Neither the names of Advanced Micro Devices, Inc,
//    nor the names of its contributors may be used to endorse or promote
//    products derived from this Software without specific prior written
//    permission.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS WITH THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////

#include "amd_options.hpp"

#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <list>
#include <string>

#include <cstddef>

namespace rocr {
namespace amd {
namespace options {

//===----------------------------------------------------------------------===//
// StringFactory.                                                             //
//===----------------------------------------------------------------------===//

std::string StringFactory::Flatten(const char **cstrs,
                                   const uint32_t &cstrs_count,
                                   const char &spacer) {
  if (NULL == cstrs || 0 == cstrs_count) {
    return std::string();
  }

  std::string flattened;
  for (uint32_t i = 0; i < cstrs_count; ++i) {
    if (NULL == cstrs[i]) {
      return std::string();
    }
    flattened += cstrs[i];
    if (i != (cstrs_count - 1)) {
      flattened += spacer;
    }
  }
  return flattened;
}

std::list<std::string> StringFactory::Tokenize(const char *cstr,
                                               const char &delim) {
  if (NULL == cstr) {
    return std::list<std::string>();
  }

  const std::string str = cstr;
  size_t start = 0;
  size_t end = 0;

  std::list<std::string> tokens;
  while ((end = str.find(delim, start)) != std::string::npos) {
    if (start != end) {
      tokens.push_back(str.substr(start, end - start));
    }
    start = end + 1;
  }
  if (str.size() > start) {
    tokens.push_back(str.substr(start));
  }
  return tokens;
}

std::string StringFactory::ToLower(const std::string& str) {
  std::string lower(str.length(), ' ');
  std::transform(str.begin(), str.end(), lower.begin(), ::tolower);
  return lower;
}

std::string StringFactory::ToUpper(const std::string& str) {
  std::string upper(str.length(), ' ');
  std::transform(str.begin(), str.end(), upper.begin(), ::toupper);
  return upper;
}

//===----------------------------------------------------------------------===//
// HelpPrinter, HelpStreambuf.                                                //
//===----------------------------------------------------------------------===//

HelpStreambuf::HelpStreambuf(std::ostream& stream)
  : basicStream_(&stream),
    basicBuf_(stream.rdbuf()),
    wrapWidth_(0),
    indentSize_(0),
    atLineStart_(true),
    lineWidth_(0)
{
  basicStream_->rdbuf(this);
}

HelpStreambuf::int_type HelpStreambuf::overflow(HelpStreambuf::int_type ch) {
    if (atLineStart_ && ch != '\n') {
      std::string indent(indentSize_, ' ');
      basicBuf_->sputn(indent.data(), indent.size());
      lineWidth_ = indentSize_;
      atLineStart_ = false;
    } else if (ch == '\n') {
      atLineStart_ = true;
      lineWidth_ = 0;
    }

    if (wrapWidth_ > 0 && lineWidth_ == wrapWidth_) {
      basicBuf_->sputc('\n');
      std::string indent(indentSize_, ' ');
      basicBuf_->sputn(indent.data(), indent.size());
      lineWidth_ = indentSize_;
      atLineStart_ = false;
    }

    lineWidth_++;
    return basicBuf_->sputc(ch);
  }

HelpPrinter& HelpPrinter::PrintUsage(const std::string& usage) {
  sbuf_.IndentSize(0);
  sbuf_.WrapWidth(0);
  Stream() << usage;
  if (usage.length() < USAGE_WIDTH) {
    Stream() <<  std::string(USAGE_WIDTH - usage.length(), ' ');
  }
  Stream() << std::string(PADDING_WIDTH, ' ');
  return *this;
}

HelpPrinter& HelpPrinter::PrintDescription(const std::string& description) {
  sbuf_.WrapWidth(USAGE_WIDTH + PADDING_WIDTH + DESCRIPTION_WIDTH);
  sbuf_.IndentSize(USAGE_WIDTH + PADDING_WIDTH);
  Stream() << description << std::endl;
  sbuf_.IndentSize(0);
  sbuf_.WrapWidth(0);
  return *this;
}

//===----------------------------------------------------------------------===//
// ChoiceOptioin.                                                             //
//===----------------------------------------------------------------------===//
ChoiceOption::ChoiceOption(const std::string& name,
                           const std::vector<std::string>& choices,
                           const std::string& help,
                           std::ostream& error)
  : OptionBase(name, help, error) {
    for (const auto& choice: choices) {
      choices_.insert(choice);
    }
  }

bool ChoiceOption::ProcessTokens(std::list<std::string> &tokens) {
  assert(0 == name_.compare(tokens.front()) && "option name is mismatched");
  if (2 != tokens.size()) {
    error() << "error: invalid option: \'" << name_ << '\'' << std::endl;
    return false;
  }

  tokens.pop_front();

  if (0 == choices_.count(tokens.front())) {
    error() << "error: invalid option: \'" << name_ << '\'' << std::endl;
    return false;
  }

  is_set_ = true;
  value_ = tokens.front();
  tokens.pop_front();
  return true;
}

void ChoiceOption::PrintHelp(HelpPrinter& printer) const {
  std::string usage = "-" + name_ + "=[";
  bool first = true;
  for (const auto& choice: choices_) {
    if (!first) {
      usage += '|';
    } else {
      first = false;
    }
    usage += choice;
  }
  usage += "]";
  printer.PrintUsage(usage).PrintDescription(help_);
}

//===----------------------------------------------------------------------===//
// PrefixOption.                                                             //
//===----------------------------------------------------------------------===//
bool PrefixOption::IsValid() const {
  return (0 < name_.size()) && (name_.find(':') == std::string::npos);
}

std::string::size_type PrefixOption::FindPrefix(const std::string& token) const {
  auto prefix = name_ + ':';
  return token.find(prefix);
}

bool PrefixOption::Accept(const std::string& token) const {
  return
    (token.compare(0, name_.length(), name_) == 0) &&
    token.length() > name_.length() &&
    token[name_.length()] == ':';
}

bool PrefixOption::ProcessTokens(std::list<std::string> &tokens) {
  assert(1 <= tokens.size());
  assert(Accept(tokens.front()) && "option name is mismatched");

  std::string value = tokens.front(); tokens.pop_front();
  value = value.substr(name_.length() + 1);

  for (const auto& token: tokens) {
    value += '=';
    value += token;
  }
  tokens.clear();

  values_.push_back(value);
  is_set_ = true;
  return true;
}

void PrefixOption::PrintHelp(HelpPrinter& printer) const {
  printer.PrintUsage("-" + name_ + ":[value]").PrintDescription(help_);
}

//===----------------------------------------------------------------------===//
// OptionParser.                                                              //
//===----------------------------------------------------------------------===//
std::vector<OptionBase*>::iterator
OptionParser::FindOption(const std::string& name) {
  std::vector<OptionBase*>::iterator it = options_.begin();
  std::vector<OptionBase*>::iterator end = options_.end();
  for (; it != end; ++it) {
    if ((*it)->Accept(name)) {
      return it;
    }
  }
  return end;
}

bool OptionParser::AddOption(OptionBase *option) {
  if (NULL == option || !option->IsValid()) {
    return false;
  }
  if (FindOption(option->name()) != options_.end()) {
    return false;
  }
  options_.push_back(option);
  return true;
}

const std::string& OptionParser::Unknown() const {
  assert(collectUnknown_);
  return unknownOptions_;
}

bool OptionParser::ParseOptions(const char *options) {
  std::list<std::string> tokens_l1 = StringFactory::Tokenize(options, ' ');
  if (0 == tokens_l1.size()) {
    return true;
  }

  std::list<std::string>::iterator tokens_l1i = tokens_l1.begin();
  while (tokens_l1i != tokens_l1.end()) {
    if ('-' == tokens_l1i->at(0)) {
      std::list<std::string>::iterator option_begin = tokens_l1i;
      std::list<std::string> tokens_l2;
      do {
        tokens_l2.push_back(*tokens_l1i);
        tokens_l1i++;
      } while (tokens_l1i != tokens_l1.end() && '-' != tokens_l1i->at(0));
      std::list<std::string>::iterator option_end = tokens_l1i;
      tokens_l2.front().erase(0, 1);

      if (1 == tokens_l2.size()) {
        tokens_l2 = StringFactory::Tokenize(tokens_l2.front().c_str(), '=');
        if (2 < tokens_l2.size()) {
          if (collectUnknown_) {
            unknownOptions_ += *tokens_l1i + " ";
            continue;
          } else {
            error() << "error: invalid option format: \'"
                    << tokens_l2.front() << '\'' << std::endl;
            Reset();
            return false;
          }
        }
      }

      auto find_status = FindOption(tokens_l2.front());
      if (find_status == options_.end()) {
        if (collectUnknown_) {
          for (; option_begin != option_end; ++option_begin) {
            unknownOptions_ += *option_begin + " ";
          }
          continue;
        } else {
          error() << "error: unknown option: \'"
                  << tokens_l2.front() << '\'' << std::endl;
          Reset();
          return false;
        }
      }

      if (!(*find_status)->ProcessTokens(tokens_l2)) {
        Reset();
        return false;
      }
      assert(0 == tokens_l2.size());
    } else {
      if (collectUnknown_) {
        unknownOptions_ += *tokens_l1i + " ";
      } else {
        error() << "error: unknown option: \'"
                << *tokens_l1i << '\'' << std::endl;
        Reset();
        return false;
      }
    }
  }

  return true;
}

void OptionParser::PrintHelp(std::ostream& out, const std::string& addition) const {
  HelpPrinter printer(out);
  for (const auto& option: options_) {
    option->PrintHelp(printer);
  }
  out << addition << std::endl;
}

void OptionParser::Reset() {
  unknownOptions_.clear();
  for (auto &option : options_) {
    option->Reset();
  }
}

} // namespace options
} // namespace amd
} // namespace rocr