Skip to main content

quilt/langs/shell/
meta.rs

1//! The shell meta-languages: bash and zsh as *hosts* that drive generation
2//! (issue #151).
3//!
4//! A `.bash.quilt` / `.zsh.quilt` file is a shell metaprogram. Where the
5//! Rust/Python hosts emit builder calls into a `QTerm` runtime, these hosts have
6//! **no runtime library**: they represent generated code as ordinary
7//! double-quoted shell words (see [`super::ops`]). A quote `↖ … ↗` expands to
8//! `" … "` and a host unquote `↙x↘` is spliced into it verbatim, because a shell
9//! expansion carries its own `$`. So running the expanded script — which is what
10//! `quilt run foo.bash.quilt` does, and what makes
11//! [`hashbang`][crate::lang::Language::hashbang] reachable at last — prints the
12//! generated code.
13//!
14//! Because everything is a string, a shell host can generate *any* target
15//! language: `bash↖…↗`, `rs↖…↗`, `wgsl↖…↗` all reconstruct the same way.
16//!
17//! # What a shell host cannot spell
18//!
19//! Quilt's five operator glyphs each expand to a fixed spelling that is spliced
20//! into the ground source and re-parsed, applied *prefix* to what follows. A
21//! shell has no prefix-applied word operators at all — juxtaposition is command
22//! invocation, and a command is not a word — so four of the five have no
23//! spelling here and say so instead of leaking a placeholder into a generated
24//! script:
25//!
26//! * `↑` (lift) and `⟨N⟩` (name) would be the identity: a shell value is
27//!   already text, and a name is its own text. There is nothing to convert with
28//!   and nothing to convert to, so both point the caller at `↙…↘`.
29//! * `←` (emit) needs a `b_` accumulator, which the string model does not have —
30//!   the same limit Lean's host has (#132), for the same reason. Nix answers it
31//!   with `builtins.concatStringsSep`, applied prefix; the shell's join is
32//!   `printf '%s\n' "${xs[@]}"`, which takes its operand *inside* a
33//!   substitution rather than after a prefix, so it cannot be a spelling. Write
34//!   it in the unquote instead.
35//! * `↓` (reduce) needs the `QTerm` runtime no string host ships.
36//!
37//! `⟨T⟩` is the fifth, and it fails too: the shell is untyped.
38
39use miette::Result;
40use std::marker::PhantomData;
41
42use super::ops::{build_quote_str, build_str_code, build_unquote_str};
43use crate::lang::Arity;
44use crate::meta::OuterKind;
45use crate::prelude::{Index, *};
46use crate::{meta::MetaLanguage, qterm::QTerm, term::CmdOrHole};
47
48/**************************************************************/
49
50/// Which shell a [`ShellMetaLanguage`] speaks.
51///
52/// The two dialects reconstruct fragments identically — zsh's grammar is a fork
53/// of bash's and their double-quoting rules are the same — so the dialect is
54/// carried only so that a refusal names the host the user actually wrote, the
55/// way [`crate::langs::lean::meta`] has to accept both `lean` and `lean4`.
56pub trait ShellDialect: Default + Send + Sync + 'static {
57    /// The canonical registry name, as it appears in an error message.
58    const NAME: &'static str;
59}
60
61/// Marker: the bash dialect.
62#[derive(Default)]
63pub struct BashDialect;
64
65impl ShellDialect for BashDialect {
66    const NAME: &'static str = "bash";
67}
68
69/// Marker: the zsh dialect.
70#[derive(Default)]
71pub struct ZshDialect;
72
73impl ShellDialect for ZshDialect {
74    const NAME: &'static str = "zsh";
75}
76
77/**************************************************************/
78
79/// A shell host: string-based generation, parameterised by dialect.
80#[derive(Default)]
81pub struct ShellMetaLanguage<D: ShellDialect>(PhantomData<D>);
82
83/// The bash host.
84pub type BashMetaLanguage = ShellMetaLanguage<BashDialect>;
85
86/// The zsh host.
87pub type ZshMetaLanguage = ShellMetaLanguage<ZshDialect>;
88
89impl<D: ShellDialect> MetaLanguage for ShellMetaLanguage<D> {
90    fn expand_tuple(
91        &self,
92        _lang1: &str,
93        _tag: &str,
94        qterms: &[Arc<QTerm>],
95        cmds: &[CmdOrHole],
96        _arity: Arity,
97    ) -> Result<Arc<QTerm>> {
98        // Strings have no builder/accumulator, so variadic and fixed nodes
99        // reconstruct identically: literal text plus spliced children.
100        Ok(build_str_code(cmds, qterms))
101    }
102
103    fn expand_quote(
104        &self,
105        _lang1: &str,
106        _tag: &str,
107        _i: Index,
108        lang2: &str,
109        qterm: &Arc<QTerm>,
110        _cmds: &[CmdOrHole],
111    ) -> Result<Arc<QTerm>> {
112        Ok(build_quote_str(lang2, qterm))
113    }
114
115    fn expand_unquote(
116        &self,
117        _lang1: &str,
118        _tag: &str,
119        _i: Index,
120        lang2: &str,
121        qterm: &Arc<QTerm>,
122        _cmds: &[CmdOrHole],
123    ) -> Result<Arc<QTerm>> {
124        Ok(build_unquote_str(lang2, qterm))
125    }
126
127    /// Identity: the string model has no `b_` accumulator to emit/splice into,
128    /// so a child is woven into its parent purely by [`Self::expand_tuple`]'s
129    /// concatenation.
130    fn wrap_child(&self, qterm: Arc<QTerm>, _okind: OuterKind) -> Result<Arc<QTerm>> {
131        Ok(qterm)
132    }
133
134    /// No spelling. `↑` renders a host value as text, and every shell value
135    /// *is* text — so the honest spelling is the empty one, which would make
136    /// `↑` an invisible no-op in the generated script rather than an operator.
137    /// Refuse instead, and name the thing that does work.
138    fn lift_str(&self, target: &str) -> Result<&'static str> {
139        let host = D::NAME;
140        miette::bail!(
141            "{host} can't lift `{target}↑`: a shell value is already text, so there is no \
142             conversion to spell — splice it with `↙…↘`, which interpolates it as written"
143        )
144    }
145
146    /// No spelling: `←` needs a `b_` accumulator to append to, which the string
147    /// model doesn't have (see [`Self::wrap_child`]). Unlike Nix's
148    /// `builtins.concatStringsSep`, the shell's join cannot stand in for one:
149    /// an operator spelling is applied *prefix* to what follows it, and
150    /// `printf` takes its operand inside a substitution.
151    fn emit_str(&self) -> Result<&'static str> {
152        let host = D::NAME;
153        miette::bail!(
154            "{host} can't emit `←`: the string-based meta has no `b_` accumulator to emit into, \
155             and a shell join takes its operand inside a substitution rather than after a prefix \
156             — collect the fragments in an array and splice the join itself, \
157             `↙$(printf '%s\\n' \"${{frags[@]}}\")↘`"
158        )
159    }
160
161    /// No spelling: `↓` compiles a term and deserializes the result back, which
162    /// needs the `QTerm` runtime this host doesn't have. Generation-time
163    /// evaluation is ordinary shell — compute the value in a variable and
164    /// splice it with `↙…↘`.
165    fn reduce_str(&self, target: &str) -> Result<&'static str> {
166        let host = D::NAME;
167        miette::bail!(
168            "{host} can't reduce `{target}↓`: the string-based meta has no `QTerm` runtime to \
169             evaluate a fragment — compute the value in ordinary shell and splice it with `↙…↘`"
170        )
171    }
172
173    /// No spelling: the shell is untyped — every value is a word — so there is
174    /// nothing for `⟨T⟩` to name and nowhere to write it.
175    fn type_str(&self) -> Result<&'static str> {
176        let host = D::NAME;
177        miette::bail!(
178            "{host} has no type for `⟨T⟩`: the shell is untyped and a generated fragment is just \
179             a word — drop the annotation"
180        )
181    }
182
183    /// No spelling, for [`Self::lift_str`]'s reason: a name in the string model
184    /// is its own text, and the shell has no identity function to say so with.
185    fn name_str(&self) -> Result<&'static str> {
186        let host = D::NAME;
187        miette::bail!(
188            "{host} has no spelling for `⟨N⟩`: a name is already its own text here — splice it \
189             with `↙…↘`"
190        )
191    }
192}