quilt/langs/python/meta.rs
1use miette::Result;
2
3use super::ops::{build_quote_code, build_tuple_code, build_unquote_code, build_variadic_block};
4use crate::lang::Arity;
5use crate::prelude::{Index, *};
6use crate::{
7 meta::{spawn_spelling, MetaLanguage, Prelude},
8 qterm::QTerm,
9 term::CmdOrHole,
10};
11
12/**************************************************************/
13
14#[derive(Default)]
15pub struct PythonMetaLanguage;
16
17impl MetaLanguage for PythonMetaLanguage {
18 fn expand_quote(
19 &self,
20 _lang1: &str,
21 tag: &str,
22 i: Index,
23 lang2: &str,
24 qterm: &Arc<QTerm>,
25 cmds: &[CmdOrHole],
26 ) -> Result<Arc<QTerm>> {
27 Ok(build_quote_code(tag, i, lang2, qterm, cmds))
28 }
29
30 fn expand_unquote(
31 &self,
32 _lang1: &str,
33 tag: &str,
34 i: Index,
35 lang2: &str,
36 qterm: &Arc<QTerm>,
37 cmds: &[CmdOrHole],
38 ) -> Result<Arc<QTerm>> {
39 Ok(build_unquote_code(tag, i, lang2, qterm, cmds))
40 }
41
42 fn expand_tuple(
43 &self,
44 _lang1: &str,
45 tag: &str,
46 qterms: &[Arc<QTerm>],
47 cmds: &[CmdOrHole],
48 arity: Arity,
49 ) -> Result<Arc<QTerm>> {
50 Ok(if arity == Arity::Variadic {
51 build_variadic_block(tag, cmds, qterms)
52 } else {
53 build_tuple_code(tag, cmds, qterms)
54 })
55 }
56
57 // `↑` is target-directed and written prefix, `↑(value)`: into Python it
58 // spells the `qlift` function (int, str, or QTerm — a method can't hang
59 // off builtin ints); into HTML it spells `qlift_html`, which
60 // entity-escapes lifted strings at runtime; into TypeScript `qlift_ts`, and
61 // into text `qlift_text`. All live in the `quilt_python` runtime.
62 fn lift_str(&self, target: &str) -> Result<&'static str> {
63 match target {
64 "python" | "py" => Ok("qlift"),
65 "html" => Ok("qlift_html"),
66 "typescript" | "ts" => Ok("qlift_ts"),
67 // Into text: `qlift_text`, or `qlift_text_in_quotes` for a hole the
68 // author wrapped in `"…"` (`lift::text`). Both take an optional
69 // dialect, and both are plain module globals, so a module that
70 // rebinds them picks a dialect for every `↑` it contains.
71 "text" | "txt" => Ok("qlift_text"),
72 crate::lift::TEXT_IN_QUOTES => Ok("qlift_text_in_quotes"),
73 _ => miette::bail!("python can't lift into {target:?}: no spelling registered"),
74 }
75 }
76
77 fn reduce_str(&self, target: &str) -> Result<&'static str> {
78 match target {
79 "" | "python" | "py" => Ok("reduce()"),
80 "rust" | "rs" => Ok("reduce_rs()"),
81 _ => miette::bail!("python can't reduce via {target:?}: no reduce_spelling registered"),
82 }
83 }
84
85 /// Machine-directed reduce: `db.↓(term)` spells the machine binding's
86 /// `eval` method (#268). Target-agnostic — the machine value, not the
87 /// annotation, knows its language.
88 fn reduce_method_str(&self, target: &str) -> Result<&'static str> {
89 match target {
90 "" => Ok("eval"),
91 _ => miette::bail!(
92 "python spells machine eval as a method on the machine value — write \
93 `m.↓(term)` with no annotation; the machine knows its own language"
94 ),
95 }
96 }
97
98 fn name_str(&self) -> Result<&'static str> {
99 Ok("name")
100 }
101
102 fn type_str(&self) -> Result<&'static str> {
103 Ok("QTerm")
104 }
105
106 /// The typing judgment on a machine: `db.⟨T⟩(term)` spells the machine
107 /// binding's `type_of` method (#273), the companion of
108 /// [`Self::reduce_method_str`]'s value judgment.
109 fn type_method_str(&self) -> Result<&'static str> {
110 Ok("type_of")
111 }
112
113 /// `lang⟨M⟩` spells the `spawn` the Python bindings already export
114 /// (`quilt-python`, #271) — the same provider choice `Multi::machine`
115 /// makes, so the machine a `.py.quilt` file gets is the machine the
116 /// conformance battery verifies.
117 fn spawn_str(&self, lang: &str) -> Result<String> {
118 spawn_spelling("python", lang, |l| format!("spawn({l:?})"))
119 }
120
121 /// No spelling: `←` needs a named `b_` accumulator in scope, and this host
122 /// has none (issue #152).
123 ///
124 /// Rust's variadic block is a *block expression*, so it can bind
125 /// `let mut b_ = tb(..)` and let ground statements append to it. Python has
126 /// no statement-block in expression position, so
127 /// [`build_variadic_block`](super::ops::build_variadic_block) emits the
128 /// fluent `tb(..).e(child).b()` chain instead — nothing to bind, and the
129 /// hole sits in argument position where a ground `for` is a syntax error.
130 /// The `quilt_python` runtime also exposes no `emit` method on a term, so
131 /// even a `b_` in scope would have nothing to call.
132 ///
133 /// This used to return `"emit(b_)"`, which quietly expanded a ground `←`
134 /// into generated Python referencing an undefined name — the same
135 /// silent-corruption failure the string-based hosts had in #190, and the
136 /// reason this accessor returns `Result` at all.
137 ///
138 /// The working alternative needs no accumulator from *us*: ground Python
139 /// builds the sequence with its own builder and splices the finished term,
140 /// which goes through `wrap_child` and the `.e(..)` chain as usual.
141 ///
142 /// ```python
143 /// b = tb("block")
144 /// for n in names:
145 /// b.e(↖print(↙name(n)↘)↗)
146 /// body = b.b()
147 /// out = ↖def f():
148 /// ↙body↘
149 /// ↗
150 /// ```
151 fn emit_str(&self) -> Result<&'static str> {
152 miette::bail!(
153 "python can't emit `←`: the fluent `.e(child)` chain has no named `b_` accumulator \
154 to emit into — build the sequence with your own `tb(..)` builder in ground code and \
155 splice the finished term with `↙…↘`"
156 )
157 }
158
159 /// `from quilt import *` — the `quilt` package whose `__init__.py`
160 /// re-exports the native `quilt._quilt` module (issue #274). One glob, so
161 /// the targets do not matter: `qlift`/`qlift_html` come along with
162 /// everything else.
163 ///
164 /// The marker is the import *statement* rather than the whole line, so a
165 /// hand-written selective import (`from quilt import tb, name`) counts as
166 /// already-imported and is left alone.
167 fn prelude(&self, _targets: &[&str]) -> Option<Prelude> {
168 Some(Prelude::new("from quilt import *", ["from quilt import"]))
169 }
170}