-
Notifications
You must be signed in to change notification settings - Fork 67
/
shell.cpp
348 lines (298 loc) · 11.1 KB
/
shell.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
// Copyright (C) 2020-2024 Jonathan Müller and lexy contributors
// SPDX-License-Identifier: BSL-1.0
#include <map>
#include <memory>
#include <string>
#include <lexy/callback.hpp>
#include <lexy/dsl.hpp>
#include <lexy_ext/shell.hpp>
namespace
{
// A shell with a couple of basic commands.
namespace shell
{
struct interpreter
{
// Manages I/O.
lexy_ext::shell<lexy_ext::default_prompt<lexy::utf8_encoding>> shell;
// The values of variables.
std::map<std::string, std::string> variables;
// Retrieves the value of a variable.
const std::string& lookup_var(const std::string& name) const
{
auto iter = variables.find(name);
if (iter == variables.end())
{
static const std::string not_found;
return not_found;
}
return iter->second;
}
};
// Special directives that control what happens with entered commands.
enum class directive
{
// Command following it is executed (the default).
execute,
// Parsing of the command following it is traced.
trace,
// All variables are printed.
vars,
};
class cmd_base
{
public:
virtual ~cmd_base() = default;
// Returns true if the shell should exit.
virtual bool execute(interpreter& intp) const = 0;
};
using command = std::unique_ptr<cmd_base>;
// Exits the shell.
class cmd_exit : public cmd_base
{
public:
bool execute(interpreter& intp) const override
{
intp.shell.write_message()("Goodbye.");
return true;
}
};
// Prints output.
class cmd_echo : public cmd_base
{
public:
explicit cmd_echo(std::string msg) : _msg(LEXY_MOV(msg)) {}
bool execute(interpreter& intp) const override
{
intp.shell.write_message()(_msg.data(), _msg.size());
return false;
}
private:
std::string _msg;
};
// Sets the value of a variable.
class cmd_set : public cmd_base
{
public:
explicit cmd_set(std::string name, std::string value)
: _name(LEXY_MOV(name)), _value(LEXY_MOV(value))
{}
bool execute(interpreter& intp) const override
{
intp.variables[_name] = _value;
return false;
}
private:
std::string _name;
std::string _value;
};
} // namespace shell
namespace grammar
{
namespace dsl = lexy::dsl;
// A bare argument or command name.
constexpr auto identifier = dsl::identifier(dsl::ascii::alnum);
//=== The arguments ===//
struct invalid_str_char
{
static constexpr auto name = "invalid string character";
};
// The content of a string literal: any unicode code point except for control characters.
constexpr auto str_char = (-dsl::unicode::control).error<invalid_str_char>;
// An unquoted sequence of characters.
struct arg_bare
{
static constexpr auto rule = identifier;
static constexpr auto value = lexy::as_string<std::string>;
};
// A string without escape characters.
struct arg_string
{
static constexpr auto rule = dsl::single_quoted(str_char);
static constexpr auto value = lexy::as_string<std::string>;
};
// A string with escape characters.
struct arg_quoted
{
struct interpolation
{
static constexpr auto rule = dsl::curly_bracketed(dsl::recurse<struct argument>);
static constexpr auto value
= lexy::bind(lexy::callback<std::string>(&shell::interpreter::lookup_var),
lexy::parse_state, lexy::values);
};
static constexpr auto escaped_sequences = lexy::symbol_table<char> //
.map<'"'>('"')
.map<'\\'>('\\')
.map<'/'>('/')
.map<'b'>('\b')
.map<'f'>('\f')
.map<'n'>('\n')
.map<'r'>('\r')
.map<'t'>('\t');
static constexpr auto rule = [] {
// C style escape sequences.
auto backslash_escape = dsl::backslash_escape.symbol<escaped_sequences>();
// Interpolation.
auto dollar_escape = dsl::dollar_escape.rule(dsl::p<interpolation>);
return dsl::quoted.limit(dsl::ascii::newline)(str_char, backslash_escape,
dollar_escape);
}();
static constexpr auto value = lexy::as_string<std::string>;
};
// An argument that expands to the value of a variable.
struct arg_var
{
static constexpr auto rule = [] {
auto bare = dsl::p<arg_bare>;
auto bracketed = dsl::curly_bracketed(dsl::recurse<argument>);
auto name = bracketed | dsl::else_ >> bare;
return dsl::dollar_sign >> name;
}();
static constexpr auto value
= lexy::bind(lexy::callback<std::string>(&shell::interpreter::lookup_var),
lexy::parse_state, lexy::values);
};
// An argument to a command.
struct argument
{
struct invalid
{
static constexpr auto name = "invalid argument character";
};
static constexpr auto rule = dsl::p<arg_string> | dsl::p<arg_quoted> //
| dsl::p<arg_var> | dsl::p<arg_bare> //
| dsl::error<invalid>;
static constexpr auto value = lexy::forward<std::string>;
};
// The separator between arguments.
constexpr auto arg_sep = [] {
struct missing_argument
{
static constexpr auto name()
{
return "missing argument";
}
};
auto blank = dsl::ascii::blank;
auto escaped_nl = dsl::backslash >> dsl::newline;
auto sep = dsl::must(blank | escaped_nl).error<missing_argument>;
return dsl::while_one(sep);
}();
//=== the commands ===//
struct cmd_exit
{
static constexpr auto rule = LEXY_KEYWORD("exit", identifier) | dsl::eof;
static constexpr auto value = lexy::new_<shell::cmd_exit, shell::command>;
};
struct cmd_echo
{
static constexpr auto rule = LEXY_KEYWORD("echo", identifier) >> arg_sep + dsl::p<argument>;
static constexpr auto value = lexy::new_<shell::cmd_echo, shell::command>;
};
struct cmd_set
{
static constexpr auto rule = LEXY_KEYWORD("set", identifier)
>> arg_sep + dsl::p<argument> + arg_sep + dsl::p<argument>;
static constexpr auto value = lexy::new_<shell::cmd_set, shell::command>;
};
// Parses one of three commands.
struct command
{
struct unknown_command
{
static constexpr auto name = "unknown command";
};
struct trailing_args
{
static constexpr auto name = "trailing command arguments";
};
static constexpr auto rule = [] {
auto unknown = dsl::error<unknown_command>(identifier);
auto commands = dsl::p<cmd_exit> | dsl::p<cmd_echo> //
| dsl::p<cmd_set> | unknown;
// Allow an optional argument separator after the final command,
// but then there should not be any other arguments after that.
return commands + dsl::if_(arg_sep) + dsl::peek(dsl::eol).error<trailing_args>;
}();
static constexpr auto value = lexy::forward<shell::command>;
};
//=== the directive ===//
// Parse an optional parsing directive with trailing separator.
// Note that it doesn't parse the following command, this is done manually.
struct directive
{
struct unknown_directive
{
static constexpr auto name = "unknown directive";
};
// Map pre-defined directives.
static constexpr auto directives
= lexy::symbol_table<shell::directive> //
.map<LEXY_SYMBOL("execute")>(shell::directive::execute) //
.map<LEXY_SYMBOL("trace")>(shell::directive::trace) //
.map<LEXY_SYMBOL("vars")>(shell::directive::vars);
static constexpr auto rule = [] {
auto pattern = dsl::identifier(dsl::ascii::alpha);
auto directive = dsl::symbol<directives>(pattern).error<unknown_directive>;
// A directive is optional, but it also consumes the argument separator if parsed.
return dsl::opt(dsl::colon >> directive + dsl::if_(arg_sep));
}();
// Forward the existing directive but default to execute.
static constexpr auto value
= lexy::bind(lexy::forward<shell::directive>, lexy::_1 or shell::directive::execute);
};
} // namespace grammar
} // namespace
#ifndef LEXY_TEST
# include <lexy/action/parse.hpp>
# include <lexy/action/scan.hpp>
# include <lexy/action/trace.hpp>
# include <lexy_ext/report_error.hpp>
int main()
{
for (shell::interpreter intp; intp.shell.is_open();)
{
// We repeatedly prompt for a new line.
// Note: everytime we do it, the memory of the previous line is cleared.
auto input = intp.shell.prompt_for_input();
// Use a scanner to handle the directives.
auto scanner = lexy::scan(input, lexy_ext::report_error);
// Parse a directive.
auto directive = scanner.parse<grammar::directive>();
if (!scanner)
continue;
auto exit = false;
switch (directive.value())
{
case shell::directive::execute: {
// Parse the command in the remaining input...
auto result = lexy::parse<grammar::command>(scanner.remaining_input(), intp,
lexy_ext::report_error);
if (result)
// ... and execute it.
exit = result.value()->execute(intp);
break;
}
case shell::directive::trace:
// Trace the command in the remaining input.
lexy::trace_to<grammar::command>(intp.shell.write_message().output_iterator(),
scanner.remaining_input(), {lexy::visualize_fancy});
break;
case shell::directive::vars: {
// Write all variables.
auto writer = intp.shell.write_message();
for (auto [name, value] : intp.variables)
{
writer(name.data(), name.length());
writer(" = ");
writer(value.data(), value.length());
writer("\n");
}
}
}
if (exit)
break;
}
}
#endif