neovm-core 0.0.1

Core runtime structures for NeoVM
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
//! Autoload and deferred after-load support.
//!
//! Provides:
//! - **Autoload system**: Deferred function loading — register a function as
//!   autoloaded so that its file is loaded on first use.
//! - **with-eval-after-load**: Deferred form execution after a file loads.
//! - **Obsolete aliases**: `define-obsolete-function-alias`,
//!   `define-obsolete-variable-alias`, `make-obsolete`, `make-obsolete-variable`.

use std::collections::HashMap;
use std::path::PathBuf;

use super::error::{EvalResult, Flow, signal};
use super::intern::{intern, resolve_sym};
use super::symbol::Obarray;
use super::value::*;
use crate::emacs_core::value::ValueKind;
use crate::gc_trace::GcTrace;

// ---------------------------------------------------------------------------
// Autoload types
// ---------------------------------------------------------------------------

/// The kind of definition an autoload stands for.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AutoloadType {
    /// Normal function (default).
    Function,
    /// Macro.
    Macro,
    /// Keymap.
    Keymap,
}

impl AutoloadType {
    /// Parse a Value into an AutoloadType.
    pub fn from_value(val: &Value) -> Self {
        if val.is_t() {
            return Self::Macro;
        }
        match val.as_symbol_name() {
            Some("macro") => Self::Macro,
            Some("keymap") => Self::Keymap,
            _ => Self::Function,
        }
    }

    /// Convert back to a symbol Value.
    pub fn to_value(&self) -> Value {
        match self {
            Self::Function => Value::NIL,
            Self::Macro => Value::symbol("macro"),
            Self::Keymap => Value::symbol("keymap"),
        }
    }
}

/// An entry in the autoload table.
#[derive(Clone, Debug)]
pub struct AutoloadEntry {
    /// The function name that is autoloaded.
    pub name: String,
    /// The file to load when the function is first called.
    pub file: String,
    /// Optional documentation string.
    pub docstring: Option<String>,
    /// Whether the function is interactive (a command).
    pub interactive: bool,
    /// The type of definition (function, macro, keymap).
    pub autoload_type: AutoloadType,
}

// ---------------------------------------------------------------------------
// AutoloadManager
// ---------------------------------------------------------------------------

/// Central registry of autoloaded functions and eval-after-load callbacks.
pub struct AutoloadManager {
    /// Map from function name to autoload entry.
    entries: HashMap<String, AutoloadEntry>,
    /// Map from file/feature name to list of forms to evaluate after loading.
    after_load: HashMap<String, Vec<Value>>,
    /// Set of files that have already been loaded (for after-load tracking).
    loaded_files: Vec<String>,
    /// Obsolete function warnings: old-name -> (new-name, when).
    obsolete_functions: HashMap<String, (String, String)>,
    /// Obsolete variable warnings: old-name -> (new-name, when).
    obsolete_variables: HashMap<String, (String, String)>,
}

impl Default for AutoloadManager {
    fn default() -> Self {
        Self::new()
    }
}

impl AutoloadManager {
    pub fn new() -> Self {
        Self {
            entries: HashMap::new(),
            after_load: HashMap::new(),
            loaded_files: Vec::new(),
            obsolete_functions: HashMap::new(),
            obsolete_variables: HashMap::new(),
        }
    }

    /// Register an autoload entry.
    pub fn register(&mut self, entry: AutoloadEntry) {
        self.entries.insert(entry.name.clone(), entry);
    }

    /// Check whether a function name has an autoload entry.
    pub fn is_autoloaded(&self, name: &str) -> bool {
        self.entries.contains_key(name)
    }

    /// Get the autoload entry for a function name.
    pub fn get_entry(&self, name: &str) -> Option<&AutoloadEntry> {
        self.entries.get(name)
    }

    /// Snapshot current autoload entries for callers that need to rebuild
    /// function cells from the registered autoload metadata.
    pub fn entries_snapshot(&self) -> Vec<AutoloadEntry> {
        self.entries.values().cloned().collect()
    }

    /// Remove an autoload entry (used after the file has been loaded and the
    /// real definition is in place).
    pub fn remove(&mut self, name: &str) {
        self.entries.remove(name);
    }

    /// Register a form to evaluate after a given file/feature is loaded.
    pub fn add_after_load(&mut self, file: &str, form: Value) {
        self.after_load
            .entry(file.to_string())
            .or_default()
            .push(form);
    }

    /// Get the after-load forms for a file (if any).
    pub fn take_after_load_forms(&mut self, file: &str) -> Vec<Value> {
        self.after_load.remove(file).unwrap_or_default()
    }

    /// Record that a file has been loaded.
    pub fn mark_loaded(&mut self, file: &str) {
        if !self.loaded_files.contains(&file.to_string()) {
            self.loaded_files.push(file.to_string());
        }
    }

    /// Check if a file has already been loaded.
    pub fn is_loaded(&self, file: &str) -> bool {
        self.loaded_files.contains(&file.to_string())
    }

    /// Mark a function as obsolete.
    pub fn make_obsolete(&mut self, old_name: &str, new_name: &str, when: &str) {
        self.obsolete_functions.insert(
            old_name.to_string(),
            (new_name.to_string(), when.to_string()),
        );
    }

    /// Check if a function is marked obsolete.
    pub fn is_function_obsolete(&self, name: &str) -> bool {
        self.obsolete_functions.contains_key(name)
    }

    /// Get obsolete function info: (new-name, when).
    pub fn get_obsolete_function(&self, name: &str) -> Option<&(String, String)> {
        self.obsolete_functions.get(name)
    }

    /// Mark a variable as obsolete.
    pub fn make_variable_obsolete(&mut self, old_name: &str, new_name: &str, when: &str) {
        self.obsolete_variables.insert(
            old_name.to_string(),
            (new_name.to_string(), when.to_string()),
        );
    }

    /// Check if a variable is marked obsolete.
    pub fn is_variable_obsolete(&self, name: &str) -> bool {
        self.obsolete_variables.contains_key(name)
    }

    /// Get obsolete variable info: (new-name, when).
    pub fn get_obsolete_variable(&self, name: &str) -> Option<&(String, String)> {
        self.obsolete_variables.get(name)
    }

    // pdump accessors
    pub(crate) fn dump_entries(&self) -> &HashMap<String, AutoloadEntry> {
        &self.entries
    }
    pub(crate) fn dump_after_load(&self) -> &HashMap<String, Vec<Value>> {
        &self.after_load
    }
    pub(crate) fn dump_loaded_files(&self) -> &[String] {
        &self.loaded_files
    }
    pub(crate) fn dump_obsolete_functions(&self) -> &HashMap<String, (String, String)> {
        &self.obsolete_functions
    }
    pub(crate) fn dump_obsolete_variables(&self) -> &HashMap<String, (String, String)> {
        &self.obsolete_variables
    }
    pub(crate) fn from_dump(
        entries: HashMap<String, AutoloadEntry>,
        after_load: HashMap<String, Vec<Value>>,
        loaded_files: Vec<String>,
        obsolete_functions: HashMap<String, (String, String)>,
        obsolete_variables: HashMap<String, (String, String)>,
    ) -> Self {
        Self {
            entries,
            after_load,
            loaded_files,
            obsolete_functions,
            obsolete_variables,
        }
    }
}

// ---------------------------------------------------------------------------
// Builtins (pure — need evaluator access)
// ---------------------------------------------------------------------------

/// Check whether a value is an autoload form (autoload FILE ...).
pub(crate) fn is_autoload_value(val: &Value) -> bool {
    if let Some(items) = list_to_vec(val) {
        if let Some(first) = items.first() {
            if let Some(name) = first.as_symbol_name() {
                return name == "autoload";
            }
        }
    }
    false
}

/// `(autoload-do-load FUNDEF &optional FUNNAME MACRO-ONLY)` — trigger autoload.
/// If FUNDEF is an autoload form, load the file and return the new definition.
/// Otherwise return FUNDEF unchanged.
pub(crate) enum AutoloadDoLoadPlan {
    Return(Value),
    Load {
        file: String,
        funname: Option<String>,
    },
}

pub(crate) fn plan_autoload_do_load_in_state(
    obarray: &Obarray,
    args: &[Value],
) -> Result<AutoloadDoLoadPlan, Flow> {
    if args.is_empty() || args.len() > 3 {
        return Err(signal(
            "wrong-number-of-arguments",
            vec![
                Value::symbol("autoload-do-load"),
                Value::fixnum(args.len() as i64),
            ],
        ));
    }

    let fundef = &args[0];
    if !is_autoload_value(fundef) {
        return Ok(AutoloadDoLoadPlan::Return(*fundef));
    }

    let items = list_to_vec(fundef).unwrap_or_default();
    // items[0] = 'autoload, items[1] = file, ...
    let file = if items.len() > 1 {
        match items[1].kind() {
            ValueKind::String => items[1].as_str().unwrap().to_owned(),
            _ => return Ok(AutoloadDoLoadPlan::Return(*fundef)),
        }
    } else {
        return Ok(AutoloadDoLoadPlan::Return(*fundef));
    };

    let funname = if args.len() > 1 {
        args[1].as_symbol_name().map(|s| s.to_string())
    } else {
        None
    };

    // MACRO-ONLY check: if the third arg is non-nil, only autoload if the
    // autoload's TYPE field (5th element) is `t` or `macro`.
    // This matches GNU Emacs eval.c:Fautoload_do_load.
    let macro_only = args.get(2).copied().unwrap_or(Value::NIL);
    if !macro_only.is_nil() {
        let kind = items.get(4).copied().unwrap_or(Value::NIL);
        let is_macro_type = kind.is_t() || kind.as_symbol_name().map_or(false, |s| s == "macro");
        if !is_macro_type {
            return Ok(AutoloadDoLoadPlan::Return(*fundef));
        }
    }

    // Before loading, check if the function cell has already been resolved
    // (i.e., a previous load of the same file already defined this function).
    // This prevents redundant re-loads that can cause side effects like
    // advice being installed multiple times.
    if let Some(ref name) = funname {
        if let Some(current) = obarray.symbol_function(name).cloned() {
            if !is_autoload_value(&current) {
                // The function is already defined (not an autoload) — a previous
                // load already resolved it. Return the current definition.
                return Ok(AutoloadDoLoadPlan::Return(current));
            }
        }
        if let Some(override_value) =
            super::eval::compiler_function_override_in_obarray(obarray, intern(name))
        {
            return Ok(AutoloadDoLoadPlan::Return(override_value));
        }
    }

    Ok(AutoloadDoLoadPlan::Load { file, funname })
}

pub(crate) fn resolve_autoload_load_path(obarray: &Obarray, file: &str) -> Result<PathBuf, Flow> {
    let load_path = super::load::get_load_path(obarray);
    match super::load::find_file_in_load_path(file, &load_path) {
        Some(path) => Ok(path),
        None => Err(signal(
            "file-missing",
            vec![Value::string(format!(
                "Cannot open load file: no such file or directory, {}",
                file
            ))],
        )),
    }
}

/// After loading an autoload file, check whether the function was defined.
/// Matches GNU Emacs eval.c:Fautoload_do_load lines 2501-2508: if the
/// function cell is still the same autoload, signal an error.
pub(crate) fn finish_autoload_do_load_in_state(
    obarray: &Obarray,
    funname: Option<&str>,
    original_autoload: Option<&Value>,
) -> EvalResult {
    if let Some(name) = funname {
        if let Some(func) = obarray.symbol_function(name).cloned() {
            // GNU Emacs: if function is still the same autoload form after
            // loading, signal "Autoloading file failed to define function".
            // GNU Emacs eval.c: if (!NILP (Fequal (fun, fundef)))
            // Only error if the function cell is STILL the SAME autoload
            // form (by identity, not by content, to avoid stale reference).
            // A different autoload (re-registered by eval-after-load
            // callbacks) is fine — the function was redefined.
            if let Some(orig) = original_autoload {
                let same_identity = match (func.kind(), orig.kind()) {
                    (ValueKind::Cons, ValueKind::Cons) => func.bits() == orig.bits(),
                    _ => false,
                };
                if same_identity {
                    return Err(signal(
                        "error",
                        vec![Value::string(format!(
                            "Autoloading failed to define function {}",
                            name
                        ))],
                    ));
                }
            }
            return Ok(func);
        }
    }
    Ok(Value::NIL)
}

pub(crate) fn builtin_autoload_do_load(
    eval: &mut super::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    let original_fundef = args.first().copied();
    match plan_autoload_do_load_in_state(&eval.obarray, &args)? {
        AutoloadDoLoadPlan::Return(value) => Ok(value),
        AutoloadDoLoadPlan::Load { file, funname } => {
            let path = resolve_autoload_load_path(&eval.obarray, &file)?;
            eval.load_file_internal(&path)?;
            finish_autoload_do_load_in_state(
                &eval.obarray,
                funname.as_deref(),
                original_fundef.as_ref(),
            )
        }
    }
}

pub(crate) fn builtin_autoload_do_load_in_vm_runtime(
    shared: &mut super::eval::Context,
    vm_gc_roots: &[Value],
    args: &[Value],
    extra_roots: &[Value],
) -> EvalResult {
    let original_fundef = args.first().copied();
    match plan_autoload_do_load_in_state(&shared.obarray, args)? {
        AutoloadDoLoadPlan::Return(value) => Ok(value),
        AutoloadDoLoadPlan::Load { file, funname } => {
            let path = resolve_autoload_load_path(&shared.obarray, &file)?;
            shared.with_extra_gc_roots(vm_gc_roots, extra_roots, move |eval| {
                eval.load_file_internal(&path)
            })?;
            finish_autoload_do_load_in_state(
                &shared.obarray,
                funname.as_deref(),
                original_fundef.as_ref(),
            )
        }
    }
}

pub(crate) fn register_autoload_in_state(
    obarray: &mut Obarray,
    autoloads: &mut AutoloadManager,
    args: &[Value],
) -> EvalResult {
    if args.len() < 2 || args.len() > 5 {
        return Err(signal(
            "wrong-number-of-arguments",
            vec![Value::symbol("autoload"), Value::fixnum(args.len() as i64)],
        ));
    }

    let func_val = args[0];
    let name = match func_val.kind() {
        ValueKind::Symbol(id) => resolve_sym(id).to_owned(),
        _ => {
            return Err(signal(
                "wrong-type-argument",
                vec![Value::symbol("symbolp"), func_val],
            ));
        }
    };

    // GNU Emacs eval.c:Fautoload — "If function is defined and not as an
    // autoload, don't override."  If the symbol already has a real (non-
    // autoload) function definition, return nil without touching it.
    if let Some(current) = obarray.symbol_function(&name).cloned() {
        if !current.is_nil() && !is_autoload_value(&current) {
            return Ok(Value::NIL);
        }
    }

    let file_val = args[1];
    let file = match file_val.kind() {
        ValueKind::String => file_val.as_str().unwrap().to_owned(),
        _ => {
            return Err(signal(
                "wrong-type-argument",
                vec![Value::symbol("stringp"), file_val],
            ));
        }
    };

    let docstring_val = args.get(2).cloned().unwrap_or(Value::NIL);
    let docstring = match docstring_val.kind() {
        ValueKind::String => Some(docstring_val.as_str().unwrap().to_owned()),
        _ => None,
    };

    let interactive_val = args.get(3).cloned().unwrap_or(Value::NIL);
    let interactive = !interactive_val.is_nil();

    let type_val = args.get(4).cloned().unwrap_or(Value::NIL);
    let autoload_type = AutoloadType::from_value(&type_val);

    let autoload_form = Value::list(vec![
        Value::symbol("autoload"),
        Value::string(file.clone()),
        docstring_val,
        interactive_val,
        type_val,
    ]);

    obarray.set_symbol_function(&name, autoload_form);
    autoloads.register(AutoloadEntry {
        name: name.clone(),
        file,
        docstring,
        interactive,
        autoload_type,
    });

    Ok(Value::symbol(&name))
}

/// `(autoload FUNCTION FILE &optional DOCSTRING INTERACTIVE TYPE)`
///
/// Callable builtin form used by `funcall`/`apply` and direct function calls.
/// Arguments are already evaluated.
pub(crate) fn builtin_autoload(eval: &mut super::eval::Context, args: Vec<Value>) -> EvalResult {
    register_autoload_in_state(&mut eval.obarray, &mut eval.autoloads, &args)
}

/// Context-aware `(symbol-file SYMBOL &optional TYPE)`.
///
/// NeoVM currently tracks symbol origin only for autoloaded function symbols.
/// This matches GNU Emacs behavior for the currently supported subset:
/// - non-symbol SYMBOL returns nil
/// - TYPE nil/missing/`defun` queries function definition origin
/// - other TYPE values return nil
pub(crate) fn builtin_symbol_file(eval: &mut super::eval::Context, args: Vec<Value>) -> EvalResult {
    if args.is_empty() || args.len() > 3 {
        return Err(signal(
            "wrong-number-of-arguments",
            vec![
                Value::symbol("symbol-file"),
                Value::fixnum(args.len() as i64),
            ],
        ));
    }

    let symbol_name = match args[0].as_symbol_name() {
        Some(name) => name,
        None => return Ok(Value::NIL),
    };

    let function_origin_requested = if args.len() == 1 || args[1].is_nil() {
        true
    } else {
        matches!(args[1].as_symbol_name(), Some("defun"))
    };
    if !function_origin_requested {
        return Ok(Value::NIL);
    }

    if let Some(entry) = eval.autoloads.get_entry(symbol_name) {
        return Ok(Value::string(entry.file.clone()));
    }

    if let Some(fndef) = eval.obarray.symbol_function(symbol_name).cloned() {
        if is_autoload_value(&fndef) {
            if let Some(items) = list_to_vec(&fndef) {
                if let Some(v) = items.get(1) {
                    if v.is_string() {
                        return Ok(Value::string(v.as_str().unwrap().to_owned()));
                    }
                }
            }
        }
    }

    Ok(Value::NIL)
}

// ---------------------------------------------------------------------------
// Special form handlers (called from eval.rs try_special_form dispatch)
// ---------------------------------------------------------------------------

/// `(autoload FUNCTION FILE &optional DOCSTRING INTERACTIVE TYPE)`
///
/// Register FUNCTION to be autoloaded from FILE.  Creates an autoload form
/// `(autoload FILE DOCSTRING INTERACTIVE TYPE)` and stores it as the function
/// cell of the symbol.  Also registers an [`AutoloadEntry`] with the
/// evaluator's [`AutoloadManager`].  Returns the function name symbol.
pub(crate) fn sf_autoload(
    eval: &mut super::eval::Context,
    tail: &[super::expr::Expr],
) -> super::error::EvalResult {
    let mut args = Vec::with_capacity(tail.len());
    for expr in tail {
        let form = eval.quote_to_runtime_value(expr);
        args.push(eval.eval_sub(form)?);
    }
    register_autoload_in_state(&mut eval.obarray, &mut eval.autoloads, &args)
}

// ---------------------------------------------------------------------------
// GcTrace
// ---------------------------------------------------------------------------

impl GcTrace for AutoloadManager {
    fn trace_roots(&self, roots: &mut Vec<Value>) {
        for values in self.after_load.values() {
            for value in values {
                roots.push(*value);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
#[path = "autoload_test.rs"]
mod tests;