quilt/langs/python/lang.rs
1use crate::{
2 lang::{Arity, Comments, InnerKind},
3 qterm::{QTerm, QTermTag},
4 term::Term,
5 treesitter::{DynTSLanguage, TSLanguage, TSProvider},
6};
7use miette::Result;
8use tree_sitter::Parser;
9
10/**************************************************************/
11
12pub struct PythonProvider(tree_sitter::Parser);
13
14impl Default for PythonProvider {
15 fn default() -> Self {
16 let mut parser = Parser::new();
17 parser
18 .set_language(&crate::grammars::python::LANGUAGE.into())
19 .expect("Error loading Python parser");
20 Self(parser)
21 }
22}
23
24impl TSProvider for PythonProvider {
25 fn parser(&mut self) -> &mut tree_sitter::Parser {
26 &mut self.0
27 }
28
29 fn hole_str(&self) -> &'static str {
30 "__HOLE__"
31 }
32
33 fn hashbang(&self) -> Option<&'static str> {
34 Some("#!/usr/bin/env python3")
35 }
36
37 /// `repr()` answers a query with Python's own literal for the value,
38 /// which is what makes a machine answer the inverse of lift. The
39 /// `PYTHONPATH` entry resolves `from quilt import *` against the package
40 /// next to this crate — the same path `reduce_py` teaches its one-shot
41 /// script — so a machine can be fed expanded meta-code, not just plain
42 /// Python.
43 /// The spec itself is data, so it lives in the runtime-side table
44 /// (`machine::script_spec`) that `qspawn` also reads — one source of
45 /// truth for the registry, the battery and `⟨M⟩` (issue #273).
46 fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
47 crate::machine::script_spec("python")
48 }
49
50 /// Preferred over the replay spec: one long-lived `python3` running a
51 /// small stdin kernel (`machine::PYTHON_KERNEL`) that exec-s each
52 /// sentinel-framed feed in one namespace — so definitions are real
53 /// process state, effects run exactly once, and a cell's stdout is its
54 /// own rather than the whole history's. The replay machine remains what
55 /// `script_spec` describes, for callers that want a snapshot-exact one.
56 fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
57 crate::machine::repl_spec("python")
58 }
59
60 /// Derived from the grammar's `REPEAT` rules by `bin/gen-arity`, not
61 /// hand-curated — see `quilt/src/langs/arity.rs` (#202).
62 fn arity(&self, tag: &str) -> Arity {
63 Arity::from_table(crate::langs::arity::PYTHON, tag)
64 }
65
66 /// `,` for the kinds `bin/gen-arity` finds comma-separated (#293).
67 fn separator(&self, tag: &str) -> Option<&'static str> {
68 crate::lang::comma_separator(crate::langs::arity::PYTHON_COMMA_SEPARATED, tag)
69 }
70
71 fn typ(&self, tag: &str) -> InnerKind {
72 if tag == "module" {
73 InnerKind::File
74 } else if tag == "assignment" || tag.ends_with("statement") || tag.ends_with("definition") {
75 InnerKind::Stmt
76 } else {
77 InnerKind::Expr
78 }
79 }
80
81 fn unwrap(&self, qterm: QTerm, ikind: Option<InnerKind>) -> Result<(QTerm, InnerKind)> {
82 if qterm.len() != 1 {
83 return Ok((qterm, InnerKind::File));
84 }
85 let qterm = qterm.squash();
86 // Upstream marks `expression_statement` as a supertype (tree-sitter-python
87 // `26855eab`), so the node no longer appears in a parse tree: `f(x)` comes
88 // back as `call`, not `expression_statement(call(...))`.
89 //
90 // Quilt does not put the wrapper back. The statement-ness of a fragment is
91 // reported through the returned `InnerKind`, not encoded as a node quilt
92 // invented — keeping a wrapper alive so the kind could be read back off a
93 // tag would tie the expanded form to an implementation detail of the
94 // grammar, which is exactly the coupling Quilt is meant to avoid (#184).
95 let QTermTag::Tuple(name) = qterm.tag() else {
96 return Ok((qterm, ikind.unwrap_or(InnerKind::Expr)));
97 };
98 if &*name == "tuple_expression" {
99 // A bare tuple (`a, b`) renders without delimiters, so the fragment
100 // splices flat into expression position. Keep it whole rather than
101 // squashing past it. Upstream moved this case out of
102 // `expression_statement` into its own node in the same release.
103 return Ok((qterm, InnerKind::Expr));
104 }
105 if &*name == "assignment" {
106 // An assignment is always a statement, regardless of position.
107 return Ok((qterm, InnerKind::Stmt));
108 }
109 match self.typ(&name) {
110 // An expression the caller explicitly placed in statement position.
111 // The term is unchanged; only the reported kind says so.
112 InnerKind::Expr if ikind == Some(InnerKind::Stmt) => Ok((qterm, InnerKind::Stmt)),
113 InnerKind::Expr => Ok((qterm, InnerKind::Expr)),
114 // Already statement-shaped (`if_statement`, `function_definition`, …).
115 // An explicit `Expr` hint still wins, as it did before.
116 _ if ikind == Some(InnerKind::Expr) => Ok((qterm, InnerKind::Expr)),
117 _ => Ok((qterm, InnerKind::Stmt)),
118 }
119 }
120}
121
122pub type PythonLanguage = TSLanguage<PythonProvider>;
123pub type DynPythonLanguage = DynTSLanguage<PythonProvider>;
124
125impl Comments for PythonLanguage {
126 const LINE: Option<&'static str> = Some("#");
127}