forked from MUME/MMapper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeParser.cpp
More file actions
460 lines (389 loc) · 13.6 KB
/
Copy pathTreeParser.cpp
File metadata and controls
460 lines (389 loc) · 13.6 KB
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2019 The MMapper Authors
#include "TreeParser.h"
#include "../global/AnsiTextUtils.h"
#include "../global/Consts.h"
#include "../global/PrintUtils.h"
#include "../global/unquote.h"
#include "SyntaxArgs.h"
#include "TokenMatcher.h"
#include <memory>
#include <optional>
#include <ostream>
#include <sstream>
#include <tuple>
#include <vector>
namespace syntax {
TreeParser::TreeParser(SharedConstSublist syntaxRoot, User &user)
: m_syntaxRoot(std::move(syntaxRoot))
, m_user{user}
{}
bool TreeParser::parse(const ParserInput &input)
{
if (syntaxOnly(input)) {
return true;
}
bool isFull = false;
const auto isHelpRequest = [&isFull](const std::string_view s) -> bool {
if (s == "??") {
isFull = true;
return true;
}
return s == "?" || s == "/?" || s == "/h" || s == "/help" || s == "-h" || s == "--help";
};
auto copy = input;
if (isHelpRequest(copy.back())) {
copy = input.rmid(1);
}
m_user.getOstream() << (isFull ? "Full" : "Basic") << " syntax help for [" << copy << "]\n";
help(copy, isFull);
return false;
}
bool TreeParser::syntaxOnly(const ParserInput &input)
{
const Sublist &node = deref(m_syntaxRoot);
return syntaxRecurseFirst(node, input, nullptr).isSuccess();
}
ParseResult TreeParser::syntaxRecurseFirst(const Sublist &node,
const ParserInput &input,
const Pair *const matchedArgs)
{
if (node.holdsNestedSublist()) {
return recurseNewSublist(node, input, matchedArgs);
} else {
return recurseTokenMatcher(node, input, matchedArgs);
}
}
ParseResult TreeParser::recurseNewSublist(const Sublist &node,
const ParserInput &input,
const Pair *const matchedArgs)
{
ParseResult tmp = syntaxRecurseFirst(deref(node.getNestedSublist()), input, matchedArgs);
if (tmp.isSuccess()) {
return tmp;
}
// Note: No support for stacking arguments spilled from a list.
return syntaxRecurseNext(node, input, matchedArgs);
}
ParseResult TreeParser::recurseTokenMatcher(const Sublist &node,
const ParserInput &input,
const Pair *const matchedArgs)
{
MatchResult tmp = node.getTokenMatcher().tryMatch(input, nullptr);
if (!tmp) {
return ParseResult::failure(input);
}
if (!tmp.optValue) {
return syntaxRecurseNext(node, tmp.unmatched, matchedArgs);
}
const Pair p{tmp.optValue.value(), matchedArgs};
return syntaxRecurseNext(node, tmp.unmatched, &p);
}
ParseResult TreeParser::syntaxRecurseNext(const Sublist &node,
const ParserInput &input,
const Pair *const matchedArgs)
{
if (!node.hasNextNode()) {
return recurseAccept(node, input, matchedArgs);
}
if (const SharedConstSublist &tmp = node.getNext()) {
return syntaxRecurseFirst(deref(tmp), input, matchedArgs);
}
return ParseResult::failure(input);
}
ParseResult TreeParser::recurseAccept(const Sublist &node,
const ParserInput &input,
const Pair *matchedArgs)
{
if (!input.empty()) {
return ParseResult::failure(input);
}
node.getAcceptFn().call(m_user, matchedArgs);
return ParseResult::success(input);
}
struct NODISCARD HelpFrame final : IMatchErrorLogger
{
private:
AnsiOstream &m_aos; // prevents move ctor and operator=
private:
size_t m_indent = 0;
std::vector<std::string> m_helps;
std::optional<std::string> m_accept;
std::vector<std::string> m_errors;
bool m_failed = false;
public:
explicit HelpFrame(AnsiOstream &aos)
: m_aos{aos}
{}
DEFAULT_COPY_CTOR(HelpFrame);
// TODO: change this to DELETE_MOVE_CTOR (compiler bug: g++ 7.4 uses move ctor in NRVO).
DEFAULT_MOVE_CTOR(HelpFrame);
DELETE_ASSIGN_OPS(HelpFrame);
~HelpFrame() final;
public:
NODISCARD bool getFailed() const { return m_failed; }
void setFailed() { m_failed = true; }
NODISCARD bool empty() { return m_helps.empty() && !m_accept && m_errors.empty(); }
void addAccept(std::string acc)
{
// REVISIT: this should probably be colored,
// but we don't have the info for that here.
if (m_helps.empty()) {
m_helps.emplace_back("<(empty)>");
}
m_accept = std::move(acc);
}
void addHelp(std::string help) { m_helps.emplace_back(std::move(help)); }
void addHelp(const TokenMatcher &tokenMatcher, std::optional<MatchTypeEnum> type);
void flush();
NODISCARD HelpFrame makeChild();
private:
void virt_logError(std::string s) override { m_errors.emplace_back(s); }
};
HelpFrame::~HelpFrame()
{
flush();
}
void HelpFrame::flush()
{
using namespace char_consts;
if (empty()) {
return;
}
auto &os = m_aos;
if (!m_helps.empty() || m_accept) {
// REVISIT: can we send directly to the ansi ostream?
std::ostringstream ss;
ss << std::string(2 * m_indent, C_SPACE);
if (!m_helps.empty()) {
bool first = true;
for (const auto &h : m_helps) {
if (first) {
first = false;
} else {
ss << C_SPACE;
}
ss << h;
}
}
auto str = ss.str();
os.writeWithEmbeddedAnsi(str);
// TODO: convert QString ansi stuff to std::string_view instead of QStringView
static const auto getLengthAnsiAware = [](const std::string_view sv) -> size_t {
size_t len = 0;
bool inEsc = false;
for (char c : sv) {
if (c == C_ESC) {
inEsc = true;
} else if (inEsc) {
if (c == 'm') {
inEsc = false;
} else {
assert(std::isdigit(c) || c == C_OPEN_BRACKET || c == C_SEMICOLON
|| c == C_COLON);
}
} else {
++len;
}
}
return len;
};
size_t pos = getLengthAnsiAware(str);
if (m_accept) {
if (!m_helps.empty()) {
pos += 1;
os << C_SPACE;
}
const auto &acc = m_accept.value();
size_t accLen = acc.length();
const auto wouldEndAt = pos + accLen;
const size_t rightMargin = 80;
if (wouldEndAt <= rightMargin) {
os << std::string(rightMargin - wouldEndAt, C_SPACE);
} else if (accLen + 2 <= rightMargin) {
os << AnsiOstream::endl;
os << std::string(rightMargin - accLen - 2, C_SPACE);
os << "# ";
} else {
os << AnsiOstream::endl;
os << "# ";
}
os << acc;
}
os << AnsiOstream::endl;
}
if (!m_errors.empty()) {
for (const std::string &w : m_errors) {
os << std::string(2 * m_indent, C_SPACE);
os << " ^ warning: " << w << AnsiOstream::endl;
}
os << AnsiOstream::endl; // blank line
}
m_helps.clear();
m_accept.reset();
m_errors.clear();
++m_indent;
}
HelpFrame HelpFrame::makeChild()
{
flush();
HelpFrame child = *this; // copy ctor
return child; // C++ standard says NRVO elides the move constructor here.
}
class NODISCARD TreeParser::HelpCommon final
{
protected:
const bool m_isFull = true;
public:
explicit HelpCommon(const bool isFull)
: m_isFull(isFull)
{}
public:
NODISCARD ParseResult syntaxRecurseFirst(const Sublist &node,
const ParserInput &input,
HelpFrame &frame);
NODISCARD ParseResult recurseNewSublist(const Sublist &node,
const ParserInput &input,
HelpFrame &frame);
NODISCARD ParseResult recurseTokenMatcher(const Sublist &node,
const ParserInput &input,
HelpFrame &frame);
NODISCARD ParseResult syntaxRecurseNext(const Sublist &node,
const ParserInput &input,
HelpFrame &frame);
NODISCARD ParseResult recurseAccept(const Sublist &node,
const ParserInput &input,
HelpFrame &frame);
};
void HelpFrame::addHelp(const TokenMatcher &tokenMatcher, std::optional<MatchTypeEnum> type)
{
if (!type) {
std::ostringstream ss;
ss << tokenMatcher;
addHelp(ss.str());
return;
}
RawAnsi raw;
raw.setBold();
switch (type.value()) {
case MatchTypeEnum::Fail:
raw.fg = AnsiColorVariant{AnsiColor16Enum::red};
break;
case MatchTypeEnum::Partial:
raw.fg = AnsiColorVariant{AnsiColor16Enum::yellow};
break;
case MatchTypeEnum::Pass:
raw.fg = AnsiColorVariant{AnsiColor16Enum::cyan};
break;
}
// REVISIT: store this as Ansi instead of the string version.
std::ostringstream ss;
to_stream_as_reset(ss, ANSI_COLOR_SUPPORT_HI, raw);
ss << tokenMatcher;
ss << reset_ansi;
addHelp(std::move(ss).str());
}
ParseResult TreeParser::HelpCommon::syntaxRecurseFirst(const Sublist &node,
const ParserInput &input,
HelpFrame &frame)
{
if (node.holdsNestedSublist()) {
return recurseNewSublist(node, input, frame);
} else {
return recurseTokenMatcher(node, input, frame);
}
}
ParseResult TreeParser::HelpCommon::recurseNewSublist(const Sublist &node,
const ParserInput &input,
HelpFrame &frame)
{
{
HelpFrame newFrame = frame.makeChild();
ParseResult tmp = syntaxRecurseFirst(deref(node.getNestedSublist()), input, newFrame);
if (tmp.isSuccess()) {
return tmp;
}
}
// Note: No support for stacking arguments spilled from a list.
return syntaxRecurseNext(node, input, frame);
}
ParseResult TreeParser::HelpCommon::recurseTokenMatcher(const Sublist &node,
const ParserInput &input,
HelpFrame &frame)
{
const TokenMatcher &tokenMatcher = node.getTokenMatcher();
if (frame.getFailed()) {
frame.addHelp(tokenMatcher, std::nullopt);
return syntaxRecurseNext(node, input, frame);
}
MatchResult tmp = tokenMatcher.tryMatch(input, &frame);
if (tmp) {
frame.addHelp(tokenMatcher, MatchTypeEnum::Pass);
return syntaxRecurseNext(node, tmp.unmatched, frame);
}
frame.setFailed();
frame.addHelp(tokenMatcher, !tmp.matched.empty() ? MatchTypeEnum::Partial : MatchTypeEnum::Fail);
return syntaxRecurseNext(node, input, frame);
}
ParseResult TreeParser::HelpCommon::syntaxRecurseNext(const Sublist &node,
const ParserInput &input,
HelpFrame &frame)
{
if (!m_isFull) {
if (frame.getFailed()) {
if (!node.hasNextNode() || node.getNext()) {
frame.addHelp("...");
}
return ParseResult::failure(input);
}
}
if (!node.hasNextNode()) {
return recurseAccept(node, input, frame);
}
if (const SharedConstSublist &tmp = node.getNext()) {
return syntaxRecurseFirst(deref(tmp), input, frame);
}
return ParseResult::failure(input);
}
ParseResult TreeParser::HelpCommon::recurseAccept(const Sublist &node,
const ParserInput &input,
HelpFrame &frame)
{
if (!frame.getFailed() && !input.empty()) {
frame.setFailed();
}
frame.addAccept(node.getAcceptFn().getHelp());
return ParseResult::failure(input);
}
void TreeParser::help(const ParserInput &input, const bool isFull)
{
const Sublist &node = deref(m_syntaxRoot);
HelpFrame frame{m_user.getOstream()};
std::ignore = HelpCommon{isFull}.syntaxRecurseFirst(node, input, frame);
}
std::string processSyntax(const syntax::SharedConstSublist &syntax,
const std::string &name,
const StringView args)
{
using namespace syntax;
const auto str = name + " " + args.toStdString();
const auto cmd = StringView{str};
auto v = unquote(cmd.getStdStringView(), true, false);
if (!v) {
throw std::runtime_error("input error: " + v.getUnquoteFailureReason());
}
const auto shared_vec = std::make_shared<const std::vector<std::string>>(v.getVectorOfStrings());
const ParserInput input(shared_vec);
std::ostringstream ss;
{
AnsiOstream aos{ss};
User u{aos};
TreeParser parser{syntax, u};
{
// REVISIT: check return value?
std::ignore = parser.parse(input);
}
}
return ss.str();
}
} // namespace syntax