quickjs-pure 0.17.30

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,
    /// The match itself, as `ToString(matchValue)` produced it.
    ///
    /// Not `input[position .. position + match_len]`: `RegExp.prototype[@@replace]` takes the
    /// match from an arbitrary value an `exec` override returned, and its `$&` is that value
    /// converted to a string — not the slice of the input it claims to come from
    /// (`Symbol.replace/result-coerce-matched`).
    pub matched: &'a [u16],
    /// Group `n` at `captures[n]`, **capture 0 being the whole match**, with each capture
    /// already reduced to its code units.
    ///
    /// Code units rather than offsets because the two callers get their captures from
    /// different places: the string methods slice their own input, while
    /// `RegExp.prototype[@@replace]` gets an arbitrary value per group from a user `exec` and
    /// must `ToString` each of them. Passing the units lets both use one expansion.
    ///
    /// 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<Vec<u16>>],
    /// Named groups, one entry per `$<…>` occurrence **in the template, in order**.
    ///
    /// **`None` is not the same as empty.** `$<name>` is syntax only when `namedCaptures`
    /// is not `undefined`: otherwise the reference emits a literal `$<` and keeps scanning,
    /// whereas an empty list would make `"$<y>"` expand to an empty string.
    ///
    /// One entry per occurrence rather than a lookup table because the value comes from
    /// `Get(namedCaptures, groupName)` — an arbitrary object, so a name may be inherited
    /// and the same name may be read twice. The caller resolves them in template order with
    /// [`template_group_names`], which is exactly the order this walk consumes them in.
    pub names: Option<&'a [(String, Vec<u16>)]>,
}

/// 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;
    // Which `$<…>` in the template this is, so a name read out of `names` matches the
    // occurrence being expanded rather than the first one with the same spelling.
    let mut occurrence = 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.matched);
                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(units)) = sub.captures.get(group) {
                        out.extend_from_slice(units);
                    }
                    // 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 the groups object does not have is `undefined`, whose `ToString`
                // is the empty string — *not* literal text. That is the opposite rule from
                // `$n`, and both are the reference's. The caller already resolved this
                // occurrence, `undefined` included.
                if let Some((_, units)) = sub.names.and_then(|names| names.get(occurrence)) {
                    out.extend_from_slice(units);
                }
                occurrence += 1;
                at = close + 1;
            }
            _ => {
                out.push(DOLLAR);
                at += 1;
            }
        }
    }
}

/// The group names a template mentions, one per `$<…>` occurrence, in order.
///
/// §22.1.3.19.1 step 2.c walks the template and reads `Get(namedCaptures, groupName)` as it
/// goes, so the *template* decides which names are read — not the groups object's own keys.
/// That is what lets an inherited name resolve, and what makes `$<length>` on
/// `groups: "123"` read the wrapper's `length`.
///
/// The scan has to agree with [`get_substitution`] about which `$<` sequences are real:
/// `$<` with no `>` after it is literal, and `$$<a>` is `$` followed by literals.
pub(crate) fn template_group_names(template: &Wtf8) -> Vec<String> {
    const DOLLAR: u16 = b'$' as u16;
    const OPEN: u16 = b'<' as u16;
    const CLOSE: u16 = b'>' as u16;
    let units = template.to_units();
    let mut names = Vec::new();
    let mut at = 0usize;
    while at < units.len() {
        if units[at] != DOLLAR {
            at += 1;
            continue;
        }
        let Some(next) = units.get(at + 1).copied() else {
            break;
        };
        if next == DOLLAR {
            at += 2;
            continue;
        }
        if next != OPEN {
            at += 1;
            continue;
        }
        let Some(offset) = units[at + 2..].iter().position(|&unit| unit == CLOSE) else {
            // No `>`: `get_substitution` emits a literal `$` and rescans from the `<`.
            at += 1;
            continue;
        };
        let close = at + 2 + offset;
        if let Some(name) = Wtf8::from_units(&units[at + 2..close]).as_str() {
            names.push(name.to_string());
        }
        at = close + 1;
    }
    names
}