Skip to main content

doge_runtime/methods/
mod.rs

1//! Built-in method dispatch for collection values — the counterpart of
2//! [`crate::objects`] for `many` instances. A method call on a non-`Object`
3//! receiver (`xs.append(1)`, `d.keys()`) routes here; the generated `call_method`
4//! dispatcher handles `Object` receivers itself and forwards everything else.
5//!
6//! Behaviour lives here, not in codegen (generated Rust is thin glue): each
7//! method mutates or reads the value's shared cell and returns a `Value`, and
8//! every failure is a catchable [`DogeError`], never a panic.
9
10use std::rc::Rc;
11
12use bigdecimal::ToPrimitive;
13
14use crate::error::{DogeError, DogeResult};
15use crate::objects::method_arity_error;
16use crate::value::Value;
17
18mod bytes;
19mod dict;
20mod list;
21#[cfg(test)]
22mod tests;
23
24use bytes::bytes_method;
25use dict::dict_method;
26use list::list_method;
27
28/// Dispatch a method call on a List or Dict. `recv` is the receiver, `name` the
29/// method, `args` the already-evaluated arguments. A non-collection receiver, an
30/// unknown method, or a wrong argument count is a catchable error.
31pub fn builtin_method(recv: &Value, name: &str, args: Vec<Value>) -> DogeResult {
32    match recv {
33        Value::List(_) => list_method(recv, name, args),
34        Value::Dict(_) => dict_method(recv, name, args),
35        Value::Bytes(_) => bytes_method(recv, name, args),
36        // The dispatcher routes objects to its own class match, never here; this
37        // defensive branch names the class rather than claiming "no methods".
38        Value::Object(_) => Err(crate::objects::no_such_method(recv, name)),
39        // No other value has methods at all. Listed by variant rather than a
40        // wildcard, so a new Value variant with methods forces a decision here.
41        Value::Int(_)
42        | Value::Float(_)
43        | Value::Decimal(_)
44        | Value::Str(_)
45        | Value::Bool(_)
46        | Value::None
47        | Value::Function(_)
48        | Value::Class(_)
49        | Value::BoundMethod(_)
50        | Value::Error(_)
51        | Value::Socket(_)
52        | Value::Pup(_)
53        | Value::Bowl(_) => Err(crate::objects::no_methods_error(recv)),
54    }
55}
56
57/// Whether a List or Dict has a built-in method named `name` — the gate a bound
58/// method read (`such f = xs.append`) checks before capturing the receiver. The
59/// method-name sets live beside each collection's dispatch (`list::LIST_METHODS`,
60/// `dict::DICT_METHODS`), so binding and dispatch never disagree.
61pub fn has_builtin_method(recv: &Value, name: &str) -> bool {
62    match recv {
63        Value::List(_) => list::LIST_METHODS.contains(&name),
64        Value::Dict(_) => dict::DICT_METHODS.contains(&name),
65        Value::Bytes(_) => bytes::BYTES_METHODS.contains(&name),
66        _ => false,
67    }
68}
69
70/// The arity gate every method runs first: reuses the object-method wording so a
71/// List/Dict arity error reads exactly like `Shibe.speak takes 1 argument, got 0`.
72pub(super) fn check_arity(
73    class: &str,
74    method: &str,
75    expected: usize,
76    got: usize,
77) -> DogeResult<()> {
78    if got == expected {
79        Ok(())
80    } else {
81        Err(method_arity_error(
82            class,
83            method,
84            expected,
85            Some(expected),
86            got,
87        ))
88    }
89}
90
91/// Take an argument that must be an Int, or raise the standard type error naming
92/// the method and what it got. `what` is the argument's role, e.g. `List.insert
93/// needs an Int index`.
94pub(super) fn expect_int(value: Value, what: &str) -> DogeResult<i64> {
95    match value {
96        // The argument is a machine index/count; a value past the i64 range can
97        // never be a valid one, so it is a catchable error rather than a panic.
98        Value::Int(n) => n
99            .to_i64()
100            .ok_or_else(|| DogeError::value_error(format!("{what}, but {n} is too large"))),
101        other => Err(DogeError::type_error(format!(
102            "{what}, got {}",
103            other.describe()
104        ))),
105    }
106}
107
108/// Take an argument that must be a Str, or raise the standard type error naming
109/// the method and what it got.
110pub(super) fn expect_str(value: Value, what: &str) -> DogeResult<Rc<str>> {
111    match value {
112        Value::Str(s) => Ok(s),
113        other => Err(DogeError::type_error(format!(
114            "{what}, got {}",
115            other.describe()
116        ))),
117    }
118}