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
//! GameShell - A fast and lightweight shell for interactive work in Rust.
//!
//! GameShell is a little lisp-like command shell made to be embedded in rust programs. It has no
//! runtime and attempts to call given handlers as fast as possible. This means that GameShell is
//! made for one-time commands, where the heavy lifting is done in your specified handler
//! functions. It does not do any JIT/compilation or bytecode conversion, but goes straight to a
//! handler and calls it.
//!
//! # Language #
//!
//! The language is just
//! ```ignore
//! command argument (subcommand argument ...) (#literal string inside here) argument ...
//! ```
//!
//! If an opened parenthesis is not closed on a newline, the next line is also considered part of
//! the command:
//! ```ignore
//! command (
//!     subcommand
//!     argument
//!     ...
//! ) argument ...
//! ```
//!
//! # Example #
//!
//! This example sets up a basic interpreter and a single handler for a single command. More
//! commands and handlers can be added.
//!
//! ```
//! use gameshell::{
//!     predicates::*, types::Type, Evaluator, GameShell, IncConsumer,
//! };
//! use std::str::from_utf8;
//!
//! // This is the input stream, GameShell will handle anything that implements
//! // std::io::Read, and will efficiently acquire data from such a stream.
//! let read = b"Lorem ipsum 1.23\n";
//! // This is the output stream, GameShell will use this to write messages out.
//! let mut write = [0u8; 18];
//!
//! // A gameshell is created by supplying a context object (here 0u8), and an IO stream.
//! let mut eval = GameShell::new(0u8, &read[..], &mut write[..]);
//!
//! // We then register command handler functions to GameShell, such that it can run commands
//! // when reading from the input stream
//! //
//! // Each command handler takes a `&mut Context` (here u8), and a list of arguments.
//! // It returns a result, `Ok` indicating a successful computation,
//! // and an `Err` indicating an error, aborting any nested computation and writing out the
//! // error message to the writer.
//! fn handler(context: &mut u8, args: &[Type]) -> Result<String, String> {
//!     *context += 1;
//!     println!("Got types: {:?}", args[0]);
//!     Ok("Hello world!".into())
//! }
//!
//! // Register the handler and associate it with the command "Lorem ipsum <f32>".
//! // The first element in the pair is a string literal on which we match the command tree,
//! // and the second argument is an arbitrary `Decider` which parses our input data into a
//! // `Type`. Deciders can consume as many elements as they like.
//! eval.register((&[("Lorem", None), ("ipsum", ANY_F32)], handler)).unwrap();
//!
//! // Run the command loop, keeps reading from the tcp buffer until the buffer has no more
//! // elements. When reading from a `TcpStream` this call will block until the stream is
//! // closed. The `buffer` provided here is the buffer for parsing a single incoming whole
//! // command. If the command exceeds this size, the command will be discarded and the
//! // connection severed.
//! let buffer = &mut [0u8; 1024];
//! eval.run(buffer);
//!
//! // Ensure that we have run at least once, our starting context was 0, which should now be 1
//! assert_eq!(1, *eval.context());
//! // Our Ok message has been written to the writer
//! assert_eq!("Ok(\"Hello world!\")", from_utf8(&write[..]).unwrap());
//! ```
//!
//! # Why does a command handler return a string instead of a type? #
//!
//! Because nested commands may reinterpret the string in any way they like, according to an
//! arbitrary decider. Thus, we can't return types. This is an inefficiency to allow for proper
//! error checking in nested calls.
//!
//! As unfortunate as that is, this library is not meant to sacrifice usability for speed. If you
//! want speed, you can just collapse two commands into one and use a single handler, since pure
//! Rust will always beat this library at speed.
//!
//! # Builtin commands #
//!
//! GameShell has 2 builtin commands:
//! ```ignore
//! ?
//! ```
//! List all registered commands and their potential arguments. An argument to this command will
//! regex filter the output: `? lorem`.
//! and
//! ```ignore
//! autocomplete
//! ```
//! Autocomplete a query.
//!
//! These commands return strings that contain useful information to be displayed to the user. If
//! you do not wish to expose these commands then you overwrite these commands using a command
//! handler.
#![deny(
    missing_docs,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unused_import_braces,
    unused_qualifications
)]
pub use crate::{evaluator::Evaluator, incconsumer::IncConsumer};
use crate::{
    incconsumer::{Consumption, Process, Validation},
    types::Type,
};
use cmdmat::RegError;
pub use cmdmat::{self, Spec};
pub use metac::{Evaluate, PartialParse, PartialParseOp};
use std::{
    io::{Read, Write},
    str::from_utf8,
};

#[cfg(feature = "with-tokio")]
mod applicator;
pub mod evaluator;
mod incconsumer;
pub mod predicates;
pub mod types;

#[cfg(feature = "with-tokio")]
pub use applicator::tokio_apply;

/// Feedback provided by the interpreter. All results are either a success string or an error
/// string.
/// Errors will abort any nested expressions and return the error immediately.
pub type Feedback = Result<String, String>;

/// The main virtual machine wrapper for a game shell
///
/// This wrapper consumes an input and output stream through which it writes messages.
pub struct GameShell<'a, C, R: Read, W: Write> {
    evaluator: Evaluator<'a, C>,
    parser: PartialParse,
    reader: R,
    writer: W,
}

impl<'a, C, R: Read, W: Write> GameShell<'a, C, R, W> {
    /// Spawn a new gameshell with a given context and readers/writers.
    pub fn new(context: C, reader: R, writer: W) -> Self {
        Self {
            evaluator: Evaluator::new(context),
            parser: PartialParse::default(),
            reader,
            writer,
        }
    }

    /// Get a reference to the current evaluator.
    pub fn evaluator(&mut self) -> &mut Evaluator<'a, C> {
        &mut self.evaluator
    }

    /// Get a reference to the current context.
    pub fn context(&self) -> &C {
        self.evaluator.context()
    }

    /// Get a mutable reference to the current context.
    pub fn context_mut(&mut self) -> &mut C {
        self.evaluator.context_mut()
    }

    /// Register a command specificator to this gameshell instance.
    pub fn register(&mut self, spec: Spec<'_, 'a, Type, String, C>) -> Result<(), RegError> {
        self.evaluator.register(spec)
    }

    /// Register multiple command specifications to this gameshell instance.
    pub fn register_many(
        &mut self,
        spec: &[Spec<'_, 'a, Type, String, C>],
    ) -> Result<(), RegError> {
        self.evaluator.register_many(spec)
    }
}

impl<'a, C, R: Read, W: Write> IncConsumer for GameShell<'a, C, R, W> {
    fn consume(&mut self, output: &mut [u8]) -> Consumption {
        if output.is_empty() {
            let _ = self
                .writer
                .write(b"DecodeError(\"Internal buffer is full, disconnecting\")");
            return Consumption::Stop;
        }
        match self.reader.read(output) {
            Ok(0) => Consumption::Stop,
            Ok(count) => Consumption::Consumed(count),
            Err(_) => Consumption::Stop,
        }
    }
    fn validate(&mut self, input: u8) -> Validation {
        match self.parser.parse_increment(input) {
            PartialParseOp::Ready => Validation::Ready,
            PartialParseOp::Unready => Validation::Unready,
            PartialParseOp::Discard => Validation::Discard,
        }
    }
    fn process(&mut self, input: &[u8]) -> Process {
        let string = from_utf8(input);
        if let Ok(string) = string {
            let result = self.evaluator.interpret_single(string);
            match result {
                Ok(result) => {
                    match result {
                        Feedback::Ok(res) => {
                            if self
                                .writer
                                .write_all(format!("Ok({:?})", res).as_bytes())
                                .is_err()
                            {
                                return Process::Stop;
                            }
                        }
                        Feedback::Err(res) => {
                            if self
                                .writer
                                .write_all(format!("Err({:?})", res).as_bytes())
                                .is_err()
                            {
                                return Process::Stop;
                            }
                        }
                    }
                    if self.writer.flush().is_err() {
                        return Process::Stop;
                    }
                }
                Err(parse_error) => {
                    if self
                        .writer
                        .write_all(
                            format!("ParseError(\"Unable to parse input: {:?}\")", parse_error)
                                .as_bytes(),
                        )
                        .is_err()
                    {
                        return Process::Stop;
                    }
                    if self.writer.flush().is_err() {
                        return Process::Stop;
                    }
                }
            }
            Process::Continue
        } else {
            if self
                .writer
                .write_all(b"DecodeError(\"Received invalid UTF-8 input, disconnecting\")")
                .is_err()
            {
                return Process::Stop;
            }
            if self.writer.flush().is_err() {
                return Process::Stop;
            }
            Process::Stop
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::predicates::*;

    #[test]
    fn basic_case() {
        let read = b"Lorem ipsum";
        let mut write = [0u8; 10];
        let mut shell = GameShell::new(0u8, &read[..], &mut write[..]);

        assert_eq!(&mut 0u8, shell.context_mut());
    }

    #[test]
    fn basic_byte_stream() {
        let read = b"call 1.23\n";
        let mut write = [0u8; 10];

        let mut eval = GameShell::new(0u8, &read[..], &mut write[..]);

        fn handler(context: &mut u8, _args: &[Type]) -> Result<String, String> {
            *context += 1;
            Ok("".into())
        }

        eval.register((&[("call", ANY_F32)], handler)).unwrap();

        let buffer = &mut [0u8; 1024];
        eval.run(buffer);

        assert_eq!(1, *eval.context());
    }

    #[test]
    fn discard_stream_first_command_too_big() {
        let read = b"call 1.2\ncall 3.1\ncall 99.9999\ncall 1.0";
        let mut write = [0u8; 1024];

        let mut eval = GameShell::new(0u8, &read[..], &mut write[..]);

        fn handler(context: &mut u8, _args: &[Type]) -> Result<String, String> {
            *context += 1;
            Ok("".into())
        }

        eval.register((&[("call", ANY_F32)], handler)).unwrap();

        let buffer = &mut [0u8; 10];
        eval.run(buffer);

        assert_eq!(2, *eval.context());

        let index = write
            .iter()
            .enumerate()
            .find(|(_, &byte)| byte == b'\0')
            .map(|(idx, _)| idx)
            .unwrap();
        assert_eq!(
            "Ok(\"\")Ok(\"\")DecodeError(\"Internal buffer is full, disconnecting\")",
            from_utf8(&write[0..index]).unwrap()
        );
    }

    #[test]
    fn partial_read_succeeds() {
        let read = b"call 1.2\nrock 3.1\n";
        let mut write = [0u8; 1024];

        let mut eval = GameShell::new(0f32, &read[..], &mut write[..]);

        fn handler(context: &mut f32, args: &[Type]) -> Result<String, String> {
            match args[0] {
                Type::F32(number) => *context += number,
                _ => panic!(),
            }
            Ok("".into())
        }

        eval.register((&[("call", ANY_F32)], handler)).unwrap();
        eval.register((&[("rock", ANY_F32)], handler)).unwrap();

        let buffer = &mut [0u8; 12];
        eval.run(buffer);

        assert_eq!(4.3, *eval.context());
    }
}