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
//! This crate provides traits and macros that make your application's structs and functions interactive.
//!
//! Annotating a struct with `#[derive(Interactive)]`, a struct's methods with `#[Methods]`
//! and a free function with `#[Function]` will implement a set of traits,
//! that will allow you to access them as if Rust had a REPL.
//!
//! Use this crate as an alternative for "print debugging" or
//! as an ergonomic testing API.
//!
//! This crate is `no_std` compatible so you can use it to interact with embedded devices
//! and blink those LEDs from a USB or UART connection.
//!
//! # Usage
//! * Annotate everything you want to access with [`Interactive`], [`Methods`] and [`Function`]
//! * Define a new struct that owns or holds references to the objects you want to access
//! * Derive [`InteractiveRoot`] for it
//! * Use the trait's methods to evaluate a string
//! (the simplest one is [`eval_to_string`](InteractiveRoot::eval_to_string) but others allow for more custom behaviour)
//! * Accessing a field will give you its Debug representation
//! * Calling a function or a method will parse its arguments and give you the Debug representation of its return value
//!
//! [`Interactive`]: macro@Interactive
//! [`Methods`]: macro@Methods
//! [`Function`]: macro@Function
//! [`InteractiveRoot`]: macro@InteractiveRoot
//!
//! Since this crate makes a lot of use of the [`Debug`] trait the helper macro [`PartialDebug`] is provided.
//! It implements `Debug` for a struct replacing all fields that do not implement `Debug` with a placeholder.
//!
//! [`Debug`]: core::fmt::Debug
//!
//! ### CLI Usage
//! Functions like [`get_all_field_names`](Interactive::get_all_field_names) are provided.
//! This makes it possible to implement things like auto-completion.
//!
//! Have a look at the autocomplete example for how this might be done using the [rustyline](https://docs.rs/crate/rustyline) crate.
//!
//! # Example
//! ```
//! use rusteval::{Interactive, Methods, InteractiveRoot, Function, PartialDebug};
//!
//! #[derive(Default)]
//! struct NoDebug;
//!
//! #[derive(Interactive, PartialDebug, Default)]
//! struct ChildStruct {
//!     last_sum: f32,
//!     no_debug: NoDebug,
//! }
//!
//! #[Methods]
//! impl ChildStruct {
//!     fn add(&mut self, a: f32, b: f32) -> f32 {
//!         self.last_sum = a + b;
//!         self.last_sum
//!     }
//! }
//!
//! #[derive(Interactive, Debug, Default)]
//! struct ParentStruct {
//!     child: ChildStruct,
//! }
//!
//! #[derive(InteractiveRoot, Debug, Default)]
//! struct Root {
//!     parent: ParentStruct,
//! }
//!
//! #[Function]
//! fn split_str_at(s: &str, mid: usize) -> (&str, &str) {
//!     s.split_at(mid)
//! }
//!
//! let mut root = Root::default();
//! assert_eq!(root.eval_to_string("parent.child.add(4.2, 6.9)"), "11.1");
//! assert_eq!(root.eval_to_string("parent.child"), "ChildStruct { last_sum: 11.1, no_debug: Unknown }");
//! // split_str_at("foobar", 3) => ("foo", "bar")
//! assert_eq!(root.eval_to_string("split_str_at(\"foobar\", 3)"), "(\"foo\", \"bar\")");
//! ```
//!
//! # How it works
//! This crate makes use of the unstable `specialization` feature, so it is only available on nightly.
//!
//! Methods like `try_as_interactive` are implemented on all types.
//! The method normally returns an error but in the specialized case
//! a trait object (`&dyn Interactive` in this case) is returned.
//!
//! The macros then implement getters that look something like this:
//! ```
//! # use rusteval::*;
//! # use rusteval::specialization::*;
//! # struct Stub {
//! #     field1: (),
//! #     field2: (),
//! # }
//! # impl Stub {
//! fn get_field<'a>(&'a self, field_name: &'a str) -> Result<'_, &dyn Interactive> {
//!     match field_name {
//!         "field1" => self.field1.try_as_interactive(),
//!         "field2" => self.field2.try_as_interactive(),
//!         _ => Err(InteractiveError::FieldNotFound {
//!             type_name: "Struct",
//!             field_name,
//!         }),
//!     }
//! }
//! # }
//! ```
//!
//! See the macro's documentation for more details.
//!
//! # Current limitations:
//! * Methods and functions can only be made interactive if their argument types are supported
//! * Enums are not supported

#![allow(incomplete_features)] // TODO re-enable warning
#![feature(specialization)]
#![warn(
    missing_copy_implementations,
    missing_debug_implementations,
    missing_docs,
    trivial_casts,
    rust_2018_idioms
)]
#![cfg_attr(not(feature = "std"), no_std)]

/// Derive this on a struct to make it an interactive access point for your application.
///
/// Same as `#[derive(Interactive)]` but with two additional impls:
/// * [`trait@InteractiveRoot`] with its default methods
/// * [`trait@Methods`] as a way to access free functions marked with the attribute [`macro@Function`] (only available with default features on).
///
///
/// ```
/// use rusteval::{Interactive, InteractiveRoot, Methods, Function};
///
/// #[derive(Interactive)]
/// struct SomethingInteractive;
///
/// #[Methods]
/// impl SomethingInteractive{
///     fn ping(&self) -> &str{
///         "pong"
///     }
/// }
///
/// #[Function]
/// fn add_one(a: u32) -> u32 {
///     a + 1
/// }
///
/// let something = SomethingInteractive;
///
/// #[derive(InteractiveRoot)]
/// struct Root {
///     field: SomethingInteractive,
/// }
///
/// let mut root = Root { field: something };
/// assert_eq!(root.eval_to_string("field.ping()"), "\"pong\"");
/// assert_eq!(root.eval_to_string("add_one(42)"), "43");
/// ```
pub use rusteval_derive::InteractiveRoot;

/// Gives interactive access to a structs fields.
///
/// # What it does:
/// ```
/// # use rusteval::Interactive;
/// #
/// #[derive(Interactive)]
/// struct Struct {
///     field1: u32,
///     field2: u32,
/// }
/// ```
/// Expands to something like:
/// ```
/// # use rusteval::*;
/// # use rusteval::specialization::*;
/// # use rusteval::InteractiveError::*;
/// # use core::fmt::Debug;
/// #
/// # struct Struct {
/// #     field1: u32,
/// #     field2: u32,
/// # }
/// impl Interactive for Struct {
///     fn get_field<'a>(&'a self, field_name: &'a str) -> Result<'_, &dyn Interactive> {
///         match field_name {
///             "field1" => self.field1.try_as_interactive(),
///             "field2" => self.field2.try_as_interactive(),
///             _ => Err(FieldNotFound {
///                 type_name: "Struct",
///                 field_name,
///             }),
///         }
///     }
///     fn get_field_mut<'a>(&'a mut self, field_name: &'a str) -> Result<'_, &mut dyn Interactive> {
///         /* ... */
///         # unimplemented!()
///     }
///     fn eval_field(&self, field_name: &str, f: &mut dyn FnMut(Result<'_, &dyn Debug>)) {
///         match field_name {
///             "field1" => f(self.field1.try_as_debug()),
///             /* ... */
///             # _ => unimplemented!(),
///         }
///     }
///     fn get_all_field_names(&self) -> &'static [&'static str] {
///         &["field1", "field2"]
///     }
/// }
/// ```
pub use rusteval_derive::Interactive;

/// Gives interactive access to a structs methods.
///
/// Only methods with supported argument types will be made interactive.
///
/// Currently supported argument types are:
///
/// `bool`, `char`, `f32`, `f64`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize`, `u8`, `u16`, `u32`,
/// `u64`, `u128`, `usize`, `String`, `str`
///
/// References to these types are also supported.
///
/// Generic argument types are not supported.
///
/// Both `String` and `str` are only available with default features on.
///
/// # What it does:
/// ```
/// # use rusteval::Methods;
/// #
/// # struct Struct;
/// #
/// #[Methods]
/// impl Struct {
///     fn ping(&self) -> &str {
///         "pong"
///     }
///     fn frob(&mut self, arg: u32){
///         unimplemented!()
///     }
/// }
/// ```
/// Expands to something like:
/// (notice how `frob` is only available inside `eval_method_mut`)
/// ```
/// # use core::fmt::Debug;
/// # use rusteval::*;
/// # use rusteval::arg_parse::*;
/// # use rusteval::InteractiveError::*;
/// #
/// # struct Struct;
/// #
/// # impl Struct {
/// #     fn ping(&self) -> &str {
/// #         "pong"
/// #     }
/// #     fn frob(&mut self, arg: u32){
/// #         unimplemented!()
/// #     }
/// # }
/// #
/// impl Methods for Struct {
///     fn eval_method(&self, method_name: &str, args: &str, f: &mut dyn FnMut(Result<'_, &dyn Debug>)) {
///         match method_name {
///             "ping" => match parse_0_args(method_name, args) {
///                 Ok(()) => f(Ok(&self.ping())),
///                 Err(e) => f(Err(e)),
///             },
///             _ => f(Err(MethodNotFound {
///                 type_name: "Struct",
///                 method_name,
///             })),
///         }
///     }
///     fn eval_method_mut(&mut self, method_name: &str, args: &str, f: &mut dyn FnMut(Result<'_, &dyn Debug>)) {
///         match method_name {
///             "ping" => match parse_0_args(method_name, args) {
///                 Ok(()) => f(Ok(&self.ping())),
///                 Err(e) => f(Err(e)),
///             },
///             "frob" => match parse_1_arg(method_name, args) {
///                 Ok((arg0,)) => f(Ok(&self.frob(arg0))),
///                 Err(e) => f(Err(e)),
///             },
///             _ => f(Err(MethodNotFound {
///                 type_name: "Struct",
///                 method_name,
///             })),
///         }
///     }
///     fn get_all_method_names(&self) -> &'static [&'static str] {
///         &["ping", "frob"]
///     }
/// }
/// ```
pub use rusteval_derive::Methods;

/// Implements [`Debug`] for a struct replacing all fields that do not implement `Debug` with a placeholder.
///
/// [`Debug`]: core::fmt::Debug
///
/// # What it does:
/// ```
/// # use rusteval::PartialDebug;
///
/// struct NoDebug;
///
/// #[derive(PartialDebug)]
/// struct Struct {
///     field: NoDebug,
/// }
/// ```
///
/// Expands to something like:
/// ```
/// # use std::fmt::Debug;
/// # use core::fmt;
/// # use rusteval::specialization::AsDebug;
/// #
/// # struct NoDebug;
/// # struct Struct {
/// #     field: NoDebug,
/// # }
/// #
/// impl Debug for Struct {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         f.debug_struct("Struct")
///             .field(
///                 "field",
///                 match &self.field.try_as_debug() {
///                     Ok(field) => field,
///                     Err(_) => &rusteval::specialization::Unknown,
///                 },
///             )
///             .finish()
///     }
/// }
///
/// ```
pub use rusteval_derive::PartialDebug;

/// Gives interactive access to a function.
///
/// Can be used in different modules.
///
/// This makes use of the [inventory](https://docs.rs/inventory/*/inventory/) crate
/// to submit a wrapper struct to a global registry.
///
/// You can gain access to the wrapped function by using `#[derive(InteractiveRoot)]`. ([link])
///
/// Since the inventory crate requires std this macro is only available with default features on.
///
/// [link]: macro@crate::InteractiveRoot
/// # What it does:
/// ```
/// # use rusteval::Function;
/// #
/// #[Function]
/// fn add_one(a: u32) -> u32 {
///     a + 1
/// }
/// ```
/// Expands to something like:
/// ```
/// # use core::fmt::Debug;
/// # use rusteval::*;
/// # use rusteval::arg_parse::*;
/// # use rusteval::inventory;
///
/// # fn add_one(a: u32) -> u32 {
/// #     a + 1
/// # }
/// #
/// struct FunctionXYZ;
/// impl Function for FunctionXYZ {
///     fn eval(&self, args: &str, f: &mut dyn FnMut(Result<'_, &dyn Debug>)) {
///         match parse_1_arg("add_one", args) {
///             Ok((arg0,)) => f(Ok(&add_one(arg0))),
///             Err(e) => f(Err(e)),
///         }
///     }
///     fn function_name(&self) -> &'static str {
///         "add_one"
///     }
/// }
/// inventory::submit! {
///     &FunctionXYZ as &dyn::rusteval::Function
/// }
///
/// ```
#[cfg(feature = "std")]
pub use rusteval_derive::Function;

pub use error::{ArgParseError, InteractiveError, Result};
#[cfg(feature = "std")]
pub use function::Function;
pub use interactive::{Interactive, Methods};
pub use root::InteractiveRoot;

#[cfg(feature = "std")]
#[doc(hidden)]
pub use inventory;

pub mod arg_parse;
mod error;
mod function;
mod interactive;
mod root;
pub mod specialization;