bynk_emit/emitter/runtime_use.rs
1//! Which runtime helpers an emitted module's *callers other than its own header* need.
2//!
3//! Every module the emitter or the harness builds takes its runtime import from its built
4//! tree: a unit module since 1A.36b-1 (`runtime_header`), the Worker `index.ts` and
5//! `compose.ts` since 1A.36b-2, and the generated test modules since 1B.5e. **So nothing here
6//! decides an import at all.** What remains is emission itself: `plain_json`, `virtual_time`,
7//! `http_result_cookie` (the `bynk` `Cookie` type a case reads, not a runtime name) and the
8//! codec roots decide what is *emitted*. 1B.5e deleted the 28 flags whose only reader was the
9//! test harness's predicted import list, with their notes and fields.
10//!
11//! A Worker module's own `RuntimeUse` (`workers.rs`, `workers_entry.rs`) is a sink: the codec
12//! producers shared with the unit modules take one to note into, and nothing reads it back.
13//!
14//! The notes that remain are the ones emission itself reads: the `Bytes` helpers
15//! (`__bynkBytesEqual` and friends, v0.110 / ADR 0142), the `detach` reporter, the comparator,
16//! key and `Decimal` helper sets a module's witnesses name, and the codec state below. The
17//! notes whose only reader was an emitter-built module's header (the ICU formatters, the
18//! session-cookie helpers and the two trace helpers) went in 1A.36b-1; those whose only
19//! reader was the test harness's import list went in 1B.5e.
20//!
21//! #917 adds a differently-shaped piece of state, riding this same shared reference for
22//! the same reason: a test-scaffold module's `Json.decode`/`Json.encode` on a named type has
23//! no local codec to delegate to (the unit it imports exports the type but not a codec for
24//! it), so the module generates its own — the `json_codec_qual`/`json_codec_roots` fields
25//! carry the namespace a foreign type's TS positions render through and the roots its bodies
26//! reached for, respectively.
27//!
28//! The condition is "did emission actually reference it", which is a fact only
29//! emission knows. This type is how that fact travels: the producers call
30//! [`RuntimeUse::note_bytes`] and the like as they emit, and the emission that depends on the
31//! fact reads it afterwards.
32//!
33//! # Why not scan the generated text
34//!
35//! This replaces `out.contains("__bynkBytes")` and friends. Scanning the output
36//! for the helper's own name is wrong in both directions. It over-matches: the
37//! generated text also carries user-authored string literals, doc comments, and
38//! field names, any of which could contain the marker and pull in an import
39//! nothing calls. Worse, it under-matches: `out.contains("selectPluralArm(")`
40//! quietly depends on the call being emitted with no space before its paren, so
41//! a formatting change in an unrelated part of the emitter silently drops a
42//! required import and produces a module that does not compile. There is no test
43//! that would obviously catch it, because the marker and the scan live in
44//! different files.
45//!
46//! Every header goes further: it reads the tree, which carries each name as a node, so no
47//! note is needed for an import at all.
48//!
49//! # What keeps the producers honest
50//!
51//! A producer added without a matching `note_*` call emits a module that
52//! references an unimported name. Deliberately *not* guarded here by comparing
53//! the flags against a scan of the generated text: that scan would inherit the
54//! over-matching described above, so a user string literal containing the marker
55//! would fire the assertion on valid input — trading a rare missing import for a
56//! panic on legitimate code. The check belongs where it is already total:
57//! `bynkc`'s fixture suite type-checks every emitted fixture under `tsc --strict`
58//! (`tests/tsc_verify.rs`), which fails loudly on an unimported reference.
59//!
60//! Interior mutability (`Cell`) rather than `&mut`: the producers sit at the
61//! bottom of a deep tree of `&`-taking emit functions — several of them pure
62//! `String`-returning helpers — and a shared `&RuntimeUse` threads through that
63//! tree without turning every intermediate signature into a `&mut` chain.
64//!
65//! The consequence, recorded here so it does not have to be bisected for later:
66//! `Cell` is `!Sync`, so [`RuntimeUse`] is `!Sync`, and so is `EmitProjectCtx`
67//! now that it owns one — an `&EmitProjectCtx` can no longer cross a thread
68//! boundary. Nothing in the tree is parallel today, so this costs nothing, but
69//! per-unit emission is the obvious thing to parallelise, and that is when it
70//! will bite. Swapping the fields to `AtomicBool` with `Relaxed` ordering
71//! restores `Sync` at no meaningful cost and leaves every call site reading the
72//! same — do that rather than unpicking the shared-`&` design.
73
74use std::cell::{Cell, RefCell};
75use std::collections::HashMap;
76
77use bynk_check::checker::TyId;
78
79use super::internal_fault::InternalFault;
80
81/// Per-module accumulator of conditional runtime-helper references.
82///
83/// One instance per emitted module (it lives on that module's emission context),
84/// so flags never leak between files.
85#[derive(Default)]
86pub struct RuntimeUse {
87 bytes: Cell<bool>,
88 /// #3437: the module references `e.detach()`'s reporter, `__bynkDetach`.
89 detach: Cell<bool>,
90 /// #2683: the test module runs on virtual time, so an addressed call is
91 /// driven by `__bynkSettleVirtual`.
92 virtual_time: Cell<bool>,
93 /// #3277: a case reads the cookies of an `HttpResult`, so names the `bynk` `Cookie` type.
94 http_result_cookie: Cell<bool>,
95 /// Constrained generics slice 1: the comparator helpers (`__bynkCmpInt`,
96 /// `__bynkCmpRecord`, …) the module's witnesses, ordering operators and
97 /// ordering kernels reference.
98 cmp: RefCell<std::collections::BTreeSet<&'static str>>,
99 /// #2858: the project has a plain-JSON route, so the generated `Option`
100 /// encoders carry the plain branch `withPlainJson` switches on. Absent, they
101 /// are emitted byte-for-byte as before.
102 plain_json: Cell<bool>,
103 /// #917: for a test-scaffold module, the type-only namespace each
104 /// codec-eligible named type reaches through (`"Order" -> "orders."`) — the
105 /// module has no local declaration of its own, only a namespace import of
106 /// the suite's target (and its `uses`). Empty (the default) on every other
107 /// emission path, where every name renders bare.
108 json_codec_qual: RefCell<HashMap<String, String>>,
109 /// #917: the `Json.decode[T]`/`Json.encode` target types a test-scaffold
110 /// module's case/property/stub bodies actually reached for, collected as they
111 /// lower. `emit_test_module` drains this once all bodies are lowered to
112 /// compute the codec closure those bodies need — the unit module they import
113 /// exports the type but no codec, so a test-scaffold module generates its own
114 /// (#661's caller-generates-its-own-codec pattern, applied to test scaffolding).
115 /// P6.28 (design/tracks/the-ir.md §6a): stored as the checker's own resolved
116 /// `TyId` rather than a re-derived `TypeRef` — both push sites already hold
117 /// the `TyId` before converting it for their own, separate codec-rendering
118 /// use, so this field no longer needs its own `TypeRef` conversion at push
119 /// time; the drain site converts once, immediately before the one consumer
120 /// (`collect_codec_closure`) that is still genuinely `TypeRef`-driven.
121 json_codec_roots: RefCell<Vec<TyId>>,
122 /// #2052: the target's `from Events(E)` services a test-scaffold module's
123 /// bodies deliver an event to (`svc.event(e)`). `emit_test_module` emits
124 /// one `__bynkEvent_<svc>` delivery helper for each, once every body has
125 /// lowered, so a module that delivers none is unchanged.
126 test_event_services: RefCell<std::collections::BTreeSet<String>>,
127 /// 1A.34: the checker facts lowering needed and did not find, in the order
128 /// they were met ([`super::internal_fault`]).
129 faults: RefCell<Vec<InternalFault>>,
130}
131
132impl RuntimeUse {
133 /// Record that the project has a plain-JSON route (#2858).
134 pub fn set_plain_json(&self, on: bool) {
135 self.plain_json.set(on);
136 }
137
138 /// Whether the `Option` encoders carry the plain-JSON branch (#2858).
139 pub fn plain_json(&self) -> bool {
140 self.plain_json.get()
141 }
142
143 /// Record that the module references the `Bytes` runtime helpers.
144 pub fn note_bytes(&self) {
145 self.bytes.set(true);
146 }
147
148 /// Record that the test module runs on virtual time (#2683).
149 pub fn note_virtual_time(&self) {
150 self.virtual_time.set(true);
151 }
152
153 /// Whether the test module runs on virtual time (#2683).
154 pub fn virtual_time(&self) -> bool {
155 self.virtual_time.get()
156 }
157
158 /// Record that the module references the `detach` reporter (#3437).
159 pub fn note_detach(&self) {
160 self.detach.set(true);
161 }
162
163 /// Record that a result method names the `bynk` `Cookie` type (#3277).
164 pub fn note_http_result_cookie(&self) {
165 self.http_result_cookie.set(true);
166 }
167
168 /// Whether the module must import the `Cookie` type (#3277).
169 pub fn http_result_cookie(&self) -> bool {
170 self.http_result_cookie.get()
171 }
172
173 /// Record that the module references the comparator helper `name`
174 /// (`compare.ts`; constrained-generics slice 1).
175 pub fn note_cmp(&self, name: &'static str) {
176 self.cmp.borrow_mut().insert(name);
177 }
178
179 /// Record that the module references the key helper `name` (`keys.ts`;
180 /// constrained-generics slice 2). They share the comparator group's import
181 /// run, which is a generic set of runtime names.
182 pub fn note_key(&self, name: &'static str) {
183 self.note_cmp(name);
184 }
185
186 /// Record that the module references the `Decimal` runtime helper `name`
187 /// (`decimal.ts`, #2622). Rides the same set as the comparator helpers, so
188 /// every import site already emits it.
189 pub fn note_decimal(&self, name: &'static str) {
190 self.note_cmp(name);
191 }
192
193 /// The comparator helpers to import, as a `", a, b"` run (empty when the
194 /// module uses none), in the shape the other conditional groups take.
195 pub fn cmp_imports(&self) -> String {
196 self.cmp
197 .borrow()
198 .iter()
199 .map(|n| format!(", {n}"))
200 .collect::<String>()
201 }
202
203 /// #917: set once, up front, before any body lowers — the type-only
204 /// namespace qualifier a test-scaffold module's codec calls render foreign
205 /// named types through. A no-op default (empty map) everywhere else.
206 pub fn set_json_codec_qual(&self, qual: HashMap<String, String>) {
207 *self.json_codec_qual.borrow_mut() = qual;
208 }
209
210 /// The namespace qualifier a test-scaffold module's codec calls render
211 /// foreign named types through (empty on every other emission path).
212 pub fn json_codec_qual(&self) -> std::cell::Ref<'_, HashMap<String, String>> {
213 self.json_codec_qual.borrow()
214 }
215
216 /// #917: record a `Json.decode[T]`/`Json.encode` target type a test-scaffold
217 /// body reached for, so the module that spliced it in can generate the codec
218 /// helper its delegating call needs.
219 pub fn note_json_codec_root(&self, t: TyId) {
220 self.json_codec_roots.borrow_mut().push(t);
221 }
222
223 /// #2052: record that a test-scaffold body delivers an event to `service`.
224 pub fn note_test_event_service(&self, service: &str) {
225 self.test_event_services
226 .borrow_mut()
227 .insert(service.to_string());
228 }
229
230 /// #2052: the services a test-scaffold module delivers events to, sorted.
231 pub fn test_event_services(&self) -> Vec<String> {
232 self.test_event_services.borrow().iter().cloned().collect()
233 }
234
235 /// #3111: how many codec roots have been noted so far; a runner records it
236 /// before lowering and reads back what it added with
237 /// [`json_codec_roots_since`](Self::json_codec_roots_since).
238 pub fn json_codec_roots_len(&self) -> usize {
239 self.json_codec_roots.borrow().len()
240 }
241
242 /// #3111: the codec roots noted at or after `mark` (not drained).
243 pub fn json_codec_roots_since(&self, mark: usize) -> Vec<TyId> {
244 self.json_codec_roots
245 .borrow()
246 .get(mark..)
247 .unwrap_or_default()
248 .to_vec()
249 }
250
251 /// 1A.34: record a checker fact lowering needed and did not find.
252 pub fn note_internal_fault(&self, span: bynk_syntax::span::Span, what: String) {
253 self.faults.borrow_mut().push(InternalFault { span, what });
254 }
255
256 /// 1A.34: drain the recorded faults, once the unit has been lowered. Empty
257 /// for every program the checker passed.
258 pub fn take_faults(&self) -> Vec<InternalFault> {
259 std::mem::take(&mut *self.faults.borrow_mut())
260 }
261
262 /// Drain the accumulated `Json` codec roots — called once, after every
263 /// case/property/stub body in the module has lowered.
264 pub fn take_json_codec_roots(&self) -> Vec<TyId> {
265 std::mem::take(&mut *self.json_codec_roots.borrow_mut())
266 }
267
268 /// Whether the `Bytes` helpers must be imported.
269 pub fn bytes(&self) -> bool {
270 self.bytes.get()
271 }
272
273 /// Whether `__bynkDetach` must be imported (#3437).
274 pub fn detach(&self) -> bool {
275 self.detach.get()
276 }
277}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282
283 /// The type's contract, written down: the flags are independent and a
284 /// note latches. Everything else about this type is `Cell` behaviour and is
285 /// not worth a test — the coverage that matters drives the real producers
286 /// end-to-end (`emitter::conditional_runtime_import_tests`).
287 #[test]
288 fn notes_are_independent_and_latch() {
289 let u = RuntimeUse::default();
290 u.note_bytes();
291 assert!(u.bytes());
292 assert!(!u.detach(), "noting one helper does not set the other");
293 u.note_bytes();
294 assert!(u.bytes(), "a second note is not a toggle");
295 }
296}