1
//! Argument parsing for `BLOCK` and `RETURN-FROM`.
2

            
3
use crate::ast::Expr;
4
use crate::compiler::expr::format_form;
5
use crate::error::{Error, Result};
6

            
7
const BLOCK: &str = "block";
8
const RETURN_FROM: &str = "return-from";
9
pub(in crate::compiler::special) const NIL_LABEL: &str = "NIL";
10

            
11
/// The block name `expr` spells: a symbol, or `nil`, the label of every
12
/// loop's implicit block.
13
699490
pub(in crate::compiler::special) fn label(expr: &Expr) -> Option<&str> {
14
699490
    match expr {
15
679636
        Expr::Symbol(name) => Some(name),
16
19848
        Expr::Nil => Some(NIL_LABEL),
17
6
        _ => None,
18
    }
19
699490
}
20

            
21
113678
pub(super) fn parse_block(args: &[Expr]) -> Result<(&str, &[Expr])> {
22
113678
    if args.is_empty() {
23
1
        return Err(Error::Arity {
24
1
            name: BLOCK.to_string(),
25
1
            expected: 1,
26
1
            actual: 0,
27
1
        });
28
113677
    }
29
113677
    let Some(name) = label(&args[0]) else {
30
3
        return Err(Error::Type {
31
3
            expected: "symbol for BLOCK label".to_string(),
32
3
            actual: format_form(&args[0]),
33
3
        });
34
    };
35
113674
    Ok((name, &args[1..]))
36
113678
}
37

            
38
267937
pub(super) fn parse_return_from(args: &[Expr]) -> Result<(&str, &Expr)> {
39
267937
    if !(1..=2).contains(&args.len()) {
40
1
        return Err(Error::Arity {
41
1
            name: RETURN_FROM.to_string(),
42
1
            expected: 2,
43
1
            actual: args.len(),
44
1
        });
45
267936
    }
46
267936
    let Some(name) = label(&args[0]) else {
47
3
        return Err(Error::Type {
48
3
            expected: "symbol for RETURN-FROM target".to_string(),
49
3
            actual: format_form(&args[0]),
50
3
        });
51
    };
52
267933
    Ok((name, args.get(1).unwrap_or(&Expr::Nil)))
53
267937
}