doge-interp 0.3.1

Tree-walking interpreter for the Doge programming language (powers `doge repl`).
Documentation
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
//! Calls in every form Doge has: direct function calls, calls through a function
//! value, method dispatch, constructors, module-member calls, and `super`. Each
//! resolves its target, evaluates arguments, binds them to the callee's header
//! (defaults, keyword arguments, and the `many` variadic), and runs the body.

use doge_compiler as dc;
use doge_runtime::{
    builtin_method, callee_function, enter_call, exit_call, function_arity_error, object_class_id,
    DogeError, DogeResult, ErrorKind, Value,
};

use crate::natives::call_native;
use crate::{cell, scope, Callable, Flow, Interp, Scope, Template};

/// A call's evaluated arguments: positional values, then `(name, value)` keyword
/// pairs in source order.
type EvaluatedArgs = (Vec<Value>, Vec<(String, Value)>);

impl Interp {
    /// Evaluate a call expression, resolving the callee the same way the compiler
    /// does: a known function/constructor/module member statically, anything else
    /// through the value it evaluates to.
    pub(crate) fn eval_call(
        &mut self,
        callee: &dc::Expr,
        args: &[dc::Expr],
        kwargs: &[(String, dc::Expr)],
        frame: &Scope,
        fid: u32,
    ) -> DogeResult<Value> {
        match callee {
            dc::Expr::Ident { name, .. } => {
                // A bound name (local, or a top-level function/variable held as a
                // value) is called through its value.
                if let Some(cell) = self.lookup(frame, fid, name) {
                    let value = cell.borrow().clone();
                    let (args, kwargs) = self.eval_args(args, kwargs, frame, fid)?;
                    return self.call_value(value, args, kwargs);
                }
                if let Some(id) = self.builtin_ids.get(name).copied() {
                    let args = self.eval_positional(args, frame, fid)?;
                    return self.call_id(id, Vec::new(), args, Vec::new(), name);
                }
                if let Some(class_id) = self.class_id_in(fid, name) {
                    let (args, kwargs) = self.eval_args(args, kwargs, frame, fid)?;
                    return self.construct(class_id, args, kwargs, name);
                }
                Err(DogeError::type_error(format!(
                    "cannot call {name} — it is not a function"
                )))
            }
            // `nerd.sqrt(...)` / `utils.square(...)` — a member call on a module.
            dc::Expr::Attr { obj, name, .. }
                if matches!(obj.as_ref(), dc::Expr::Ident { name: base, .. }
                    if self.lookup(frame, fid, base).is_none()
                        && self.import_ref(fid, base).is_some()) =>
            {
                let dc::Expr::Ident { name: base, .. } = obj.as_ref() else {
                    unreachable!("guarded to an Ident base")
                };
                let module = self
                    .import_ref(fid, base)
                    .expect("guarded: base is an import");
                self.call_module_member(module, base, name, args, kwargs, frame, fid)
            }
            // `kabosu.speak(...)` — a method call, dispatched on the receiver.
            dc::Expr::Attr { obj, name, .. } => {
                let recv = self.eval(obj, frame, fid)?;
                let args = self.eval_positional(args, frame, fid)?;
                self.call_method(recv, name, args)
            }
            // Any other callee expression is called through its value.
            other => {
                let value = self.eval(other, frame, fid)?;
                let (args, kwargs) = self.eval_args(args, kwargs, frame, fid)?;
                self.call_value(value, args, kwargs)
            }
        }
    }

    /// Call a top-level function of the entry file by name with no arguments,
    /// returning its value or the (catchable) error it raised. The test runner
    /// drives each discovered `test`-prefixed function through this, after
    /// [`Interp::prepare`](crate::Interp::prepare) has integrated the program.
    pub fn call_entry_function(&mut self, name: &str) -> DogeResult<Value> {
        let value = self
            .lookup(&self.globals(0), 0, name)
            .map(|cell| cell.borrow().clone())
            .ok_or_else(|| {
                DogeError::new(ErrorKind::ValueError, format!("no function named {name}"))
            })?;
        self.call_value(value, Vec::new(), Vec::new())
    }

    /// Evaluate positional arguments only.
    fn eval_positional(
        &mut self,
        args: &[dc::Expr],
        frame: &Scope,
        fid: u32,
    ) -> DogeResult<Vec<Value>> {
        let mut out = Vec::with_capacity(args.len());
        for arg in args {
            out.push(self.eval(arg, frame, fid)?);
        }
        Ok(out)
    }

    /// Evaluate positional then keyword arguments, left to right.
    fn eval_args(
        &mut self,
        args: &[dc::Expr],
        kwargs: &[(String, dc::Expr)],
        frame: &Scope,
        fid: u32,
    ) -> DogeResult<EvaluatedArgs> {
        let positional = self.eval_positional(args, frame, fid)?;
        let mut keyword = Vec::with_capacity(kwargs.len());
        for (name, value) in kwargs {
            keyword.push((name.clone(), self.eval(value, frame, fid)?));
        }
        Ok((positional, keyword))
    }

    /// Call a function value: unwrap it, then dispatch on its `fn_id`. Arity
    /// diagnostics name the function by its own definition name, not the call site.
    pub(crate) fn call_value(
        &mut self,
        value: Value,
        args: Vec<Value>,
        kwargs: Vec<(String, Value)>,
    ) -> DogeResult<Value> {
        // A bound method routes back through method dispatch, exactly as a direct
        // `a.speak(...)` would. Indirect calls carry no keyword arguments (the
        // checker rejects them), so the defensive guard here never fires in a
        // checked program.
        if let Value::BoundMethod(m) = &value {
            if !kwargs.is_empty() {
                return Err(DogeError::type_error(
                    "cannot call a bound method with keyword arguments",
                ));
            }
            let recv = m.receiver.clone();
            let method = m.method.clone();
            return self.call_method(recv, &method, args);
        }
        let func = callee_function(&value)?;
        self.call_id(
            func.fn_id as usize,
            func.captures.clone(),
            args,
            kwargs,
            &func.name,
        )
    }

    /// Dispatch a call to the callable at `fn_id`: a native, or a user function
    /// with its captured cells.
    fn call_id(
        &mut self,
        id: usize,
        captures: Vec<crate::Cell>,
        args: Vec<Value>,
        kwargs: Vec<(String, Value)>,
        label: &str,
    ) -> DogeResult<Value> {
        let callable = self.callables[id].clone();
        match callable.as_ref() {
            // `pack.zoom` is the one native that needs interpreter state: it spawns
            // a fresh interpreter over the same program on a new thread, so it is
            // dispatched here rather than through the stateless `call_native`.
            Callable::Native(native) if native.runtime_fn == dc::PACK_ZOOM_RUNTIME_FN => {
                self.interp_zoom(args)
            }
            Callable::Native(native) => call_native(native, args),
            Callable::User(template) => {
                self.call_user(template, &captures, args, kwargs, None, label)
            }
            // A class value called: build an instance through its constructor.
            Callable::Ctor(class_id) => self.construct(*class_id, args, kwargs, label),
        }
    }

    /// Run a user function/method/closure body: guard recursion, build its frame
    /// (captures, `self`, parameters, hoisted locals), execute, and return the
    /// value it `return`s (or `none` if it falls off the end).
    fn call_user(
        &mut self,
        template: &Template,
        captures: &[crate::Cell],
        args: Vec<Value>,
        kwargs: Vec<(String, Value)>,
        self_value: Option<Value>,
        label: &str,
    ) -> DogeResult<Value> {
        enter_call(&mut self.depth)?;
        let saved_class = self.current_method_class;
        self.current_method_class = template.method_class;
        let result = self.user_body(template, captures, args, kwargs, self_value, label);
        self.current_method_class = saved_class;
        exit_call(&mut self.depth);
        result
    }

    fn user_body(
        &mut self,
        template: &Template,
        captures: &[crate::Cell],
        args: Vec<Value>,
        kwargs: Vec<(String, Value)>,
        self_value: Option<Value>,
        label: &str,
    ) -> DogeResult<Value> {
        let bound = self.bind_args(&template.params, args, kwargs, label, template.file_id)?;

        let frame = scope();
        {
            let mut f = frame.borrow_mut();
            for (name, captured) in template.capture_names.iter().zip(captures) {
                f.insert(name.clone(), captured.clone());
            }
            if let Some(self_value) = self_value {
                f.insert("self".to_string(), cell(self_value));
            }
            for (name, value) in template.params.binding_names().iter().zip(bound) {
                f.insert(name.clone(), cell(value));
            }
        }
        // Hoist the body's remaining local names to `none`, like the compiler's
        // hoisted `Env` fields; nested-function values bind when their statement runs.
        for name in dc::hoisted_names(&template.body) {
            frame
                .borrow_mut()
                .entry(name)
                .or_insert_with(|| cell(Value::None));
        }

        match self.exec_stmts(&template.body, &frame, template.file_id)? {
            Flow::Return(value) => Ok(value),
            // Falling off the end (or a checked-away stray bork/continue) yields none.
            _ => Ok(Value::None),
        }
    }

    /// Map a call's positional and keyword arguments onto a header's slots — filling
    /// from positionals, then keywords, then defaults, and collecting any surplus
    /// into the `many` variadic — returning the values in binding order. The arity
    /// and keyword diagnostics match the compiler's wording.
    fn bind_args(
        &mut self,
        params: &dc::Params,
        args: Vec<Value>,
        kwargs: Vec<(String, Value)>,
        label: &str,
        fid: u32,
    ) -> DogeResult<Vec<Value>> {
        let n = params.params.len();
        let has_vararg = params.has_vararg();
        let required = params.required();
        let max = params.max_positional();
        let total = args.len() + kwargs.len();

        if !has_vararg && args.len() > n {
            return Err(function_arity_error(label, required, max, total));
        }

        let mut slot: Vec<Option<Value>> = vec![None; n];
        let mut extras: Vec<Value> = Vec::new();
        for (i, arg) in args.into_iter().enumerate() {
            if i < n {
                slot[i] = Some(arg);
            } else {
                extras.push(arg);
            }
        }
        for (name, value) in kwargs {
            match params.params.iter().position(|p| p.name == name) {
                Some(idx) if slot[idx].is_none() => slot[idx] = Some(value),
                Some(_) => {
                    return Err(DogeError::type_error(format!(
                        "{label} got parameter {name} twice"
                    )))
                }
                None => {
                    return Err(DogeError::type_error(format!(
                        "{label} has no parameter {name}"
                    )))
                }
            }
        }

        let mut out = Vec::with_capacity(n + has_vararg as usize);
        for (i, filled) in slot.into_iter().enumerate() {
            match filled {
                Some(value) => out.push(value),
                None => match &params.params[i].default {
                    Some(default) => out.push(self.eval(default, &scope(), fid)?),
                    None => return Err(function_arity_error(label, required, max, total)),
                },
            }
        }
        if has_vararg {
            out.push(Value::list(extras));
        }
        Ok(out)
    }

    /// Dispatch a method call: an object routes through its class's method table
    /// (walking its ancestry); any other receiver forwards to the runtime's
    /// collection methods, exactly like the compiled dispatcher.
    fn call_method(&mut self, recv: Value, name: &str, args: Vec<Value>) -> DogeResult<Value> {
        if !matches!(recv, Value::Object(_)) {
            return builtin_method(&recv, name, args);
        }
        let class_id = object_class_id(&recv)?;
        match self.resolve_method(class_id, name) {
            Some((fn_id, def_class)) => {
                let label = format!("{}.{name}", self.classes[def_class as usize].name);
                self.invoke_method(fn_id, recv, args, &label)
            }
            None => Err(doge_runtime::no_such_method(&recv, name)),
        }
    }

    /// Invoke a resolved method template with `recv` bound as `self`.
    fn invoke_method(
        &mut self,
        fn_id: usize,
        recv: Value,
        args: Vec<Value>,
        label: &str,
    ) -> DogeResult<Value> {
        let callable = self.callables[fn_id].clone();
        let Callable::User(template) = callable.as_ref() else {
            unreachable!("interp bug: a method id points at a native");
        };
        self.call_user(template, &[], args, Vec::new(), Some(recv), label)
    }

    /// `super.method(args)`: resolve `method` in the enclosing class's parent chain
    /// and call it with the current `self`.
    pub(crate) fn eval_super_call(
        &mut self,
        method: &str,
        args: &[dc::Expr],
        frame: &Scope,
        fid: u32,
    ) -> DogeResult<Value> {
        let class_id = self
            .current_method_class
            .expect("checker guarantees super is inside a method");
        let parent = self.classes[class_id as usize]
            .parent
            .expect("checker guarantees the class has a parent");
        let (fn_id, def_class) = self
            .resolve_method(parent, method)
            .expect("checker guarantees a parent defines the method");
        let self_value = self
            .lookup(frame, fid, "self")
            .expect("a method frame always binds self")
            .borrow()
            .clone();
        let args = self.eval_positional(args, frame, fid)?;
        let label = format!("{}.{method}", self.classes[def_class as usize].name);
        self.invoke_method(fn_id, self_value, args, &label)
    }

    /// The method named `name` callable on `class_id`: the nearest definition up
    /// its ancestry, returning its `fn_id` and the class that defines it.
    pub(crate) fn resolve_method(&self, class_id: u32, name: &str) -> Option<(usize, u32)> {
        let mut current = Some(class_id);
        let mut guard = 0;
        while let Some(cid) = current {
            let class = &self.classes[cid as usize];
            if let Some(fn_id) = class.methods.get(name) {
                return Some((*fn_id, cid));
            }
            guard += 1;
            if guard > self.classes.len() {
                break;
            }
            current = class.parent;
        }
        None
    }

    /// Construct an instance of `class_id`: build the object, then run its
    /// effective `init` (its own or the nearest inherited one) with `self` bound.
    fn construct(
        &mut self,
        class_id: u32,
        args: Vec<Value>,
        kwargs: Vec<(String, Value)>,
        label: &str,
    ) -> DogeResult<Value> {
        let class = self.classes[class_id as usize].clone();
        let object = Value::object(class_id, &class.name);
        match self.resolve_method(class_id, "init") {
            Some((fn_id, _)) => {
                self.invoke_method_kw(fn_id, object.clone(), args, kwargs, label)?;
            }
            None => {
                // No init anywhere in the chain: construction takes no arguments.
                self.bind_args(&dc::Params::default(), args, kwargs, label, class.file_id)?;
            }
        }
        Ok(object)
    }

    /// Invoke a method template that accepts keyword arguments (a constructor's
    /// `init`), binding `recv` as `self`.
    fn invoke_method_kw(
        &mut self,
        fn_id: usize,
        recv: Value,
        args: Vec<Value>,
        kwargs: Vec<(String, Value)>,
        label: &str,
    ) -> DogeResult<Value> {
        let callable = self.callables[fn_id].clone();
        let Callable::User(template) = callable.as_ref() else {
            unreachable!("interp bug: a method id points at a native");
        };
        self.call_user(template, &[], args, kwargs, Some(recv), label)
    }

    /// A call to a module member: a stdlib function, or a user module's function or
    /// constructor.
    #[allow(clippy::too_many_arguments)]
    fn call_module_member(
        &mut self,
        module: crate::ModuleRef,
        base: &str,
        member: &str,
        args: &[dc::Expr],
        kwargs: &[(String, dc::Expr)],
        frame: &Scope,
        fid: u32,
    ) -> DogeResult<Value> {
        match module {
            crate::ModuleRef::Stdlib(m) => {
                let args = self.eval_positional(args, frame, fid)?;
                match self
                    .module_fn_ids
                    .get(&(m.name.to_string(), member.to_string()))
                {
                    Some(id) => self.call_id(*id, Vec::new(), args, Vec::new(), member),
                    None => Err(DogeError::attr_error(format!(
                        "{base} has no member {member}"
                    ))),
                }
            }
            crate::ModuleRef::User(mfid) => {
                let (args, kwargs) = self.eval_args(args, kwargs, frame, fid)?;
                if let Some(class_id) = self.class_id_in(mfid, member) {
                    let label = format!("{base}.{member}");
                    return self.construct(class_id, args, kwargs, &label);
                }
                let value = self
                    .lookup(&self.globals(mfid), mfid, member)
                    .map(|c| c.borrow().clone())
                    .ok_or_else(|| {
                        DogeError::attr_error(format!("{base} has no member {member}"))
                    })?;
                self.call_value(value, args, kwargs)
            }
        }
    }
}