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
461
462
463
464
465
466
467
468
469
// EndBASIC
// Copyright 2020 Julio Merino
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations
// under the License.

//! Interactive help support.

use crate::ast::{ArgSep, Expr, VarType};
use crate::console::Console;
use crate::eval::{BuiltinFunction, CallableMetadata, CallableMetadataBuilder};
use crate::exec::{self, BuiltinCommand, Machine};
use async_trait::async_trait;
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;

/// Cheat-sheet for the language syntax.
const LANG_REFERENCE: &str = r"
    Symbols (variable and function references):
        name?    Boolean (TRUE and FALSE).
        name%    Integer (32 bits).
        name$    String.
        name     Type determined by value or definition.

    Assignments:
        varref = expr

    Expressions:
        a + b      a - b       a * b     a / b      a MOD b    -a
        a AND b    NOT a       a OR b    a XOR b
        a = b      a <> b      a < b     a <= b     a > b      a >= b
        (a)        varref      funcref(a1[, ..., aN])

    Flow control:
        IF expr THEN: ...: ELSE IF expr THEN: ...: ELSE: ...: END IF
        FOR varref = expr TO expr [STEP int]: ...: NEXT
        WHILE expr: ...: END WHILE

    Misc:
        st1: st2    Separates statements (same as a newline).
        REM text    Comment until end of line.
        ' text      Comment until end of line.
        ,           Long separator for arguments to builtin call.
        ;           Short separator for arguments to builtin call.
";

/// Returns the header for the help summary.
fn header() -> String {
    format!(
        "
    EndBASIC {}
    Copyright 2020 Julio Merino

    Project page at <{}>
    License Apache Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0>
",
        env!("CARGO_PKG_VERSION"),
        env!("CARGO_PKG_HOMEPAGE")
    )
}

/// Computes a unified collection of metadata objects for all given `commands` and `functions`.
// TODO(jmmv): This is a code smell from the lack of genericity between commands and functions.
// If we can homogenize their representation, this should go away.
fn compute_callables<'a>(
    commands: &'a HashMap<&'static str, Rc<dyn BuiltinCommand>>,
    functions: &'a HashMap<&'static str, Rc<dyn BuiltinFunction>>,
) -> HashMap<&'static str, &'a CallableMetadata> {
    let mut callables: HashMap<&'static str, &'a CallableMetadata> = HashMap::default();
    for (name, command) in commands.iter() {
        assert!(!callables.contains_key(name), "Command names are in a map; must be unique");
        callables.insert(&name, command.metadata());
    }
    for (name, function) in functions.iter() {
        assert!(!callables.contains_key(name), "Command and function names are not disjoint");
        callables.insert(&name, function.metadata());
    }
    callables
}

/// Builds the index of commands needed to print the summary.
///
/// The return value is the index in the form of a (category name -> (name, blurb)) mapping,
/// followed by the length of the longest command name that was found.
fn build_index(
    callables: &HashMap<&'static str, &CallableMetadata>,
) -> (BTreeMap<&'static str, BTreeMap<String, &'static str>>, usize) {
    let mut index = BTreeMap::default();
    let mut max_length = 0;
    for metadata in callables.values() {
        let name = format!("{}{}", metadata.name(), metadata.return_type().annotation());
        if name.len() > max_length {
            max_length = name.len();
        }
        let blurb = metadata.description().next().unwrap();
        index.entry(metadata.category()).or_insert_with(BTreeMap::default).insert(name, blurb);
    }
    (index, max_length)
}

/// The `HELP` command.
pub struct HelpCommand {
    metadata: CallableMetadata,
    console: Rc<RefCell<dyn Console>>,
}

impl HelpCommand {
    /// Creates a new command that writes help messages to `output`.
    pub fn new(console: Rc<RefCell<dyn Console>>) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("HELP", VarType::Void)
                .with_syntax("[topic]")
                .with_category("Interpreter manipulation")
                .with_description(
                    "Prints interactive help.
Without arguments, shows a summary of all available help topics.
With a single argument, shows detailed information about the given help topic, command, or \
function.",
                )
                .build(),
            console,
        })
    }

    /// Prints a summary of all available help topics.
    fn summary(&self, callables: &HashMap<&'static str, &CallableMetadata>) -> exec::Result<()> {
        let (index, max_length) = build_index(callables);

        let mut console = self.console.borrow_mut();
        for line in header().lines() {
            console.print(line)?;
        }

        for (category, by_name) in index.iter() {
            console.print("")?;
            console.print(&format!("    >> {} <<", category))?;
            for (name, blurb) in by_name.iter() {
                let filler = " ".repeat(max_length - name.len());
                console.print(&format!("    {}{}    {}", name, filler, blurb))?;
            }
        }

        console.print("")?;
        console.print("    Type HELP followed by a command or function name for details.")?;
        console.print("    Type HELP LANG for a quick reference guide about the language.")?;
        console.print("")?;
        Ok(())
    }

    /// Describes one command or function.
    fn describe_callable(&self, metadata: &CallableMetadata) -> exec::Result<()> {
        let mut console = self.console.borrow_mut();
        console.print("")?;
        if metadata.return_type() == VarType::Void {
            if metadata.syntax().is_empty() {
                console.print(&format!("    {}", metadata.name()))?
            } else {
                console.print(&format!("    {} {}", metadata.name(), metadata.syntax()))?
            }
        } else {
            console.print(&format!(
                "    {}{}({})",
                metadata.name(),
                metadata.return_type().annotation(),
                metadata.syntax(),
            ))?;
        }
        for line in metadata.description() {
            console.print("")?;
            console.print(&format!("    {}", line))?;
        }
        console.print("")?;
        Ok(())
    }

    /// Prints a quick reference of the language syntax.
    fn describe_lang(&self) -> exec::Result<()> {
        let mut console = self.console.borrow_mut();
        for line in LANG_REFERENCE.lines() {
            // Print line by line to honor any possible differences in line feeds.
            console.print(line)?;
        }
        console.print("")?;
        Ok(())
    }
}

#[async_trait(?Send)]
impl BuiltinCommand for HelpCommand {
    fn metadata(&self) -> &CallableMetadata {
        &self.metadata
    }

    async fn exec(
        &self,
        args: &[(Option<Expr>, ArgSep)],
        machine: &mut Machine,
    ) -> exec::Result<()> {
        let callables = compute_callables(machine.get_commands(), machine.get_functions());
        match args {
            [] => self.summary(&callables)?,
            [(Some(Expr::Symbol(vref)), ArgSep::End)] => {
                let name = vref.name().to_ascii_uppercase();
                if name == "LANG" {
                    if vref.ref_type() != VarType::Auto {
                        return exec::new_usage_error("Incompatible type annotation");
                    }
                    self.describe_lang()?;
                } else {
                    match callables.get(name.as_str()) {
                        Some(metadata) => {
                            if vref.ref_type() != VarType::Auto
                                && vref.ref_type() != metadata.return_type()
                            {
                                return exec::new_usage_error("Incompatible type annotation");
                            }
                            self.describe_callable(metadata)?;
                        }
                        None => {
                            return exec::new_usage_error(format!(
                                "Cannot describe unknown command or function {}",
                                name
                            ))
                        }
                    }
                }
            }
            _ => return exec::new_usage_error("HELP takes zero or only one argument"),
        }
        Ok(())
    }
}

#[cfg(test)]
pub(crate) mod testutils {
    use super::*;
    use crate::ast::Value;
    use crate::eval::{self, CallableMetadata, CallableMetadataBuilder};

    /// A command that does nothing.
    pub(crate) struct DoNothingCommand {
        metadata: CallableMetadata,
    }

    impl DoNothingCommand {
        /// Creates a new instance of the command.
        pub fn new() -> Rc<Self> {
            Rc::from(Self {
                metadata: CallableMetadataBuilder::new("DO_NOTHING", VarType::Void)
                    .with_syntax("this [would] <be|the> syntax \"specification\"")
                    .with_category("Testing")
                    .with_description(
                        "This is the blurb.
First paragraph of the extended description.
Second paragraph of the extended description.",
                    )
                    .build(),
            })
        }
    }

    #[async_trait(?Send)]
    impl BuiltinCommand for DoNothingCommand {
        fn metadata(&self) -> &CallableMetadata {
            &self.metadata
        }

        async fn exec(
            &self,
            _args: &[(Option<Expr>, ArgSep)],
            _machine: &mut Machine,
        ) -> exec::Result<()> {
            Ok(())
        }
    }

    /// A function that does nothing.
    pub(crate) struct EmptyFunction {
        metadata: CallableMetadata,
    }

    impl EmptyFunction {
        pub(crate) fn new() -> Rc<Self> {
            Rc::from(Self {
                metadata: CallableMetadataBuilder::new("EMPTY", VarType::Text)
                    .with_syntax("this [would] <be|the> syntax \"specification\"")
                    .with_category("Testing")
                    .with_description(
                        "This is the blurb.
First paragraph of the extended description.
Second paragraph of the extended description.",
                    )
                    .build(),
            })
        }
    }

    impl BuiltinFunction for EmptyFunction {
        fn metadata(&self) -> &CallableMetadata {
            &self.metadata
        }

        fn exec(&self, _args: Vec<Value>) -> eval::FunctionResult {
            Ok(Value::Text("irrelevant".to_owned()))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::testutils::*;
    use super::*;
    use crate::console::testutils::*;
    use crate::exec::MachineBuilder;
    use futures_lite::future::block_on;
    use std::cell::RefCell;

    /// Expects the output to the console to be just print calls and concatenates them all as they
    /// would have been printed on screen.
    fn flatten_captured_out(output: &[CapturedOut]) -> String {
        output.iter().fold(String::new(), |result, o| match o {
            CapturedOut::Print(text) => result + &text + "\n",
            _ => panic!("Unexpected element in output"),
        })
    }

    /// Runs the `input` code on a new machine and verifies that it fails with `expected_err`.
    fn do_error_test(input: &str, expected_err: &str) {
        let console = Rc::from(RefCell::from(MockConsoleBuilder::new().build()));
        let mut machine = MachineBuilder::default()
            .add_command(HelpCommand::new(console.clone()))
            .add_command(DoNothingCommand::new())
            .add_function(EmptyFunction::new())
            .build();
        assert_eq!(
            expected_err,
            format!(
                "{}",
                block_on(machine.exec(&mut input.as_bytes())).expect_err("Execution did not fail")
            )
        );
        assert!(console.borrow().captured_out().is_empty());
    }

    #[test]
    fn test_help_summarize_callables() {
        let console = Rc::from(RefCell::from(MockConsoleBuilder::new().build()));
        let mut machine = MachineBuilder::default()
            .add_command(HelpCommand::new(console.clone()))
            .add_command(DoNothingCommand::new())
            .add_function(EmptyFunction::new())
            .build();
        block_on(machine.exec(&mut b"HELP".as_ref())).unwrap();

        let text = flatten_captured_out(console.borrow().captured_out());
        assert_eq!(
            header()
                + "
    >> Interpreter manipulation <<
    HELP          Prints interactive help.

    >> Testing <<
    DO_NOTHING    This is the blurb.
    EMPTY$        This is the blurb.

    Type HELP followed by a command or function name for details.
    Type HELP LANG for a quick reference guide about the language.

",
            text
        );
    }

    #[test]
    fn test_help_describe_command() {
        let console = Rc::from(RefCell::from(MockConsoleBuilder::new().build()));
        let mut machine = MachineBuilder::default()
            .add_command(HelpCommand::new(console.clone()))
            .add_command(DoNothingCommand::new())
            .build();
        block_on(machine.exec(&mut b"help Do_Nothing".as_ref())).unwrap();

        let text = flatten_captured_out(console.borrow().captured_out());
        assert_eq!(
            "
    DO_NOTHING this [would] <be|the> syntax \"specification\"

    This is the blurb.

    First paragraph of the extended description.

    Second paragraph of the extended description.

",
            &text
        );
    }

    fn do_help_describe_function_test(name: &str) {
        let console = Rc::from(RefCell::from(MockConsoleBuilder::new().build()));
        let mut machine = MachineBuilder::default()
            .add_command(HelpCommand::new(console.clone()))
            .add_function(EmptyFunction::new())
            .build();
        block_on(machine.exec(&mut format!("help {}", name).as_bytes())).unwrap();

        let text = flatten_captured_out(console.borrow().captured_out());
        assert_eq!(
            "
    EMPTY$(this [would] <be|the> syntax \"specification\")

    This is the blurb.

    First paragraph of the extended description.

    Second paragraph of the extended description.

",
            &text
        );
    }

    #[test]
    fn test_help_describe_function_without_annotation() {
        do_help_describe_function_test("Empty")
    }

    #[test]
    fn test_help_describe_function_with_annotation() {
        do_help_describe_function_test("EMPTY$")
    }

    #[test]
    fn test_help_lang() {
        let console = Rc::from(RefCell::from(MockConsoleBuilder::new().build()));
        let mut machine = MachineBuilder::default()
            .add_command(HelpCommand::new(console.clone()))
            .add_command(DoNothingCommand::new())
            .build();
        block_on(machine.exec(&mut b"help lang".as_ref())).unwrap();

        let text = flatten_captured_out(console.borrow().captured_out());
        assert_eq!(String::from(LANG_REFERENCE) + "\n", text);
    }

    #[test]
    fn test_help_errors() {
        do_error_test("HELP foo bar", "Unexpected value in expression");
        do_error_test("HELP foo, bar", "HELP takes zero or only one argument");

        do_error_test("HELP lang%", "Incompatible type annotation");

        do_error_test("HELP foo$", "Cannot describe unknown command or function FOO");
        do_error_test("HELP foo", "Cannot describe unknown command or function FOO");

        do_error_test("HELP do_nothing$", "Incompatible type annotation");
        do_error_test("HELP empty?", "Incompatible type annotation");
    }
}