-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathargs.cpp
446 lines (378 loc) · 11.9 KB
/
args.cpp
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
#include "pch.h"
#include "gg_error.hpp"
#include "option.hpp"
#include "output.hpp"
#include "types.hpp"
#include <parsertl/enums.hpp>
#include <lexertl/iterator.hpp>
#include <parsertl/iterator.hpp>
#include <boost/regex.hpp>
#include <cctype>
#include <charconv>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <format>
#include <iosfwd>
#include <iostream>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>
extern void build_condition_parser();
extern std::string dedup_apostrophes(std::string str);
extern void show_usage(const std::string& msg);
extern options g_options;
extern condition_parser g_condition_parser;
std::vector<std::string_view> split(const char* str, const char c)
{
std::vector<std::string_view> ret;
const char* first = str;
std::size_t count = 0;
for (; *str; ++str)
{
if (*str == c)
{
count = str - first;
if (count > 0)
ret.emplace_back(first, count);
first = str + 1;
}
}
count = str - first;
if (count > 0)
ret.emplace_back(first, count);
return ret;
}
bool is_windows()
{
#ifdef _WIN32
return true;
#else
return false;
#endif
}
void parse_condition(const char* str)
{
if (g_condition_parser._gsm.empty())
build_condition_parser();
lexertl::citerator liter(str, str + strlen(str), g_condition_parser._lsm);
parsertl::citerator giter(liter, g_condition_parser._gsm);
for (; giter->entry.action != parsertl::action::accept &&
giter->entry.action != parsertl::action::error; ++giter)
{
if (giter->entry.param == 2)
{
// start: 'regex_search' '(' Index ',' String ')'
const auto index = giter.dollar(2);
const auto rx = giter.dollar(4);
g_options._conditions[atoi(index.first + 1) & 0xffff] =
boost::regex(dedup_apostrophes(rx.substr(1, 1)));
}
}
if (giter->entry.action == parsertl::action::error)
throw gg_error(std::format("Failed to parse '{}'", str));
}
static void process_long(int& i, const char* const argv[],
std::vector<config>& configs)
{
// Skip over "--"
const char* a = argv[i] + 2;
const char* equal = strchr(a, '=');
const std::string_view param(a, equal ? equal : a + strlen(a));
const std::string_view value(equal ? equal + 1 : "");
auto iter = std::ranges::find_if(g_option,
[param](const auto& c)
{
std::vector<std::string_view> switches;
if (c._long)
switches = split(c._long, ',');
return std::ranges::find(switches, param) != switches.end();
});
if (iter != std::end(g_option))
{
if (iter->_param && value.empty() && *iter->_param != '[')
{
show_usage(std::format("{}option '{}' "
"requires an argument\n",
gg_text(),
argv[i]));
}
if (!value.empty() && !iter->_param)
{
show_usage(std::format("{}option '--{}' "
"doesn't allow an argument\n",
gg_text(),
param));
}
iter->_func(i, true, argv, value, configs);
}
else
{
show_usage(std::format("{}unrecognised option '{}'\n",
gg_text(),
argv[i]));
}
}
static void process_short(int& i, const int argc, const char* const argv[],
std::vector<config>& configs)
{
// Skip over '-'
const char* param = argv[i] + 1;
while (*param)
{
if (isdigit(*param))
{
const char* first = param;
while (isdigit(*param))
++param;
g_options._hit_separator = true;
std::from_chars(first, param, g_options._before_context);
g_options._after_context = g_options._before_context;
continue;
}
auto iter = std::find_if(std::begin(g_option), std::end(g_option),
[param](const auto& c)
{
return *param == c._short;
});
if (iter != std::end(g_option))
{
if (iter->_param && i + 1 == argc)
{
show_usage(std::format("{}option requires an "
"argument -- '{}'\n",
gg_text(),
argv[i][1]));
}
iter->_func(i, false, argv, std::string_view(), configs);
}
else
{
show_usage(std::format("{}unrecognised option '-{}'\n",
gg_text(),
*param));
}
++param;
}
}
void add_pattern(const char* param, std::vector<config>& configs)
{
// Use the lexertl enum operator
using namespace lexertl;
const match_type type = []()
{
switch (g_options._pattern_type)
{
case pattern_type::fixed:
return match_type::text;
case pattern_type::flex:
return match_type::dfa_regex;
default:
return match_type::regex;
}
} ();
if (g_options._pattern_type == pattern_type::extended)
g_options._flags |= *config_flags::egrep;
else if (g_options._pattern_type == pattern_type::basic ||
g_options._pattern_type == pattern_type::none)
{
g_options._flags |= *config_flags::grep;
}
configs.emplace_back(type, param, g_options._flags,
std::move(g_options._conditions));
g_options._pattern_type = pattern_type::none;
g_options._flags = 0;
}
void read_switches(const int argc, const char* const argv[],
std::vector<config>& configs, std::vector<std::string>& files)
{
for (int i = 1; i < argc; ++i)
{
const char* param = argv[i];
if (*param == '-')
if (param[1] == '-')
process_long(i, argv, configs);
else
process_short(i, argc, argv, configs);
else
{
namespace fs = std::filesystem;
if (g_options._pattern_type == pattern_type::none && !configs.empty())
{
files.emplace_back(g_options._directories == directories::recurse ?
(std::string(argv[i]) +
static_cast<char>(fs::path::preferred_separator)) + '*' :
argv[i]);
}
else
{
add_pattern(param, configs);
}
}
}
}
static void show_option(const option& opt)
{
constexpr std::size_t max_len = 28;
std::vector<std::string_view> long_options;
std::ostringstream ss;
if (opt._long)
long_options = split(opt._long, ',');
ss << " ";
if (opt._short)
{
ss << '-';
if (opt._short == '0')
ss << "NUM";
else
ss << opt._short;
if (opt._long)
ss << ", ";
}
else
ss << " ";
for (std::size_t idx = 0, size = long_options.size(); idx < size; ++idx)
{
if (idx)
ss << ", ";
ss << "--" << long_options[idx];
}
if (opt._param)
{
if (*opt._param == '[')
ss << '[' << '=' << opt._param + 1;
else
ss << '=' << opt._param;
}
if (const auto sz = ss.view().size();
sz < max_len - 1)
{
ss << std::string(max_len - sz, ' ');
}
else
ss << " ";
std::cout << ss.view();
if (opt._help)
{
const std::vector<std::string_view> help = split(opt._help, '\n');
for (std::size_t idx = 0, size = help.size(); idx < size; ++idx)
{
if (idx)
std::cout << '\n' << std::string(max_len, ' ');
std::cout << help[idx];
}
}
std::cout << '\n';
}
const char* usage()
{
return "Usage: gram_grep ([OPTION]... PATTERN)+ [FILE]...\n";
}
const char* try_help()
{
return "Try 'gram_grep --help' for more information.\n";
}
void show_help()
{
auto iter = std::begin(g_option);
auto end = std::end(g_option);
std::cout << usage() <<
"Search for PATTERNs in each FILE or standard input.\n"
"PATTERN is, by default, a basic regular expression (BRE).\n"
"This is only true for the first PATTERN (for grep compatibility).\n"
"Example: gram_grep -i \"hello world\" menu.h main.c\n\n"
"Pattern selection and interpretation:\n";
for (; iter->_type == option::type::regexp; ++iter)
{
show_option(*iter);
}
std::cout << '\n' << "Miscellaneous:\n";
for (; iter->_type == option::type::misc; ++iter)
{
show_option(*iter);
}
std::cout << '\n' << "Output control:\n";
for (; iter->_type == option::type::output; ++iter)
{
show_option(*iter);
}
std::cout << '\n' << "Context control:\n";
for (; iter->_type == option::type::context; ++iter)
{
show_option(*iter);
}
std::cout << '\n' << "gram_grep specific switches:\n";
for (; iter != end; ++iter)
{
show_option(*iter);
}
std::cout << "\nConfig file format:\n"
" <grammar directives>\n"
" %%\n"
" <grammar>\n"
" %%\n"
" <regexp macros>\n"
" %%\n"
" <regexes>\n"
" %%\n\n"
"Grammar Directives:\n"
" %captures (parenthesis in grammars will be treated as captures)\n"
" %consume (list tokens that are not to be reported as unused)\n"
" %option caseless\n"
" %token\n"
" %left\n"
" %right\n"
" %nonassoc\n"
" %precedence\n"
" %start\n"
" %x\n\n"
"Grammar scripting:\n"
" - Note that all strings can contain $n indexes\n\n"
"Functions returning strings:\n"
" format('text', ...); (use {} for format specifiers)\n"
" replace_all('text', 'regexp', 'text');\n"
" system('text');\n"
"\n"
"General functions:\n"
" erase($n);\n"
" erase($from, $to);\n"
" erase($from.second, $to.first);\n"
" insert($n, 'text');\n"
" insert($n.second, 'text');\n"
" match = $n;\n"
" match += $n;\n"
" match = substr($n, <omit from left>, <omit from right>);\n"
" match += substr($n, <omit from left>, <omit from right>);\n"
" print('text');\n"
" replace($n, 'text');\n"
" replace($from, $to, 'text');\n"
" replace($from.second, $to.first, 'text');\n"
" replace_all($n, 'regexp', 'text');\n"
"\n"
"--if Syntax:\n"
" regex_search($n, 'regex'){ || regex_search($n, 'regex')}\n"
"\n"
"Example:\n"
" %token RawString String\n"
" %%\n"
" list: String { match = substr($1, 1, 1); };\n"
" list: RawString { match = substr($1, 3, 2); };\n"
" list: list String { match += substr($2, 1, 1); };\n"
" list: list RawString { match += substr($2, 3, 2); };\n"
" %%\n"
R"( ws [ \t\r\n]+)"
"\n"
" %%\n"
R"( \"([^"\\\r\n]|\\.)*\" String)"
"\n"
R"( R\"\((?s:.)*?\)\" RawString)"
"\n"
R"( '([^'\\\r\n]|\\.)*' skip())"
"\n"
R"( {ws}|"//".*|"/*"(?s:.)*?"*/" skip())"
"\n"
" %%\n\n"
" Note that you can pipeline searches by using multiple switches.\n"
" The searches are run in the order they occur on the command line.\n";
}