Coverage Report

Created: 2025-09-27 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/WasmEdge/lib/po/argument_parser.cpp
Line
Count
Source
1
// SPDX-License-Identifier: Apache-2.0
2
// SPDX-FileCopyrightText: 2019-2024 Second State INC
3
4
#include "po/argument_parser.h"
5
#include "common/defines.h"
6
#include "common/spdlog.h"
7
#include "system/winapi.h"
8
#include <cstdio>
9
10
namespace WasmEdge {
11
namespace PO {
12
13
cxx20::expected<bool, Error> ArgumentParser::SubCommandDescriptor::parse(
14
    std::FILE *Out, Span<const char *> ProgramNamePrefix, int Argc,
15
1.70k
    const char *Argv[], int ArgP, const bool &VersionOpt) noexcept {
16
1.70k
  ProgramNames.reserve(ProgramNamePrefix.size() + 1);
17
1.70k
  ProgramNames.assign(ProgramNamePrefix.begin(), ProgramNamePrefix.end());
18
1.70k
  if (ArgP < Argc) {
19
1.70k
    ProgramNames.push_back(Argv[ArgP]);
20
1.70k
  }
21
1.70k
  ArgumentDescriptor *CurrentDesc = nullptr;
22
1.70k
  bool FirstNonOption = true;
23
1.70k
  bool Escaped = false;
24
1.70k
  auto PositionalIter = PositionalList.cbegin();
25
1.99M
  for (int ArgI = ArgP + 1; ArgI < Argc; ++ArgI) {
26
1.99M
    std::string_view Arg = Argv[ArgI];
27
1.99M
    if (!Escaped && Arg.size() >= 2 && Arg[0] == '-') {
28
357k
      if (Arg[1] == '-') {
29
356k
        if (Arg.size() == 2) {
30
47
          Escaped = true;
31
356k
        } else {
32
          // long option
33
356k
          if (CurrentDesc && CurrentDesc->nargs() == 0) {
34
2.22k
            CurrentDesc->default_value();
35
2.22k
          }
36
356k
          if (auto Res = consume_long_option_with_argument(Arg); !Res) {
37
380
            return cxx20::unexpected(Res.error());
38
356k
          } else {
39
356k
            CurrentDesc = *Res;
40
356k
          }
41
356k
        }
42
356k
      } else {
43
        // short options
44
1.31k
        if (CurrentDesc && CurrentDesc->nargs() == 0) {
45
201
          CurrentDesc->default_value();
46
201
        }
47
1.31k
        if (auto Res = consume_short_options(Arg); !Res) {
48
38
          return cxx20::unexpected(Res.error());
49
1.27k
        } else {
50
1.27k
          CurrentDesc = *Res;
51
1.27k
        }
52
1.31k
      }
53
1.63M
    } else if (!Escaped && CurrentDesc) {
54
882
      consume_argument(*CurrentDesc, Arg);
55
882
      CurrentDesc = nullptr;
56
1.63M
    } else {
57
      // no more options
58
1.63M
      if (FirstNonOption) {
59
578
        FirstNonOption = false;
60
578
        if (!SubCommandMap.empty()) {
61
0
          if (auto Iter = SubCommandMap.find(Arg);
62
0
              Iter != SubCommandMap.end()) {
63
0
            auto &Child = this[Iter->second];
64
0
            Child.SC->select();
65
0
            return Child.parse(Out, ProgramNames, Argc, Argv, ArgI, VersionOpt);
66
0
          }
67
0
        }
68
578
      }
69
1.63M
      Escaped = true;
70
1.63M
      if (CurrentDesc) {
71
1.63M
        if (auto Res = consume_argument(*CurrentDesc, Arg); !Res) {
72
1
          return cxx20::unexpected(Res.error());
73
1.63M
        } else {
74
1.63M
          CurrentDesc = *Res;
75
1.63M
        }
76
1.63M
      } else {
77
837
        if (PositionalIter == PositionalList.cend()) {
78
0
          return cxx20::unexpected<Error>(
79
0
              std::in_place, ErrCode::InvalidArgument,
80
0
              "positional argument exceeds maximum consuming."s);
81
0
        }
82
837
        if (auto Res =
83
837
                consume_argument(ArgumentDescriptors[*PositionalIter], Arg);
84
837
            !Res) {
85
0
          return cxx20::unexpected(Res.error());
86
837
        } else {
87
837
          CurrentDesc = *Res;
88
837
        }
89
837
        ++PositionalIter;
90
837
      }
91
1.63M
    }
92
1.99M
  }
93
1.29k
  if (CurrentDesc && CurrentDesc->nargs() == 0) {
94
33
    CurrentDesc->default_value();
95
33
  }
96
97
1.29k
  if (VersionOpt) {
98
236
    return true;
99
236
  }
100
1.05k
  if (!HelpOpt->value()) {
101
15.3k
    for (const auto &Desc : ArgumentDescriptors) {
102
15.3k
      if (Desc.nargs() < Desc.min_nargs()) {
103
499
        help(Out);
104
499
        return false;
105
499
      }
106
15.3k
    }
107
1.01k
  } else {
108
41
    help(Out);
109
41
    return true;
110
41
  }
111
514
  return true;
112
1.05k
}
113
114
void ArgumentParser::SubCommandDescriptor::usage(
115
540
    std::FILE *Out) const noexcept {
116
540
  fmt::print(Out, "{}USAGE{}\n"sv, YELLOW_COLOR, RESET_COLOR);
117
540
  for (const char *Part : ProgramNames) {
118
540
    fmt::print(Out, "\t{}"sv, Part);
119
540
  }
120
540
  if (!SubCommandList.empty()) {
121
0
    fmt::print(Out, " [SUBCOMMANDS]"sv);
122
0
  }
123
540
  if (!NonpositionalList.empty()) {
124
540
    fmt::print(Out, " [OPTIONS]"sv);
125
540
  }
126
540
  bool First = true;
127
1.08k
  for (const auto &Index : PositionalList) {
128
1.08k
    const auto &Desc = ArgumentDescriptors[Index];
129
1.08k
    if (Desc.hidden()) {
130
0
      continue;
131
0
    }
132
133
1.08k
    if (First) {
134
540
      fmt::print(Out, " [--]"sv);
135
540
      First = false;
136
540
    }
137
138
1.08k
    const bool Optional = (Desc.min_nargs() == 0);
139
1.08k
    fmt::print(Out, " "sv);
140
1.08k
    if (Optional) {
141
540
      fmt::print(Out, "["sv);
142
540
    }
143
1.08k
    switch (ArgumentDescriptors[Index].max_nargs()) {
144
0
    case 0:
145
0
      break;
146
540
    case 1:
147
540
      fmt::print(Out, "{}"sv, Desc.meta());
148
540
      break;
149
540
    default:
150
540
      fmt::print(Out, "{} ..."sv, Desc.meta());
151
540
      break;
152
1.08k
    }
153
1.08k
    if (Optional) {
154
540
      fmt::print(Out, "]"sv);
155
540
    }
156
1.08k
  }
157
540
  fmt::print(Out, "\n"sv);
158
540
}
159
160
540
void ArgumentParser::SubCommandDescriptor::help(std::FILE *Out) const noexcept {
161
// For enabling Windows PowerShell color support.
162
#if WASMEDGE_OS_WINDOWS && WINAPI_PARTITION_DESKTOP
163
  winapi::HANDLE_ OutputHandler =
164
      winapi::GetStdHandle(winapi::STD_OUTPUT_HANDLE_);
165
  if (OutputHandler != winapi::INVALID_HANDLE_VALUE_) {
166
    winapi::DWORD_ ConsoleMode = 0;
167
    if (winapi::GetConsoleMode(OutputHandler, &ConsoleMode)) {
168
      ConsoleMode |= winapi::ENABLE_VIRTUAL_TERMINAL_PROCESSING_;
169
      winapi::SetConsoleMode(OutputHandler, ConsoleMode);
170
    }
171
  }
172
#endif
173
174
540
  usage(Out);
175
540
  const constexpr std::string_view kIndent = "\t"sv;
176
177
540
  fmt::print(Out, "\n"sv);
178
540
  if (!SubCommandList.empty()) {
179
0
    fmt::print(Out, "{}SUBCOMMANDS{}\n"sv, YELLOW_COLOR, RESET_COLOR);
180
0
    for (const auto Offset : SubCommandList) {
181
0
      fmt::print(Out, "{}{}"sv, kIndent, GREEN_COLOR);
182
0
      bool First = true;
183
0
      for (const auto &Name : this[Offset].SubCommandNames) {
184
0
        if (!First) {
185
0
          fmt::print(Out, "|"sv);
186
0
        }
187
0
        fmt::print(Out, "{}"sv, Name);
188
0
        First = false;
189
0
      }
190
0
      fmt::print(Out, "{}\n"sv, RESET_COLOR);
191
0
      indent_output(Out, kIndent, 2, 80, this[Offset].SC->description());
192
0
      fmt::print(Out, "\n"sv);
193
0
    }
194
0
    fmt::print(Out, "\n"sv);
195
0
  }
196
197
540
  fmt::print(Out, "{}OPTIONS{}\n"sv, YELLOW_COLOR, RESET_COLOR);
198
13.5k
  for (const auto &Index : NonpositionalList) {
199
13.5k
    const auto &Desc = ArgumentDescriptors[Index];
200
13.5k
    if (Desc.hidden()) {
201
0
      continue;
202
0
    }
203
204
13.5k
    fmt::print(Out, "{}{}\n"sv, kIndent, GREEN_COLOR);
205
13.5k
    bool First = true;
206
14.5k
    for (const auto &Option : Desc.options()) {
207
14.5k
      if (!First) {
208
1.08k
        fmt::print(Out, "|"sv);
209
1.08k
      }
210
14.5k
      if (Option.size() == 1) {
211
1.08k
        fmt::print(Out, "-{}"sv, Option);
212
13.5k
      } else {
213
13.5k
        fmt::print(Out, "--{}"sv, Option);
214
13.5k
      }
215
14.5k
      First = false;
216
14.5k
    }
217
13.5k
    fmt::print(Out, "{}\n"sv, RESET_COLOR);
218
13.5k
    indent_output(Out, kIndent, 2, 80, Desc.description());
219
13.5k
    fmt::print(Out, "\n"sv);
220
13.5k
  }
221
540
}
222
223
void ArgumentParser::SubCommandDescriptor::indent_output(
224
    std::FILE *Out, const std::string_view kIndent, std::size_t IndentCount,
225
13.5k
    std::size_t ScreenWidth, std::string_view Desc) const noexcept {
226
13.5k
  const std::size_t Width = ScreenWidth - kIndent.size() * IndentCount;
227
16.7k
  while (Desc.size() > Width) {
228
3.24k
    const std::size_t SpacePos = Desc.find_last_of(' ', Width);
229
3.24k
    if (SpacePos != std::string_view::npos) {
230
9.72k
      for (std::size_t I = 0; I < IndentCount; ++I) {
231
6.48k
        fmt::print(Out, "{}"sv, kIndent);
232
6.48k
      }
233
3.24k
      fmt::print(Out, "{}\n"sv, Desc.substr(0, SpacePos));
234
3.24k
      const std::size_t WordPos = Desc.find_first_not_of(' ', SpacePos);
235
3.24k
      if (WordPos != std::string_view::npos) {
236
3.24k
        Desc = Desc.substr(WordPos);
237
3.24k
      } else {
238
0
        Desc = {};
239
0
      }
240
3.24k
    }
241
3.24k
  }
242
13.5k
  if (!Desc.empty()) {
243
40.5k
    for (std::size_t I = 0; I < IndentCount; ++I) {
244
27.0k
      fmt::print(Out, "{}"sv, kIndent);
245
27.0k
    }
246
13.5k
    fmt::print(Out, "{}"sv, Desc);
247
13.5k
  }
248
13.5k
}
249
250
cxx20::expected<ArgumentParser::ArgumentDescriptor *, Error>
251
ArgumentParser::SubCommandDescriptor::consume_short_options(
252
1.31k
    std::string_view Arg) noexcept {
253
1.31k
  ArgumentDescriptor *CurrentDesc = nullptr;
254
1.11M
  for (std::size_t I = 1; I < Arg.size(); ++I) {
255
1.11M
    if (CurrentDesc && CurrentDesc->nargs() == 0) {
256
0
      CurrentDesc->default_value();
257
0
    }
258
1.11M
    std::string_view Option = Arg.substr(I, 1);
259
1.11M
    if (auto Res = consume_short_option(Option); !Res) {
260
38
      return cxx20::unexpected(Res.error());
261
1.11M
    } else {
262
1.11M
      CurrentDesc = *Res;
263
1.11M
    }
264
1.11M
  }
265
1.27k
  return CurrentDesc;
266
1.31k
}
267
268
cxx20::expected<ArgumentParser::ArgumentDescriptor *, Error>
269
ArgumentParser::SubCommandDescriptor::consume_long_option_with_argument(
270
356k
    std::string_view Arg) noexcept {
271
356k
  if (auto Pos = Arg.find('=', 2); Pos != std::string_view::npos) {
272
    // long option with argument
273
344k
    std::string_view Option = Arg.substr(2, Pos - 2);
274
344k
    std::string_view Argument = Arg.substr(Pos + 1);
275
344k
    if (auto Res = consume_long_option(Option); !Res) {
276
53
      return cxx20::unexpected<Error>(Res.error());
277
344k
    } else if (ArgumentDescriptor *CurrentDesc = *Res; !CurrentDesc) {
278
13
      return cxx20::unexpected<Error>(std::in_place, ErrCode::InvalidArgument,
279
13
                                      "option "s + std::string(Option) +
280
13
                                          "doesn't need arguments."s);
281
344k
    } else {
282
344k
      consume_argument(*CurrentDesc, Argument);
283
344k
      return nullptr;
284
344k
    }
285
344k
  } else {
286
    // long option without argument
287
12.0k
    std::string_view Option = Arg.substr(2);
288
12.0k
    return consume_long_option(Option);
289
12.0k
  }
290
356k
}
291
292
cxx20::expected<ArgumentParser::ArgumentDescriptor *, Error>
293
ArgumentParser::SubCommandDescriptor::consume_short_option(
294
1.11M
    std::string_view Option) noexcept {
295
1.11M
  auto Iter = ArgumentMap.find(Option);
296
1.11M
  if (Iter == ArgumentMap.end()) {
297
38
    return cxx20::unexpected<Error>(std::in_place, ErrCode::InvalidArgument,
298
38
                                    "unknown option: "s + std::string(Option));
299
38
  }
300
1.11M
  ArgumentDescriptor &CurrentDesc = ArgumentDescriptors[Iter->second];
301
1.11M
  if (CurrentDesc.max_nargs() == 0) {
302
1.11M
    CurrentDesc.default_value();
303
1.11M
    return nullptr;
304
1.11M
  }
305
0
  return &CurrentDesc;
306
1.11M
}
307
308
cxx20::expected<ArgumentParser::ArgumentDescriptor *, Error>
309
ArgumentParser::SubCommandDescriptor::consume_long_option(
310
356k
    std::string_view Option) noexcept {
311
356k
  auto Iter = ArgumentMap.find(Option);
312
356k
  if (Iter == ArgumentMap.end()) {
313
367
    return cxx20::unexpected<Error>(std::in_place, ErrCode::InvalidArgument,
314
367
                                    "unknown option: "s + std::string(Option));
315
367
  }
316
356k
  ArgumentDescriptor &CurrentDesc = ArgumentDescriptors[Iter->second];
317
356k
  if (CurrentDesc.max_nargs() == 0) {
318
1.57k
    CurrentDesc.default_value();
319
1.57k
    return nullptr;
320
1.57k
  }
321
354k
  return &CurrentDesc;
322
356k
}
323
324
cxx20::expected<ArgumentParser::ArgumentDescriptor *, Error>
325
ArgumentParser::SubCommandDescriptor::consume_argument(
326
1.98M
    ArgumentDescriptor &CurrentDesc, std::string_view Argument) noexcept {
327
1.98M
  if (auto Res = CurrentDesc.argument(std::string(Argument)); !Res) {
328
1.93k
    return cxx20::unexpected(Res.error());
329
1.93k
  }
330
1.98M
  if (++CurrentDesc.nargs() >= CurrentDesc.max_nargs()) {
331
67.2k
    return nullptr;
332
67.2k
  }
333
1.91M
  return &CurrentDesc;
334
1.98M
}
335
336
bool ArgumentParser::parse(std::FILE *Out, int Argc,
337
1.70k
                           const char *Argv[]) noexcept {
338
1.70k
  if (auto Res = SubCommandDescriptors.front().parse(Out, {}, Argc, Argv, 0,
339
1.70k
                                                     VerOpt.value());
340
1.70k
      !Res) {
341
419
    fmt::print(Out, "{}\n"sv, Res.error().message());
342
419
    return false;
343
1.29k
  } else {
344
1.29k
    return *Res || VerOpt.value();
345
1.29k
  }
346
1.70k
}
347
348
} // namespace PO
349
} // namespace WasmEdge