pythonrs 0.1.14

Python as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PyHost heap — the first compiled standalone Python runtime
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
//! Interactive REPL (`python --repl`, or `python` on a TTY).
//!
//! Keeps one persistent host across lines (module globals, defs, classes and
//! imports survive between prompts). Compound statements (those whose header
//! ends in `:`) accumulate lines until a blank line closes the block.
//!
//! Tab pops a `ColumnarMenu` of completions sourced from the LSP corpus
//! (`lsp::corpus` — keywords, builtins, `math.*`, and per-type method names)
//! plus the live module globals / class names from the persistent host. This
//! is the same word corpus the LSP serves; the REPL just adds the interpreter's
//! current bindings on top so freshly-defined names complete immediately.

use crate::banner;
use nu_ansi_term::Color;
use reedline::{
    default_emacs_keybindings, ColumnarMenu, Completer, Emacs, FileBackedHistory, KeyCode,
    KeyModifiers, MenuBuilder, Reedline, ReedlineEvent, ReedlineMenu, Signal, Span, Suggestion,
};
use reedline::{DefaultPrompt, DefaultPromptSegment};

/// History file: `~/.pythonrs/history` (falls back to CWD-relative if `$HOME`
/// is unset). Mirrors stryke's `~/.stryke/history`.
fn history_path() -> std::path::PathBuf {
    let dir = std::env::var_os("HOME")
        .map(|h| std::path::PathBuf::from(h).join(".pythonrs"))
        .unwrap_or_else(|| std::path::PathBuf::from(".pythonrs"));
    let _ = std::fs::create_dir_all(&dir);
    dir.join("history")
}

/// The static word corpus: every LSP-corpus name (keywords, builtins, `math.*`,
/// str/list/dict/set/tuple/int/float methods), sorted and deduped. Built once at
/// REPL startup — the corpus is `'static`, so this never changes across lines.
fn build_static_words() -> Vec<String> {
    let mut v: Vec<String> = crate::lsp::corpus()
        .iter()
        .map(|(name, ..)| (*name).to_string())
        .collect();
    v.sort();
    v.dedup();
    v
}

/// Byte index of the identifier under the cursor and the incomplete prefix. Word
/// boundaries are any non-identifier char (`.` included, so `math.sq` completes
/// the `sq` segment against bare corpus names like `sqrt`).
fn completion_word_start(line: &str, pos: usize) -> (usize, &str) {
    let pos = pos.min(line.len());
    let before = line.get(..pos).unwrap_or("");
    let start = before
        .char_indices()
        .rev()
        .find(|(_, c)| !(c.is_alphanumeric() || *c == '_'))
        .map(|(i, c)| i + c.len_utf8())
        .unwrap_or(0);
    (start, line.get(start..pos).unwrap_or(""))
}

/// Detect a `base.<partial>` attribute context at the cursor. Returns the
/// receiver identifier `base`, the byte offset where `partial` starts, and the
/// `partial` typed so far. `None` when the cursor is not immediately after a
/// `name.` (bare word, chained `a.b.`, or literal receiver → plain completion).
fn attr_context(line: &str, pos: usize) -> Option<(&str, usize, &str)> {
    let (pstart, partial) = completion_word_start(line, pos);
    let before = line.get(..pstart)?;
    // The partial must sit directly after a `.` (one ASCII byte).
    if !before.ends_with('.') {
        return None;
    }
    let dot = pstart - 1;
    let base_before = line.get(..dot)?;
    let base_start = base_before
        .char_indices()
        .rev()
        .find(|(_, c)| !(c.is_alphanumeric() || *c == '_'))
        .map(|(i, c)| i + c.len_utf8())
        .unwrap_or(0);
    let base = line.get(base_start..dot)?;
    if base.is_empty() {
        return None;
    }
    Some((base, pstart, partial))
}

/// Corpus method names for one chapter (`"str"`, `"list"`, …) — the per-type
/// method surface for builtin-type attribute completion.
fn corpus_chapter_names(chapter: &str) -> Vec<String> {
    crate::lsp::corpus()
        .iter()
        .filter(|(_, ch, ..)| *ch == chapter)
        .map(|(name, ..)| (*name).to_string())
        .collect()
}

/// One prefix-matched suggestion (shared struct-literal for both paths).
fn suggestion(value: String, span: Span) -> Suggestion {
    Suggestion {
        value,
        description: None,
        style: None,
        extra: None,
        span,
        append_whitespace: false,
        display_override: None,
        match_indices: None,
    }
}

/// Reedline completer: static LSP corpus + live host globals/class names,
/// prefix-matched against the identifier at the cursor.
struct PyCompleter {
    static_words: Vec<String>,
}

impl Completer for PyCompleter {
    fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
        // 1. `base.<partial>` — type-aware attribute/method completion off the
        //    receiver's live runtime type (str/list/…/module/instance).
        if let Some((base, start, partial)) = attr_context(line, pos) {
            let candidates: Option<Vec<String>> = crate::host::with_host(|h| {
                h.attr_completions(base).map(|a| match a {
                    crate::host::AttrCompletion::BuiltinType(ch) => corpus_chapter_names(ch),
                    crate::host::AttrCompletion::Names(v) => v,
                })
            });
            if let Some(mut names) = candidates {
                let span = Span::new(start, pos);
                names.retain(|w| w.starts_with(partial));
                names.sort();
                names.dedup();
                return names.into_iter().map(|w| suggestion(w, span)).collect();
            }
            // `base` unbound or no attr surface → fall through to word completion.
        }

        // 2. bare-word completion (keywords/builtins/methods + live globals).
        let (start, prefix) = completion_word_start(line, pos);
        let span = Span::new(start, pos);

        // Live bindings from the persistent host — same thread as read_line, so
        // a direct `with_host` read is always current (no snapshot needed).
        let dynamic = crate::host::with_host(|h| h.global_names());

        let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
        let mut out: Vec<Suggestion> = Vec::new();
        for w in self.static_words.iter().chain(dynamic.iter()) {
            if !w.starts_with(prefix) {
                continue;
            }
            if !seen.insert(w.as_str()) {
                continue;
            }
            out.push(suggestion(w.clone(), span));
        }
        out.sort_by(|a, b| a.value.cmp(&b.value));
        out
    }
}

/// Build a reedline editor wired with completion menu, Tab/Shift+Tab bindings,
/// and file-backed history.
fn build_editor() -> Reedline {
    let completer = PyCompleter {
        static_words: build_static_words(),
    };

    let menu = ColumnarMenu::default()
        .with_name("completion_menu")
        .with_columns(4)
        .with_column_padding(2);

    let mut keybindings = default_emacs_keybindings();
    keybindings.add_binding(
        KeyModifiers::NONE,
        KeyCode::Tab,
        ReedlineEvent::UntilFound(vec![
            ReedlineEvent::Menu("completion_menu".to_string()),
            ReedlineEvent::MenuNext,
        ]),
    );
    keybindings.add_binding(
        KeyModifiers::SHIFT,
        KeyCode::BackTab,
        ReedlineEvent::MenuPrevious,
    );
    keybindings.add_binding(
        KeyModifiers::NONE,
        KeyCode::BackTab,
        ReedlineEvent::MenuPrevious,
    );

    let editor = Reedline::create()
        .with_completer(Box::new(completer))
        .with_menu(ReedlineMenu::EngineCompleter(Box::new(menu)))
        .with_edit_mode(Box::new(Emacs::new(keybindings)));

    match FileBackedHistory::with_file(5_000, history_path()) {
        Ok(h) => editor.with_history(Box::new(h)),
        // History unavailable (read-only home, CI sandbox): run without it.
        Err(_) => editor,
    }
}

/// Run the REPL loop.
pub fn run() {
    banner::print_banner();
    crate::host::reset_host();
    let mut line_editor = build_editor();
    let prompt = DefaultPrompt::new(
        DefaultPromptSegment::Basic(">>> ".to_string()),
        DefaultPromptSegment::Empty,
    );

    loop {
        match line_editor.read_line(&prompt) {
            Ok(Signal::Success(mut buffer)) => {
                if buffer.trim().is_empty() {
                    continue;
                }
                // Accumulate an indented block if the header opens a suite.
                if opens_block(&buffer) {
                    let cont_prompt = DefaultPrompt::new(
                        DefaultPromptSegment::Basic("... ".to_string()),
                        DefaultPromptSegment::Empty,
                    );
                    while let Ok(Signal::Success(more)) = line_editor.read_line(&cont_prompt) {
                        if more.trim().is_empty() {
                            break;
                        }
                        buffer.push('\n');
                        buffer.push_str(&more);
                    }
                }
                run_line(&buffer);
            }
            Ok(Signal::CtrlC) => continue,
            Ok(Signal::CtrlD) => break,
            Ok(_) => continue,
            Err(_) => break,
        }
    }
}

/// Non-TTY REPL: read source lines from stdin and evaluate them with the same
/// interactive semantics as the TTY loop (persistent host, block accumulation on
/// an open header, `sys.displayhook` echo of non-`None` top-level expressions).
/// This is the pipe-driven analogue of CPython's `python3 -i < file` — reached
/// only when `--repl` is passed with a non-interactive stdin. No banner and no
/// prompts are emitted (nothing to prompt to), keeping stdout to program output
/// and displayhook echoes only.
pub fn run_piped() {
    use std::io::BufRead;
    crate::host::reset_host();
    let stdin = std::io::stdin();
    let mut lines = stdin.lock().lines().map_while(Result::ok);
    while let Some(mut buffer) = lines.next() {
        if buffer.trim().is_empty() {
            continue;
        }
        if opens_block(&buffer) {
            for more in lines.by_ref() {
                if more.trim().is_empty() {
                    break;
                }
                buffer.push('\n');
                buffer.push_str(&more);
            }
        }
        run_line(&buffer);
    }
}

fn opens_block(s: &str) -> bool {
    let t = s.trim_end();
    t.ends_with(':')
        || t.ends_with('\\')
        || t.ends_with('(')
        || t.ends_with('[')
        || t.ends_with('{')
}

fn run_line(src: &str) {
    match crate::compile_interactive(src) {
        Ok(prog) => match crate::run_compiled(prog) {
            Ok(_) => {}
            Err(e) => eprintln!("{}", Color::Red.paint(crate::plain_error(e))),
        },
        // A line that does not compile is shown with its source and caret, as
        // a script's is.
        Err(e) => eprint!(
            "{}",
            Color::Red.paint(crate::render_compile_error(&e, src, "<stdin>"))
        ),
    }
    // `PyRun_InteractiveOneObject` ends every statement with `flush_io()`, after
    // reporting its exception, so the next prompt follows everything it wrote.
    crate::stdio::flush_io();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn static_words_include_keywords_builtins_methods() {
        let v = build_static_words();
        assert!(v.iter().any(|w| w == "def"), "keyword `def` missing");
        assert!(v.iter().any(|w| w == "lambda"), "keyword `lambda` missing");
        assert!(v.iter().any(|w| w == "sqrt"), "math `sqrt` missing");
        assert!(
            v.iter().any(|w| w == "append"),
            "list method `append` missing"
        );
    }

    #[test]
    fn word_start_at_bare_identifier() {
        let s = "print(le";
        let (st, pre) = completion_word_start(s, s.len());
        assert_eq!(st, 6);
        assert_eq!(pre, "le");
    }

    #[test]
    fn word_start_snaps_after_dot() {
        let s = "math.sq";
        let (st, pre) = completion_word_start(s, s.len());
        assert_eq!(st, 5);
        assert_eq!(pre, "sq");
    }

    #[test]
    fn word_start_empty_prefix_after_space() {
        let s = "x = ";
        let (st, pre) = completion_word_start(s, s.len());
        assert_eq!(st, 4);
        assert_eq!(pre, "");
    }

    #[test]
    fn attr_context_detects_receiver_and_partial() {
        assert_eq!(attr_context("s.up", 4), Some(("s", 2, "up")));
        // Empty partial right after the dot.
        assert_eq!(attr_context("s.", 2), Some(("s", 2, "")));
        // Bare word — not an attribute context.
        assert_eq!(attr_context("upp", 3), None);
        // Chained: base parses as the segment before the last dot.
        assert_eq!(attr_context("a.b.c", 5), Some(("b", 4, "c")));
    }

    #[test]
    fn attr_completion_str_offers_str_methods_only() {
        use fusevm::Value;
        use std::sync::Arc;
        crate::host::reset_host();
        crate::host::with_host(|h| h.set_global("s", Value::Str(Arc::new("hi".to_string()))));

        let mut c = PyCompleter {
            static_words: build_static_words(),
        };
        let line = "s.up";
        let out = c.complete(line, line.len());
        assert!(
            out.iter().any(|s| s.value == "upper"),
            "str.upper not offered"
        );
        assert!(out.iter().all(|s| s.value.starts_with("up")));
        // A dict-only method must not leak onto a str receiver.
        let all = c.complete("s.", 2);
        assert!(all.iter().any(|s| s.value == "split"), "str.split missing");
        assert!(
            !all.iter().any(|s| s.value == "keys"),
            "dict.keys leaked onto str"
        );
    }

    #[test]
    fn attr_completion_list_offers_list_methods() {
        crate::host::reset_host();
        let lst = crate::host::with_host(|h| h.new_list(Vec::new()));
        crate::host::with_host(|h| h.set_global("xs", lst));

        let mut c = PyCompleter {
            static_words: build_static_words(),
        };
        let out = c.complete("xs.app", 6);
        assert!(
            out.iter().any(|s| s.value == "append"),
            "list.append not offered"
        );
        assert!(out.iter().all(|s| s.value.starts_with("app")));
    }

    #[test]
    fn attr_completion_unbound_base_falls_back_to_words() {
        crate::host::reset_host();
        let mut c = PyCompleter {
            static_words: build_static_words(),
        };
        // `nope` is unbound → attr path yields nothing, word completion runs on
        // the `up` segment (dot is a word boundary) and finds nothing starting
        // with `up` except any such corpus name; assert it does not panic and
        // every suggestion respects the `up` prefix.
        let out = c.complete("nope.up", 7);
        assert!(out.iter().all(|s| s.value.starts_with("up")));
    }

    #[test]
    fn completer_prefix_matches_and_dedups() {
        let mut c = PyCompleter {
            static_words: build_static_words(),
        };
        let line = "le";
        let out = c.complete(line, line.len());
        assert!(
            out.iter().any(|s| s.value == "len"),
            "`len` not suggested for `le`"
        );
        // Every suggestion must actually start with the prefix.
        assert!(out.iter().all(|s| s.value.starts_with("le")));
        // No duplicate values.
        let mut vals: Vec<&str> = out.iter().map(|s| s.value.as_str()).collect();
        vals.sort();
        let n = vals.len();
        vals.dedup();
        assert_eq!(n, vals.len(), "duplicate suggestions leaked");
    }
}