1
//! `APROPOS` — search the symbol table for names containing a
2
//! substring (case-insensitive), return a sorted quoted list of
3
//! matching symbols. Powers `nomisync-help` completion in emacs and
4
//! the REPL's tab-completion.
5

            
6
use crate::ast::{Expr, WasmType};
7
use crate::compiler::context::CompileContext;
8
use crate::compiler::emit::FunctionEmitter;
9
use crate::compiler::expr::{compile_expr, format_expr};
10
use crate::error::{Error, Result};
11
use crate::runtime::SymbolTable;
12

            
13
use super::compile_static_result_for_stack;
14
use super::folded::folded_form;
15

            
16
1730
fn folded_needle(symbols: &mut SymbolTable, arg: &Expr) -> Result<String> {
17
1730
    match folded_form(symbols, "APROPOS", arg)? {
18
1297
        Expr::String(s) => Ok(s),
19
215
        Expr::Symbol(s) | Expr::Keyword(s) => Ok(s.trim_start_matches(':').to_string()),
20
6
        Expr::Nil => Ok("NIL".to_string()),
21
209
        other => Err(Error::Compile(format!(
22
209
            "APROPOS: argument must be a string or symbol, got {}",
23
209
            format_expr(&other)
24
209
        ))),
25
    }
26
1730
}
27

            
28
1938
pub(super) fn apropos(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
29
1938
    if args.len() != 1 {
30
208
        return Err(Error::Arity {
31
208
            name: "APROPOS".to_string(),
32
208
            expected: 1,
33
208
            actual: args.len(),
34
208
        });
35
1730
    }
36
1730
    let needle = folded_needle(symbols, &args[0])?;
37
1518
    let needle_uc = needle.to_uppercase();
38
1518
    let mut matches: Vec<String> = symbols
39
1518
        .iter()
40
306156
        .filter(|(name, _)| name.to_uppercase().contains(&needle_uc))
41
11295
        .map(|(name, _)| name.clone())
42
        .collect();
43
1518
    matches.sort();
44
1518
    let elems = matches.into_iter().map(Expr::Symbol).collect();
45
1518
    Ok(Expr::quoted_list(elems))
46
1938
}
47

            
48
1258
pub(super) fn compile_apropos(
49
1258
    ctx: &mut CompileContext,
50
1258
    emit: &mut FunctionEmitter,
51
1258
    symbols: &mut SymbolTable,
52
1258
    args: &[Expr],
53
1258
) -> Result<()> {
54
1258
    let result = apropos(symbols, args)?;
55
840
    compile_expr(ctx, emit, symbols, &result)
56
1258
}
57

            
58
658
pub(super) fn compile_apropos_for_stack(
59
658
    ctx: &mut CompileContext,
60
658
    emit: &mut FunctionEmitter,
61
658
    symbols: &mut SymbolTable,
62
658
    args: &[Expr],
63
658
) -> Result<WasmType> {
64
658
    let result = apropos(symbols, args)?;
65
658
    compile_static_result_for_stack(ctx, emit, symbols, &result)
66
658
}