Skip to main content

targeted_mutation/instrument/
render.rs

1//! Probe rendering and compiler-error site blaming.
2
3use super::discover::variable_name;
4use super::model::{ArmGuard, RUNTIME_MOD, RangeIndexMode, Site, SiteKind};
5
6/// Instrumented text plus the mapping back to the original, used to blame a site for a
7/// compile error in the rewritten file.
8#[derive(Debug, PartialEq)]
9pub struct Rendered {
10    pub text: String,
11    /// `(output offset, original offset, length)` of each stretch copied from the original,
12    /// in output order.
13    segments: Vec<(usize, usize, usize)>,
14    /// `(output offset, length, site)` of each piece of text a probe added, in output order.
15    inserted: Vec<(usize, usize, u32)>,
16}
17
18impl Rendered {
19    /// Where a stretch of the original that no probe touches is in the instrumented
20    /// text. `None` when a probe is in it or next to its ends.
21    pub fn copied(&self, from: usize, to: usize) -> Option<(usize, usize)> {
22        self.segments
23            .iter()
24            .find(|(_, start, len)| *start <= from && to <= start + len)
25            .map(|(out, start, _)| (out + from - start, out + to - start))
26    }
27
28    /// Maps a byte offset in the instrumented text to the original. Offsets inside inserted
29    /// text map to the point of insertion.
30    /// The site whose probe text contains the byte at `offset` of the instrumented text.
31    pub fn inserted_by(&self, offset: usize) -> Option<u32> {
32        let idx = self.inserted.partition_point(|(out, _, _)| *out <= offset);
33        let (out, len, site) = self.inserted[idx.checked_sub(1)?];
34        (offset - out < len).then_some(site)
35    }
36
37    pub fn to_original(&self, offset: usize) -> usize {
38        let idx = self.segments.partition_point(|(out, _, _)| *out <= offset);
39        let Some((out, orig, len)) = idx.checked_sub(1).map(|i| self.segments[i]) else {
40            return 0;
41        };
42        // Past the end of the copied stretch is inserted text, which sits at its end.
43        orig + (offset - out).min(len)
44    }
45}
46
47struct Edit {
48    pos: usize,
49    end: usize,
50    /// 0: closes a site, 1: replaces an operator, 2: opens a site.
51    phase: u8,
52    /// Closers: innermost first. Openers: outermost first.
53    order: i64,
54    text: String,
55    /// The site the text belongs to.
56    site: u32,
57}
58
59/// Rewrites `source` with probes for the sites that `enabled` accepts.
60pub fn render(source: &str, sites: &[Site], enabled: &dyn Fn(u32) -> bool) -> Rendered {
61    let rt = format!("crate::{RUNTIME_MOD}");
62    let mut edits = vec![];
63    for site in sites.iter().filter(|s| enabled(s.id)) {
64        // Edits at one position are ordered by the length of their site, doubled to leave
65        // room: a site that wraps a whole expression goes around a site of that very
66        // expression (`if a > b` as a guard and as a comparison).
67        let wraps = matches!(
68            site.kind,
69            SiteKind::Return { .. }
70                | SiteKind::Body { .. }
71                | SiteKind::Guard { .. }
72                | SiteKind::Field { .. }
73        );
74        // tmt:ignore `2 +` orders the same: nothing longer starts or ends where a wrapping site does
75        let len = 2 * (site.end - site.start) as i64 + wraps as i64;
76        let (open, close) = match &site.kind {
77            SiteKind::Cmp { op, gap, .. } => {
78                let (fast, func) = if op.is_ordering() {
79                    ("fast_ord", "ord")
80                } else {
81                    ("fast_eq", "eq")
82                };
83                edits.push(Edit {
84                    pos: gap.0,
85                    end: gap.1,
86                    phase: 1,
87                    order: 0,
88                    text: "), &(".into(),
89                    site: site.id,
90                });
91                (
92                    "(match (&(".to_string(),
93                    format!(
94                        ")) {{ (__tmt_l, __tmt_r) => if {rt}::idle({id}u32) {{ {rt}::{fast}({code}u8, __tmt_l, __tmt_r) }} else {{ #[allow(unused_imports)] use {rt}::{{ValAny as _, ValNum as _}}; \
95                         {rt}::{func}({id}u32, {code}u8, __tmt_l, __tmt_r, (&{rt}::W(__tmt_l)).tmt_val(), (&{rt}::W(__tmt_r)).tmt_val()) }} }})",
96                        id = site.id,
97                        code = op.code(),
98                    ),
99                )
100            }
101            // In the probes below the user's operands are evaluated where no name the probe
102            // introduces is in scope: in the scrutinee of a `match`, in the initialiser of a
103            // `let`, or in an arm that binds nothing. A scrutinee keeps its temporaries
104            // until the end of the enclosing statement, as an arithmetic operator does.
105            SiteKind::Logic { and, gap, .. } => {
106                // The right operand stays in place, so it is evaluated exactly when the
107                // (possibly mutated) left operand asks for it.
108                let id = site.id;
109                edits.push(Edit {
110                    pos: gap.0,
111                    end: gap.1,
112                    phase: 1,
113                    order: 0,
114                    text: format!("); __tmt_c }} {{ 2u8 => {rt}::rhs({id}u32, {and}, "),
115                    site: site.id,
116                });
117                (
118                    // Each operand of `&&` / `||` drops its temporaries when it is done.
119                    // The `let` ends the left operand's; the arm ends the right one's.
120                    format!("(match {{ let __tmt_c: u8 = {rt}::lhs({id}u32, {and}, "),
121                    "), __tmt_c => __tmt_c == 1u8 })".to_string(),
122                )
123            }
124            SiteKind::Arith {
125                op,
126                assign,
127                gap,
128                cast_probes,
129                ..
130            } => {
131                // A compound assignment hands the probe the place to update.
132                let (holder, lhs_open, lhs_close) = if *assign {
133                    ("Aa", "&mut (", ")")
134                } else {
135                    ("Ar", "", "")
136                };
137                for &(slot, start, end) in cast_probes {
138                    let wider = 2 * (end - start) as i64 + 1;
139                    edits.push(Edit {
140                        pos: start,
141                        end: start,
142                        phase: 2,
143                        order: -wider,
144                        text: "(match (".into(),
145                        site: site.id,
146                    });
147                    edits.push(Edit {
148                        pos: end,
149                        end,
150                        phase: 0,
151                        order: wider,
152                        text: format!(
153                            ") {{ __tmt_v => {{ #[allow(unused_imports)] use {rt}::{{CastAny as _, CastPrim as _}}; \
154                             {rt}::record_cast({id}u32, {slot}u32, (&{rt}::W(&__tmt_v)).tmt_cast_bounds()); __tmt_v }} }})",
155                            id = site.id,
156                        ),
157                        site: site.id,
158                    });
159                }
160                edits.push(Edit {
161                    pos: gap.0,
162                    end: gap.1,
163                    phase: 1,
164                    order: 0,
165                    text: format!("{lhs_close}, "),
166                    site: site.id,
167                });
168                (
169                    format!("(match ({lhs_open}"),
170                    format!(
171                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{{any} as _, {prim} as _}}; \
172                         (&{rt}::{holder}::new(__tmt_a, __tmt_b)).{method}({id}u32) }} }})",
173                        any = op.fallback_trait(*assign),
174                        prim = op.prim_trait(*assign),
175                        method = op.method(*assign),
176                        id = site.id,
177                    ),
178                )
179            }
180            SiteKind::Not { bang, .. } => {
181                // Drop the `!`; the probe applies it (or not).
182                edits.push(Edit {
183                    pos: bang.0,
184                    end: bang.1,
185                    phase: 1,
186                    order: 0,
187                    text: String::new(),
188                    site: site.id,
189                });
190                (
191                    "(match (".to_string(),
192                    format!(
193                        ") {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyNot as _, NotPrim as _}}; \
194                         (&{rt}::Un::new(__tmt_a)).tmt_not({}u32) }} }})",
195                        site.id
196                    ),
197                )
198            }
199            SiteKind::Return { option, .. } => match option {
200                None => (
201                    " let __tmt_v: bool = {".to_string(),
202                    format!("}}; {rt}::ret({}u32, __tmt_v) ", site.id),
203                ),
204                Some(ty) => (
205                    format!(" let __tmt_v: {ty} = {{"),
206                    format!("}}; {rt}::ret_opt({}u32, __tmt_v) ", site.id),
207                ),
208            },
209            SiteKind::MinMax {
210                max, call, close, ..
211            } => {
212                // The receiver is borrowed, as a method call borrows it: a `max` that takes
213                // `&self` leaves it where it is, and one that takes it by value copies it
214                // out (or, for a type that cannot be copied, does not compile: no probe).
215                edits.push(Edit {
216                    pos: call.0,
217                    end: call.1,
218                    phase: 1,
219                    order: 0,
220                    text: "), ".into(),
221                    site: site.id,
222                });
223                // The call's own `)` (and a trailing comma) is replaced by the probe.
224                // The call is made as it was written, on the same operands; the probe only
225                // decides which of the two it is.
226                let (same, other) = if *max { ("max", "min") } else { ("min", "max") };
227                edits.push(Edit {
228                    pos: close.0,
229                    end: close.1,
230                    phase: 1,
231                    order: 0,
232                    text: format!(
233                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyMinMax as _, MinMaxPrim as _}}; \
234                         if (&{rt}::Mm(__tmt_a, &__tmt_b)).tmt_other({}u32) {{ (*__tmt_a).{other}(__tmt_b) }} else {{ (*__tmt_a).{same}(__tmt_b) }} }} }})",
235                        site.id
236                    ),
237                    site: site.id,
238                });
239                ("(match (&(".to_string(), String::new())
240            }
241            SiteKind::SliceEnd {
242                first,
243                receiver,
244                call,
245                ..
246            } => {
247                // Both calls are made as they are written. Only where the runtime knows
248                // the receiver's type does it ever ask for the other one; of anything else
249                // it has nothing to say, whatever the call returns.
250                let (same, other) = if *first {
251                    ("first", "last")
252                } else {
253                    ("last", "first")
254                };
255                let id = site.id;
256                let decide = format!(
257                    "#[allow(unused_imports)] use {rt}::{{AnyEnd as _, SliceEnd as _}}; \
258                     match (&{rt}::Ends(__TMT_BORROWED__)).tmt_other_end({id}u32, {first}) {{ \
259                     {rt}::End::Other => {{ let __tmt_o = (__TMT_PLACE__).{other}(); \
260                     if false {{ {rt}::same_type(&__tmt_o, &(__TMT_PLACE__).{same}()); }} __tmt_o }}, \
261                     {rt}::End::Same(__tmt_s) => {{ \
262                     let __tmt_r = (__TMT_PLACE__).{same}(); \
263                     __tmt_s.tmt_end_seen({id}u32, &__tmt_r); __tmt_r }} }}"
264                );
265                // A variable is the same place each time it is named, so it is named
266                // again for the call: the call then borrows it exactly as it did (a `&mut`
267                // for as long as it is one). Any other receiver is evaluated once and
268                // borrowed for the probe.
269                let (open, close) = if let Some(name) = variable_name(receiver) {
270                    // The receiver may have the name the probe would give.
271                    let seen = if name == "__tmt_s" {
272                        "__tmt_t"
273                    } else {
274                        "__tmt_s"
275                    };
276                    let decide = decide
277                        .replace("__tmt_s", seen)
278                        .replace("__TMT_PLACE__", &name);
279                    let (head, tail) = decide
280                        .split_once("__TMT_BORROWED__")
281                        .expect("the receiver is borrowed once");
282                    (format!("({{ {head}&("), format!("){tail} }})"))
283                } else {
284                    let decide = decide
285                        .replace("__TMT_BORROWED__", "__tmt_a")
286                        .replace("__TMT_PLACE__", "*__tmt_a");
287                    (
288                        "(match (&(".to_string(),
289                        format!(")) {{ __tmt_a => {{ {decide} }} }})"),
290                    )
291                };
292                edits.push(Edit {
293                    pos: call.0,
294                    end: call.1,
295                    phase: 1,
296                    order: 0,
297                    text: close,
298                    site: site.id,
299                });
300                (open, String::new())
301            }
302            SiteKind::StrAffix {
303                starts,
304                call,
305                close,
306                ..
307            } => {
308                let same = if *starts { "starts_with" } else { "ends_with" };
309                edits.push(Edit {
310                    pos: call.0,
311                    end: call.1,
312                    phase: 1,
313                    order: 0,
314                    text: "), ".into(),
315                    site: site.id,
316                });
317                edits.push(Edit {
318                    pos: close.0,
319                    end: close.1,
320                    phase: 1,
321                    order: 0,
322                    text: format!(
323                        ") {{ (__tmt_a, __tmt_p) => {{ #[allow(unused_imports)] use {rt}::{{AnyStrAffix as _, StrAffixPrim as _}}; \
324                         (&{rt}::Aff::new(__tmt_a, __tmt_p)).tmt_str_affix({}u32, {starts}, |__tmt_a, __tmt_p| (*__tmt_a).{same}(__tmt_p)) }} }})",
325                        site.id
326                    ),
327                    site: site.id,
328                });
329                ("(match (&(".to_string(), String::new())
330            }
331            SiteKind::StrReplace {
332                replace_all,
333                call,
334                comma,
335                close,
336                ..
337            } => {
338                let same_call = if *replace_all {
339                    "(*__tmt_a).replace(__tmt_f, __tmt_t)"
340                } else {
341                    "(*__tmt_a).replacen(__tmt_f, __tmt_t, 1)"
342                };
343                edits.push(Edit {
344                    pos: call.0,
345                    end: call.1,
346                    phase: 1,
347                    order: 0,
348                    text: "), ".into(),
349                    site: site.id,
350                });
351                edits.push(Edit {
352                    pos: comma.0,
353                    end: comma.1,
354                    phase: 1,
355                    order: 0,
356                    text: ", ".into(),
357                    site: site.id,
358                });
359                edits.push(Edit {
360                    pos: close.0,
361                    end: close.1,
362                    phase: 1,
363                    order: 0,
364                    text: format!(
365                        ") {{ (__tmt_a, __tmt_f, __tmt_t) => {{ #[allow(unused_imports)] use {rt}::{{AnyStrReplace as _, StrReplacePrim as _}}; \
366                         (&{rt}::Rep::new(__tmt_a, __tmt_f, __tmt_t)).tmt_str_replace({}u32, {replace_all}, |__tmt_a, __tmt_f, __tmt_t| {same_call}) }} }})",
367                        site.id
368                    ),
369                    site: site.id,
370                });
371                ("(match (&(".to_string(), String::new())
372            }
373            SiteKind::Clamp {
374                call, comma, close, ..
375            } => {
376                edits.push(Edit {
377                    pos: call.0,
378                    end: call.1,
379                    phase: 1,
380                    order: 0,
381                    text: "), ".into(),
382                    site: site.id,
383                });
384                edits.push(Edit {
385                    pos: comma.0,
386                    end: comma.1,
387                    phase: 1,
388                    order: 0,
389                    text: ", ".into(),
390                    site: site.id,
391                });
392                edits.push(Edit {
393                    pos: close.0,
394                    end: close.1,
395                    phase: 1,
396                    order: 0,
397                    text: format!(
398                        ") {{ (__tmt_a, __tmt_lo, __tmt_hi) => {{ #[allow(unused_imports)] use {rt}::{{AnyClamp as _, ClampPrim as _}}; \
399                         (&{rt}::Clp::new(__tmt_a, __tmt_lo, __tmt_hi)).tmt_clamp({}u32, |__tmt_a, __tmt_lo, __tmt_hi| (*__tmt_a).clamp(__tmt_lo, __tmt_hi)) }} }})",
400                        site.id
401                    ),
402                    site: site.id,
403                });
404                ("(match (&(".to_string(), String::new())
405            }
406            SiteKind::Rounding { op, call, .. } => {
407                let same = op.name();
408                let op_code = op.code();
409                edits.push(Edit {
410                    pos: call.0,
411                    end: call.1,
412                    phase: 1,
413                    order: 0,
414                    text: format!(
415                        ")) {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyRound as _, RoundPrim as _}}; \
416                         (&{rt}::Rnd(__tmt_a)).tmt_round({}u32, {op_code}u8, || (*__tmt_a).{same}()) }} }})",
417                        site.id
418                    ),
419                    site: site.id,
420                });
421                ("(match (&(".to_string(), String::new())
422            }
423            SiteKind::Quantifier {
424                all, call, close, ..
425            } => {
426                let same = if *all { "all" } else { "any" };
427                edits.push(Edit {
428                    pos: call.0,
429                    end: call.1,
430                    phase: 1,
431                    order: 0,
432                    text: ").__tmt_quant_mut(), ".into(),
433                    site: site.id,
434                });
435                edits.push(Edit {
436                    pos: close.0,
437                    end: close.1,
438                    phase: 1,
439                    order: 0,
440                    text: format!(
441                        ") {{ (__tmt_q, __tmt_f) => (&__tmt_q).tmt_quant({}u32, {all}, __tmt_f, |__tmt_i, __tmt_f| (*__tmt_i).{same}(__tmt_f)) }} }})",
442                        site.id
443                    ),
444                    site: site.id,
445                });
446                (
447                    format!(
448                        "({{ #[allow(unused_imports)] use {rt}::{{AnyQuant as _, QuantPrim as _, TmtQuantExt as _}}; match (("
449                    ),
450                    String::new(),
451                )
452            }
453            SiteKind::Position {
454                forward,
455                call,
456                close,
457                ..
458            } => {
459                let same = if *forward { "position" } else { "rposition" };
460                edits.push(Edit {
461                    pos: call.0,
462                    end: call.1,
463                    phase: 1,
464                    order: 0,
465                    text: format!(").__tmt_quant_mut())).tmt_pos({}u32, {forward}, ", site.id),
466                    site: site.id,
467                });
468                edits.push(Edit {
469                    pos: close.0,
470                    end: close.1,
471                    phase: 1,
472                    order: 0,
473                    text: format!(", |__tmt_i, __tmt_f| (*__tmt_i).{same}(__tmt_f)) }})"),
474                    site: site.id,
475                });
476                (
477                    format!(
478                        "({{ #[allow(unused_imports)] use {rt}::{{AnyPos as _, PosPrim as _, TmtQuantExt as _}}; (&(("
479                    ),
480                    String::new(),
481                )
482            }
483            SiteKind::SaturatingArith {
484                op, call, close, ..
485            } => {
486                let same = op.name();
487                let op_code = op.code();
488                edits.push(Edit {
489                    pos: call.0,
490                    end: call.1,
491                    phase: 1,
492                    order: 0,
493                    text: "), ".into(),
494                    site: site.id,
495                });
496                edits.push(Edit {
497                    pos: close.0,
498                    end: close.1,
499                    phase: 1,
500                    order: 0,
501                    text: format!(
502                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnySaturating as _, SaturatingPrim as _}}; \
503                         (&{rt}::Sat::new(__tmt_a, __tmt_b)).tmt_sat({}u32, {op_code}u8, |__tmt_a, __tmt_b| (*__tmt_a).{same}(__tmt_b)) }} }})",
504                        site.id
505                    ),
506                    site: site.id,
507                });
508                ("(match (&(".to_string(), String::new())
509            }
510            SiteKind::StrTrim { op, call, .. } => {
511                let same = op.name();
512                let op_code = op.code();
513                edits.push(Edit {
514                    pos: call.0,
515                    end: call.1,
516                    phase: 1,
517                    order: 0,
518                    text: format!(
519                        "))).tmt_str_trim({}u32, {op_code}u8, |__tmt_a| (*__tmt_a).{same}()) }})",
520                        site.id
521                    ),
522                    site: site.id,
523                });
524                (
525                    format!(
526                        "({{ #[allow(unused_imports)] use {rt}::{{AnyStrTrim as _, StrTrimPrim as _}}; (&{rt}::Trm(&("
527                    ),
528                    String::new(),
529                )
530            }
531            SiteKind::StrCaseEq { call, close, .. } => {
532                edits.push(Edit {
533                    pos: call.0,
534                    end: call.1,
535                    phase: 1,
536                    order: 0,
537                    text: "), ".into(),
538                    site: site.id,
539                });
540                edits.push(Edit {
541                    pos: close.0,
542                    end: close.1,
543                    phase: 1,
544                    order: 0,
545                    text: format!(
546                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyCaseEq as _, CaseEqPrim as _}}; \
547                         (&{rt}::Ceq::new(__tmt_a, __tmt_b)).tmt_case_eq({}u32, |__tmt_a, __tmt_b| (*__tmt_a).eq_ignore_ascii_case(__tmt_b)) }} }})",
548                        site.id
549                    ),
550                    site: site.id,
551                });
552                ("(match (&(".to_string(), String::new())
553            }
554            SiteKind::Abs { call, .. } => {
555                edits.push(Edit {
556                    pos: call.0,
557                    end: call.1,
558                    phase: 1,
559                    order: 0,
560                    text: format!(
561                        ")) {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyAbs as _, AbsPrim as _}}; \
562                         (&{rt}::AbsWrap(__tmt_a)).tmt_abs({}u32, || (*__tmt_a).abs()) }} }})",
563                        site.id
564                    ),
565                    site: site.id,
566                });
567                ("(match (&(".to_string(), String::new())
568            }
569            SiteKind::IterLimit {
570                take, call, close, ..
571            } => {
572                let same = if *take { "take" } else { "skip" };
573                edits.push(Edit {
574                    pos: call.0,
575                    end: call.1,
576                    phase: 1,
577                    order: 0,
578                    text: ", ".into(),
579                    site: site.id,
580                });
581                edits.push(Edit {
582                    pos: close.0,
583                    end: close.1,
584                    phase: 1,
585                    order: 0,
586                    text: format!(
587                        ") {{ (__tmt_i, __tmt_n) => {{ #[allow(unused_imports)] use {rt}::{{AnyIterLimit as _, IterLimitPrim as _}}; \
588                         (&{rt}::Ilm::new(__tmt_i, __tmt_n)).tmt_iter_limit({}u32, {take}, |mut __tmt_i, __tmt_n| __tmt_i.{same}(__tmt_n)) }} }})",
589                        site.id
590                    ),
591                    site: site.id,
592                });
593                ("(match (".to_string(), String::new())
594            }
595            SiteKind::EndianSwap { op, call, .. } => {
596                let same = op.name();
597                let (method_call, to_be) = match op {
598                    super::model::EndianOp::ToBeBytes => ("tmt_endian_bytes", true),
599                    super::model::EndianOp::ToLeBytes => ("tmt_endian_bytes", false),
600                    super::model::EndianOp::ToBe => ("tmt_endian_int", true),
601                    super::model::EndianOp::ToLe => ("tmt_endian_int", false),
602                };
603                edits.push(Edit {
604                    pos: call.0,
605                    end: call.1,
606                    phase: 1,
607                    order: 0,
608                    text: format!(
609                        ")) {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyEndian as _, EndianPrim as _}}; \
610                         (&{rt}::Endn(__tmt_a)).{method_call}({}u32, {to_be}, || (*__tmt_a).{same}()) }} }})",
611                        site.id
612                    ),
613                    site: site.id,
614                });
615                ("(match (&(".to_string(), String::new())
616            }
617            SiteKind::BitCount { op, call, .. } => {
618                let same = op.name();
619                let op_code = op.code();
620                edits.push(Edit {
621                    pos: call.0,
622                    end: call.1,
623                    phase: 1,
624                    order: 0,
625                    text: format!(
626                        ")) {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyBitCount as _, BitCountPrim as _}}; \
627                         (&{rt}::Btc(__tmt_a)).tmt_bit_count({}u32, {op_code}u8, || (*__tmt_a).{same}()) }} }})",
628                        site.id
629                    ),
630                    site: site.id,
631                });
632                ("(match (&(".to_string(), String::new())
633            }
634            SiteKind::LoopCtrl { is_break } => {
635                let other = if *is_break { "continue" } else { "break" };
636                (
637                    format!(
638                        "(if {rt}::loop_ctrl_swap({}u32) {{ {other}; }} else {{ ",
639                        site.id
640                    ),
641                    "; })".to_string(),
642                )
643            }
644            SiteKind::LiteralSet { call, close, .. } => {
645                edits.push(Edit {
646                    pos: call.0,
647                    end: call.1,
648                    phase: 1,
649                    order: 0,
650                    text: "), ".into(),
651                    site: site.id,
652                });
653                edits.push(Edit {
654                    pos: close.0,
655                    end: close.1,
656                    phase: 1,
657                    order: 0,
658                    text: format!(
659                        ") {{ (__tmt_a, __tmt_x) => {{ #[allow(unused_imports)] use {rt}::{{AnyLitSet as _, LitSetPrim as _}}; \
660                         (&{rt}::Lst::new(__tmt_a, __tmt_x)).tmt_lit_set({}u32, |__tmt_a, __tmt_x| (*__tmt_a).contains(__tmt_x)) }} }})",
661                        site.id
662                    ),
663                    site: site.id,
664                });
665                ("(match (&(".to_string(), String::new())
666            }
667            SiteKind::RangeContains {
668                inclusive,
669                open,
670                gap,
671                call,
672                close,
673                ..
674            } => {
675                let dots = if *inclusive { "..=" } else { ".." };
676                if open.0 < open.1 {
677                    edits.push(Edit {
678                        pos: open.0,
679                        end: open.1,
680                        phase: 1,
681                        order: 0,
682                        text: String::new(),
683                        site: site.id,
684                    });
685                }
686                edits.push(Edit {
687                    pos: gap.0,
688                    end: gap.1,
689                    phase: 1,
690                    order: 0,
691                    text: "), (".into(),
692                    site: site.id,
693                });
694                edits.push(Edit {
695                    pos: call.0,
696                    end: call.1,
697                    phase: 1,
698                    order: 0,
699                    text: "), &*(".into(),
700                    site: site.id,
701                });
702                edits.push(Edit {
703                    pos: close.0,
704                    end: close.1,
705                    phase: 1,
706                    order: 0,
707                    text: format!(
708                        ")) {{ (__tmt_s, __tmt_e, __tmt_x) => {{ #[allow(unused_imports)] use {rt}::{{AnyRangeContains as _, RangeContainsPrim as _}}; \
709                         (&{rt}::Rcn::new(__tmt_s, __tmt_e, __tmt_x)).tmt_range_contains({id}u32, {inclusive}, |__tmt_s, __tmt_e, __tmt_x| (__tmt_s{dots}__tmt_e).contains(__tmt_x)) }} }})",
710                        id = site.id,
711                    ),
712                    site: site.id,
713                });
714                ("(match ((".to_string(), String::new())
715            }
716            SiteKind::Range {
717                inclusive,
718                gap,
719                index: Some(idx),
720                ..
721            } => {
722                let (orig_dots, mut_dots) = if *inclusive {
723                    ("..=", "..")
724                } else {
725                    ("..", "..=")
726                };
727                let (open_str, extra_close) = match idx.mode {
728                    RangeIndexMode::Deref => ("(*(match ((", ")"),
729                    _ => ("(match ((", ""),
730                };
731                edits.push(Edit {
732                    pos: idx.head.0,
733                    end: idx.head.1,
734                    phase: 1,
735                    order: 0,
736                    text: String::new(),
737                    site: site.id,
738                });
739                edits.push(Edit {
740                    pos: gap.0,
741                    end: gap.1,
742                    phase: 1,
743                    order: 0,
744                    text: "), (".into(),
745                    site: site.id,
746                });
747                let (sv, ev) = if idx.base.contains("__tmt_s") || idx.base.contains("__tmt_e") {
748                    ("__tmt_rs", "__tmt_re")
749                } else {
750                    ("__tmt_s", "__tmt_e")
751                };
752                let branch = |dots: &str| match idx.mode {
753                    RangeIndexMode::Ref | RangeIndexMode::Deref => {
754                        format!("&({})[{sv}{dots}{ev}]", idx.base)
755                    }
756                    RangeIndexMode::RefMut => format!("&mut ({})[{sv}{dots}{ev}]", idx.base),
757                    RangeIndexMode::Get => format!("({}).get({sv}{dots}{ev})", idx.base),
758                    RangeIndexMode::GetMut => format!("({}).get_mut({sv}{dots}{ev})", idx.base),
759                };
760                let mut_expr = branch(mut_dots);
761                let orig_expr = branch(orig_dots);
762                edits.push(Edit {
763                    pos: idx.close_bracket.0,
764                    end: idx.close_bracket.1,
765                    phase: 1,
766                    order: 0,
767                    text: format!(
768                        ")) {{ ({sv}, {ev}) => if {rt}::range_end({id}u32) {{ {mut_expr} }} else {{ {orig_expr} }} }}){extra_close}",
769                        id = site.id,
770                    ),
771                    site: site.id,
772                });
773                (open_str.to_string(), String::new())
774            }
775            SiteKind::Range {
776                inclusive,
777                gap,
778                index: None,
779                ..
780            } => {
781                edits.push(Edit {
782                    pos: gap.0,
783                    end: gap.1,
784                    phase: 1,
785                    order: 0,
786                    text: ", ".into(),
787                    site: site.id,
788                });
789                let method = if *inclusive {
790                    "tmt_range_inclusive"
791                } else {
792                    "tmt_range"
793                };
794                (
795                    "(match (".to_string(),
796                    format!(
797                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyRange as _, RangePrim as _}}; \
798                         (&{rt}::Ar::new(__tmt_a, __tmt_b)).{method}({}u32) }} }})",
799                        site.id
800                    ),
801                )
802            }
803            SiteKind::Arm { guard, .. } => {
804                // The probe goes into the arm's guard, where it runs only when the
805                // pattern matched.
806                match guard {
807                    ArmGuard::None(arrow) => edits.push(Edit {
808                        pos: *arrow,
809                        end: *arrow,
810                        phase: 2,
811                        order: 0,
812                        text: format!("if {rt}::arm({}u32) ", site.id),
813                        site: site.id,
814                    }),
815                    ArmGuard::Existing(from, to) => {
816                        let wider = 2 * (to - from + 1) as i64;
817                        edits.push(Edit {
818                            pos: *from,
819                            end: *from,
820                            phase: 2,
821                            order: -wider,
822                            text: format!("{rt}::arm({}u32) && (", site.id),
823                            site: site.id,
824                        });
825                        edits.push(Edit {
826                            pos: *to,
827                            end: *to,
828                            phase: 0,
829                            order: wider,
830                            text: ")".into(),
831                            site: site.id,
832                        });
833                    }
834                }
835                (String::new(), String::new())
836            }
837            SiteKind::Stmt => (
838                format!("if {rt}::live({}u32) {{ ", site.id),
839                " }".to_string(),
840            ),
841            // A literal takes its type from where it stands, so it stays where it is.
842            SiteKind::Neg {
843                operand,
844                literal: true,
845                ..
846            } => (
847                format!("(if {rt}::live({}u32) {{ ", site.id),
848                format!(" }} else {{ {operand} }})"),
849            ),
850            SiteKind::Neg { minus, .. } => {
851                edits.push(Edit {
852                    pos: minus.0,
853                    end: minus.1,
854                    phase: 1,
855                    order: 0,
856                    text: String::new(),
857                    site: site.id,
858                });
859                (
860                    "(match (".to_string(),
861                    format!(
862                        ") {{ __tmt_a => if {rt}::live({}u32) {{ -__tmt_a }} else {{ __tmt_a }} }})",
863                        site.id
864                    ),
865                )
866            }
867            SiteKind::Guard { .. } => (
868                format!(
869                    "(match {rt}::guard_override({id}u32) {{ ::core::option::Option::Some(__tmt_g) => __tmt_g, ::core::option::Option::None => {rt}::guard_record({id}u32, ",
870                    id = site.id
871                ),
872                ") })".to_string(),
873            ),
874            SiteKind::Field {
875                name,
876                shorthand,
877                from_base: Some(from_base),
878                ..
879            } => (
880                format!(
881                    "{}if {rt}::live({}u32) {{ ",
882                    if *shorthand {
883                        format!("{name}: ")
884                    } else {
885                        String::new()
886                    },
887                    site.id
888                ),
889                format!(" }} else {{ {from_base} }}"),
890            ),
891            SiteKind::Field {
892                from_base: None, ..
893            } => continue,
894            SiteKind::Body { value, .. } => (
895                format!(" if !{rt}::live({}u32) {{ return {value}; }}", site.id),
896                String::new(),
897            ),
898        };
899        edits.push(Edit {
900            pos: site.start,
901            end: site.start,
902            phase: 2,
903            order: -len,
904            text: open,
905            site: site.id,
906        });
907        edits.push(Edit {
908            pos: site.end,
909            end: site.end,
910            phase: 0,
911            order: len,
912            text: close,
913            site: site.id,
914        });
915    }
916    edits.sort_by_key(|e| (e.pos, e.phase, e.order));
917
918    // tmt:ignore the capacity is a hint: any number gives the same text
919    let capacity = source.len() + edits.iter().map(|e| e.text.len()).sum::<usize>();
920    let mut text = String::with_capacity(capacity);
921    let mut segments = vec![];
922    let mut inserted = vec![];
923    let mut cursor = 0;
924    for edit in edits {
925        // Also when nothing lies between two edits: text inserted right after a replaced
926        // stretch then maps to where it was inserted, not to where the stretch began.
927        if edit.pos >= cursor {
928            segments.push((text.len(), cursor, edit.pos - cursor));
929            text.push_str(&source[cursor..edit.pos]);
930        }
931        // A line that ends inside a replaced stretch still ends: `line!()` and the place
932        // of a panic after it are what they were.
933        let replaced = &source[cursor.max(edit.pos)..cursor.max(edit.end)];
934        let lines = "\n".repeat(replaced.matches('\n').count());
935        inserted.push((text.len(), edit.text.len() + lines.len(), edit.site));
936        text.push_str(&edit.text);
937        text.push_str(&lines);
938        cursor = cursor.max(edit.end);
939    }
940    segments.push((text.len(), cursor, source.len() - cursor));
941    text.push_str(&source[cursor..]);
942    Rendered {
943        text,
944        segments,
945        inserted,
946    }
947}
948
949/// The sites to blame for a compile error at `offset` (original coordinates): the smallest
950/// enabled sites that contain it.
951pub fn blame(sites: &[Site], enabled: &dyn Fn(u32) -> bool, offset: usize) -> Vec<u32> {
952    // A replaced body is blamed for what is wrong in its own text only (`inserted_by`):
953    // by position it would answer for everything in the function.
954    let containing = || {
955        sites.iter().filter(|s| {
956            enabled(s.id)
957                && s.start <= offset
958                && offset <= s.end
959                && !matches!(s.kind, SiteKind::Body { .. })
960        })
961    };
962    let Some(smallest) = containing().map(|s| s.end - s.start).min() else {
963        return vec![];
964    };
965    containing()
966        .filter(|s| s.end - s.start == smallest)
967        .map(|s| s.id)
968        .collect()
969}