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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use crate::console::{refill_and_print, Console};
use crate::exec::CATEGORY;
use async_trait::async_trait;
use endbasic_core::ast::{ArgSep, Expr, VarType};
use endbasic_core::exec::Machine;
use endbasic_core::syms::{
CallError, CallableMetadata, CallableMetadataBuilder, Command, CommandResult, Symbols,
};
use radix_trie::{Trie, TrieCommon};
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::io;
use std::rc::Rc;
const LANG_REFERENCE: &str = r"
Symbols (variable, array and function references):
name? Boolean (TRUE and FALSE).
name# Floating point (double).
name% Integer (32 bits).
name$ String.
name Type determined by value or definition.
Assignments and declarations:
varref[(dim1[, ..., dimN])] = expr
DIM varname[(dim1[, ..., dimN])] [AS BOOLEAN|DOUBLE|INTEGER|STRING]
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
arrayref(s1[, ..., sN]) 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: ...: WEND
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.
";
fn header() -> Vec<String> {
vec![
"".to_owned(),
format!(" EndBASIC {}", env!("CARGO_PKG_VERSION")),
" Copyright 2020-2021 Julio Merino".to_owned(),
"".to_owned(),
format!(" Project page at <{}>", env!("CARGO_PKG_HOMEPAGE")),
" License Apache Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0>".to_owned(),
]
}
trait Topic {
fn name(&self) -> &str;
fn title(&self) -> &str;
fn show_in_summary(&self) -> bool;
fn describe(&self, _console: &mut dyn Console) -> io::Result<()>;
}
struct CallableTopic {
name: String,
metadata: CallableMetadata,
}
impl Topic for CallableTopic {
fn name(&self) -> &str {
&self.name
}
fn title(&self) -> &str {
self.metadata.description().next().unwrap()
}
fn show_in_summary(&self) -> bool {
false
}
fn describe(&self, console: &mut dyn Console) -> io::Result<()> {
console.print("")?;
if self.metadata.return_type() == VarType::Void {
if self.metadata.syntax().is_empty() {
refill_and_print(console, self.metadata.name(), " ")?
} else {
refill_and_print(
console,
&format!("{} {}", self.metadata.name(), self.metadata.syntax()),
" ",
)?
}
} else {
refill_and_print(
console,
&format!(
"{}{}({})",
self.metadata.name(),
self.metadata.return_type().annotation(),
self.metadata.syntax(),
),
" ",
)?;
}
for paragraph in self.metadata.description() {
console.print("")?;
refill_and_print(console, paragraph, " ")?;
}
console.print("")?;
Ok(())
}
}
struct CategoryTopic {
name: &'static str,
metadatas: Vec<CallableMetadata>,
}
impl Topic for CategoryTopic {
fn name(&self) -> &str {
self.name
}
fn title(&self) -> &str {
self.name
}
fn show_in_summary(&self) -> bool {
true
}
fn describe(&self, console: &mut dyn Console) -> io::Result<()> {
let description = self.metadatas.get(0).expect("Must have at least one symbol").category();
let mut index = BTreeMap::default();
let mut max_length = 0;
for metadata in &self.metadatas {
debug_assert_eq!(
description,
metadata.category(),
"All commands registered in this category must be equivalent"
);
let name = format!("{}{}", metadata.name(), metadata.return_type().annotation());
if name.len() > max_length {
max_length = name.len();
}
let blurb = metadata.description().next().unwrap();
let previous = index.insert(name, blurb);
assert!(previous.is_none(), "Names should have been unique");
}
console.print("")?;
for line in description.lines() {
refill_and_print(console, line, " ")?;
console.print("")?;
}
for (name, blurb) in index.iter() {
let filler = " ".repeat(max_length - name.len());
console.print(&format!(" >> {}{} {}", name, filler, blurb))?;
}
console.print("")?;
refill_and_print(
console,
" Type HELP followed by the name of a symbol for details.",
" ",
)?;
console.print("")?;
Ok(())
}
}
struct LanguageTopic {}
impl Topic for LanguageTopic {
fn name(&self) -> &str {
"Language reference"
}
fn title(&self) -> &str {
"Language reference"
}
fn show_in_summary(&self) -> bool {
true
}
fn describe(&self, console: &mut dyn Console) -> io::Result<()> {
for line in LANG_REFERENCE.lines() {
console.print(line)?;
}
console.print("")?;
Ok(())
}
}
struct Topics(Trie<String, Box<dyn Topic>>);
impl Topics {
fn new(symbols: &Symbols) -> Self {
fn insert(topics: &mut Trie<String, Box<dyn Topic>>, topic: Box<dyn Topic>) {
let key = topic.name().to_ascii_uppercase();
topics.insert(key, topic);
}
let mut topics = Trie::default();
insert(&mut topics, Box::from(LanguageTopic {}));
let mut categories = HashMap::new();
for (name, symbol) in symbols.as_hashmap().iter() {
if let Some(metadata) = symbol.metadata() {
let category_title = metadata.category().lines().next().unwrap();
categories
.entry(category_title)
.or_insert_with(Vec::default)
.push(metadata.clone());
insert(
&mut topics,
Box::from(CallableTopic {
name: format!("{}{}", name, metadata.return_type().annotation()),
metadata: metadata.clone(),
}),
);
}
}
for (name, metadatas) in categories.into_iter() {
insert(&mut topics, Box::from(CategoryTopic { name, metadatas }));
}
Self(topics)
}
fn find(&self, name: &str) -> Result<&dyn Topic, CallError> {
let key = name.to_ascii_uppercase();
match self.0.get_raw_descendant(&key) {
Some(subtrie) => {
let children: Vec<(&String, &Box<dyn Topic>)> = subtrie.iter().collect();
match children[..] {
[(_name, topic)] => Ok(topic.as_ref()),
_ => {
let completions: Vec<String> =
children.iter().map(|(name, _topic)| (*name).to_owned()).collect();
Err(CallError::ArgumentError(format!(
"Ambiguous help topic {}; candidates are: {}",
name,
completions.join(", ")
)))
}
}
}
None => Err(CallError::ArgumentError(format!("Unknown help topic {}", name))),
}
}
fn values(&self) -> radix_trie::iter::Values<String, Box<dyn Topic>> {
self.0.values()
}
}
pub struct HelpCommand {
metadata: CallableMetadata,
console: Rc<RefCell<dyn Console>>,
}
impl HelpCommand {
pub fn new(console: Rc<RefCell<dyn Console>>) -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("HELP", VarType::Void)
.with_syntax("[topic]")
.with_category(CATEGORY)
.with_description(
"Prints interactive help.
Without arguments, shows a summary of all available top-level help topics.
With a single argument, which may be a bare name or a string, shows detailed information about the \
given help topic, command, or function. Topic names with spaces in them must be double-quoted.
Topic names are case-insensitive and can be specified as prefixes, in which case the topic whose \
name starts with the prefix will be shown. For example, the following invocations are all \
equivalent: HELP CON, HELP console, HELP \"Console manipulation\".",
)
.build(),
console,
})
}
fn summary(&self, topics: &Topics) -> io::Result<()> {
let mut console = self.console.borrow_mut();
for line in header() {
refill_and_print(&mut *console, &line, " ")?;
}
console.print("")?;
refill_and_print(&mut *console, "Top-level help topics:", " ")?;
console.print("")?;
for topic in topics.values() {
if topic.show_in_summary() {
console.print(&format!(" >> {}", topic.title()))?;
}
}
console.print("")?;
refill_and_print(
&mut *console,
"Type HELP followed by the name of a topic for details.",
" ",
)?;
refill_and_print(
&mut *console,
"Type HELP HELP for details on how to specify topic names.",
" ",
)?;
console.print("")?;
Ok(())
}
}
#[async_trait(?Send)]
impl Command for HelpCommand {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
async fn exec(&self, args: &[(Option<Expr>, ArgSep)], machine: &mut Machine) -> CommandResult {
let topics = Topics::new(machine.get_symbols());
match args {
[] => {
self.summary(&topics)?;
}
[(Some(Expr::Symbol(vref)), ArgSep::End)] => {
let topic = topics.find(&format!("{}", vref))?;
let mut console = self.console.borrow_mut();
topic.describe(&mut *console)?;
}
[(Some(Expr::Text(name)), ArgSep::End)] => {
let topic = topics.find(name)?;
let mut console = self.console.borrow_mut();
topic.describe(&mut *console)?;
}
_ => {
return Err(CallError::ArgumentError(
"HELP takes zero or only one argument".to_owned(),
))
}
}
Ok(())
}
}
pub fn add_all(machine: &mut Machine, console: Rc<RefCell<dyn Console>>) {
machine.add_command(HelpCommand::new(console));
}
#[cfg(test)]
pub(crate) mod testutils {
use super::*;
use endbasic_core::ast::Value;
use endbasic_core::syms::{
CallableMetadata, CallableMetadataBuilder, Function, FunctionResult,
};
pub(crate) struct DoNothingCommand {
metadata: CallableMetadata,
}
impl DoNothingCommand {
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
This is a sample category for testing.",
)
.with_description(
"This is the blurb.
First paragraph of the extended description.
Second paragraph of the extended description.",
)
.build(),
})
}
}
#[async_trait(?Send)]
impl Command for DoNothingCommand {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
async fn exec(
&self,
_args: &[(Option<Expr>, ArgSep)],
_machine: &mut Machine,
) -> CommandResult {
Ok(())
}
}
pub(crate) struct EmptyFunction {
metadata: CallableMetadata,
}
impl EmptyFunction {
pub(crate) fn new() -> Rc<Self> {
EmptyFunction::new_with_name("EMPTY")
}
pub(crate) fn new_with_name(name: &'static str) -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new(name, VarType::Text)
.with_syntax("this [would] <be|the> syntax \"specification\"")
.with_category(
"Testing
This is a sample category for testing.",
)
.with_description(
"This is the blurb.
First paragraph of the extended description.
Second paragraph of the extended description.",
)
.build(),
})
}
}
impl Function for EmptyFunction {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
fn exec(&self, _args: &[Expr], _symbols: &mut Symbols) -> FunctionResult {
Ok(Value::Text("irrelevant".to_owned()))
}
}
}
#[cfg(test)]
mod tests {
use super::testutils::*;
use super::*;
use crate::testutils::*;
fn tester() -> Tester {
let tester = Tester::empty();
let console = tester.get_console();
tester.add_command(HelpCommand::new(console))
}
#[test]
fn test_help_summarize_symbols() {
tester()
.add_command(DoNothingCommand::new())
.add_function(EmptyFunction::new())
.run("HELP")
.expect_prints(header())
.expect_prints([
"",
" Top-level help topics:",
"",
" >> Interpreter",
" >> Language reference",
" >> Testing",
"",
" Type HELP followed by the name of a topic for details.",
" Type HELP HELP for details on how to specify topic names.",
"",
])
.check();
}
#[test]
fn test_help_describe_callables_topic() {
tester()
.add_command(DoNothingCommand::new())
.add_function(EmptyFunction::new())
.run("help testing")
.expect_prints([
"",
" Testing",
"",
" This is a sample category for testing.",
"",
" >> DO_NOTHING This is the blurb.",
" >> EMPTY$ This is the blurb.",
"",
" Type HELP followed by the name of a symbol for details.",
"",
])
.check();
}
#[test]
fn test_help_describe_command() {
tester()
.add_command(DoNothingCommand::new())
.run("help Do_Nothing")
.expect_prints([
"",
" DO_NOTHING this [would] <be|the> syntax \"specification\"",
"",
" This is the blurb.",
"",
" First paragraph of the extended description.",
"",
" Second paragraph of the extended description.",
"",
])
.check();
}
fn do_help_describe_function_test(name: &str) {
tester()
.add_function(EmptyFunction::new())
.run(format!("help {}", name))
.expect_prints([
"",
" EMPTY$(this [would] <be|the> syntax \"specification\")",
"",
" This is the blurb.",
"",
" First paragraph of the extended description.",
"",
" Second paragraph of the extended description.",
"",
])
.check();
}
#[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() {
for cmd in &["help lang", "help language", r#"help "Language Reference""#] {
tester()
.run(*cmd)
.expect_prints(LANG_REFERENCE.lines().collect::<Vec<&str>>())
.expect_prints([""])
.check();
}
}
#[test]
fn test_help_prefix_search() {
fn exp_output(name: &str) -> Vec<String> {
vec![
"".to_owned(),
format!(" {}$(this [would] <be|the> syntax \"specification\")", name),
"".to_owned(),
" This is the blurb.".to_owned(),
"".to_owned(),
" First paragraph of the extended description.".to_owned(),
"".to_owned(),
" Second paragraph of the extended description.".to_owned(),
"".to_owned(),
]
}
for cmd in &["help aa", "help aab", "help aabc"] {
tester()
.add_function(EmptyFunction::new_with_name("AABC"))
.add_function(EmptyFunction::new_with_name("ABC"))
.add_function(EmptyFunction::new_with_name("BC"))
.run(*cmd)
.expect_prints(exp_output("AABC"))
.check();
}
for cmd in &["help b", "help bc"] {
tester()
.add_function(EmptyFunction::new_with_name("AABC"))
.add_function(EmptyFunction::new_with_name("ABC"))
.add_function(EmptyFunction::new_with_name("BC"))
.run(*cmd)
.expect_prints(exp_output("BC"))
.check();
}
tester()
.add_function(EmptyFunction::new_with_name("ABC"))
.add_function(EmptyFunction::new_with_name("AABC"))
.run("help a")
.expect_err("Ambiguous help topic a; candidates are: AABC$, ABC$")
.check();
}
#[test]
fn test_help_errors() {
let mut t =
tester().add_command(DoNothingCommand::new()).add_function(EmptyFunction::new());
t.run("HELP foo bar").expect_err("Unexpected value in expression").check();
t.run("HELP foo, bar").expect_err("HELP takes zero or only one argument").check();
t.run("HELP lang%").expect_err("Unknown help topic lang%").check();
t.run("HELP foo$").expect_err("Unknown help topic foo$").check();
t.run("HELP foo").expect_err("Unknown help topic foo").check();
t.run("HELP do_nothing$").expect_err("Unknown help topic do_nothing$").check();
t.run("HELP empty?").expect_err("Unknown help topic empty?").check();
let mut t = tester();
t.run("HELP undoc").expect_err("Unknown help topic undoc").check();
t.run("undoc = 3: HELP undoc")
.expect_err("Unknown help topic undoc")
.expect_var("undoc", 3)
.check();
let mut t = tester();
t.run("HELP undoc").expect_err("Unknown help topic undoc").check();
t.run("DIM undoc(3): HELP undoc")
.expect_err("Unknown help topic undoc")
.expect_array("undoc", VarType::Integer, &[3], vec![])
.check();
}
}