quickjs-pure 0.13.1

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
//! `GetSubstitution` โ€” the `$` expansion shared by `String.prototype.replace`,
//! `String.prototype.replaceAll` and `RegExp.prototype[Symbol.replace]`.
//!
//! ยง22.1.3.19.1 takes a template plus the pieces of one match and produces the text that
//! replaces it. Everything it needs is a code-unit list, so it needs no `Interp`: the three
//! callers do their own `ToString` and hand the pieces here.
//!
//! **Code units, not code points or bytes.** `StringIndexOf` and every string offset in
//! ยง22.1 are UTF-16 code unit indices, and they do not have to land on a code point
//! boundary: `"\uD83D"` *does* occur in `"๐Ÿฑ"`, at unit 0. Working in units is what makes
//! `"๐Ÿฑ".replaceAll("", "-")` give `"-\uD83D-\uDC31-"` โ€” the two halves of the pair are
//! separate insertion points โ€” instead of inserting once around one code point.
//!
//! **The rule worth stating up front: a `$` sequence that names nothing is literal.**
//! `"a".replace("a", "$1")` is `"$1"` because a string pattern has no groups, and
//! `"a".replace(/(a)/, "$2")` is `"$2"` for the same reason. Both directions were wrong
//! before this existed: `String.prototype.replace` expanded only `$&`, and the regexp path
//! dropped a `$n` naming a group past the end instead of copying it through.

use crate::value::Wtf8;

/// What a substitution is expanded against. Every offset is a code unit index into `input`.
pub(crate) struct Substitution<'a> {
    /// The whole string the match came from.
    ///
    /// `$`` and `$'` are the text before and after the match, so the whole thing has to be
    /// here, not just the match.
    pub input: &'a [u16],
    /// Where the match begins in `input`.
    pub position: usize,
    /// How many code units the match is. For a literal pattern this is the pattern's own
    /// length; for a regexp it is `end - start`, which is *not* `matched.len()` when the
    /// pattern matched half of a surrogate pair.
    pub match_len: usize,
    /// Group `n` at `captures[n]`, in code units, with **capture 0 being the whole match**.
    ///
    /// The valid range is `1 ..= captures.len() - 1`; a pattern with no groups passes an
    /// empty slice, which is the same rule with nothing valid in it.
    pub captures: &'a [Option<(usize, usize)>],
    /// Group names, indexed by capture number like `captures`.
    ///
    /// **`None` is not the same as empty.** `$<name>` is syntax only when the pattern has
    /// named groups at all: with `namedCaptures` undefined the reference emits a literal
    /// `$<` and keeps scanning, whereas an empty list would make `"$<y>"` expand to an
    /// empty string. `/x/` and `"$<y>"` need the literal.
    pub names: Option<&'a [(String, usize)]>,
}

/// Append `template` to `out`, expanding every `$` sequence.
pub(crate) fn get_substitution(out: &mut Vec<u16>, template: &Wtf8, sub: &Substitution<'_>) {
    const DOLLAR: u16 = b'$' as u16;
    const AMP: u16 = b'&' as u16;
    const BACKTICK: u16 = b'`' as u16;
    const QUOTE: u16 = b'\'' as u16;
    const OPEN: u16 = b'<' as u16;
    const CLOSE: u16 = b'>' as u16;
    const ZERO: u16 = b'0' as u16;
    const NINE: u16 = b'9' as u16;

    let points = template.to_units();
    let group_count = sub.captures.len().saturating_sub(1);
    let end_of_match = sub.position + sub.match_len;
    let mut at = 0usize;
    while at < points.len() {
        if points[at] != DOLLAR {
            out.push(points[at]);
            at += 1;
            continue;
        }
        // A `$` that ends the template has nothing to escape into.
        let Some(next) = points.get(at + 1).copied() else {
            out.push(DOLLAR);
            break;
        };
        match next {
            v if v == DOLLAR => {
                out.push(DOLLAR);
                at += 2;
            }
            v if v == AMP => {
                out.extend_from_slice(
                    sub.input
                        .get(sub.position..end_of_match)
                        .unwrap_or_default(),
                );
                at += 2;
            }
            v if v == BACKTICK => {
                out.extend_from_slice(sub.input.get(..sub.position).unwrap_or_default());
                at += 2;
            }
            v if v == QUOTE => {
                out.extend_from_slice(sub.input.get(end_of_match..).unwrap_or_default());
                at += 2;
            }
            v if (ZERO..=NINE).contains(&v) => {
                // At most two digits: the grammar is `$nn`, never `$nnn`.
                let first = usize::from(v - ZERO);
                let second = points
                    .get(at + 2)
                    .copied()
                    .filter(|digit| (ZERO..=NINE).contains(digit))
                    .map(|digit| usize::from(digit - ZERO));
                // A two-digit index naming no group is retried as a one-digit one, and the
                // digit it gives back stays in the output: `$12` with two groups is group 1
                // followed by a literal `2`.
                let (group, digits) = match second {
                    Some(second) if first * 10 + second <= group_count => (first * 10 + second, 2),
                    _ => (first, 1),
                };
                if group >= 1 && group <= group_count {
                    if let Some(Some((start, end))) = sub.captures.get(group) {
                        out.extend_from_slice(sub.input.get(*start..*end).unwrap_or_default());
                    }
                    // A group that did not participate is the empty string, not the text.
                    at += 1 + digits;
                } else {
                    // Nothing named: the `$` is literal and the digits are not special.
                    out.push(DOLLAR);
                    at += 1;
                }
            }
            v if v == OPEN => {
                let close = sub.names.and_then(|_| {
                    points[at + 2..]
                        .iter()
                        .position(|&unit| unit == CLOSE)
                        .map(|offset| at + 2 + offset)
                });
                let Some(close) = close else {
                    // `$<` with no `>` after it, or a pattern with no named groups at all:
                    // the `$` is literal and the `<` is copied by the next iteration.
                    out.push(DOLLAR);
                    at += 1;
                    continue;
                };
                // A name that the pattern does not have reads as an absent property of the
                // groups object, whose `ToString` is the empty string โ€” *not* literal text.
                // That is the opposite rule from `$n`, and both are the reference's.
                let name: Option<String> = Wtf8::from_units(&points[at + 2..close])
                    .as_str()
                    .map(str::to_string);
                let index = name.and_then(|name| {
                    sub.names
                        .and_then(|names| names.iter().find(|(n, _)| *n == name))
                        .map(|(_, index)| *index)
                });
                if let Some(Some((start, end))) = index.and_then(|i| sub.captures.get(i).copied()) {
                    out.extend_from_slice(sub.input.get(start..end).unwrap_or_default());
                }
                at = close + 1;
            }
            _ => {
                out.push(DOLLAR);
                at += 1;
            }
        }
    }
}