Skip to main content

quickjs/builtins/
regexp.rs

1//! `RegExp` and `RegExp.prototype`.
2//!
3//! The engine lives in [`crate::regexp`]; this module is the JavaScript-facing half: the
4//! constructor, the compiled-pattern cache, `lastIndex`, and `exec`.
5//!
6//! `exec` is where most of the observable semantics live. A `g` or `y` pattern advances
7//! `lastIndex`, a failed match resets it to zero, and the returned array carries the
8//! captured groups plus `index`, `input` and (for the `d` flag) `indices`.
9
10use crate::builtins::{arg, define_method};
11use crate::interp::{Interp, JsResult};
12use crate::object::{JsObject, Property};
13use crate::regexp::{Flags, Regex};
14use crate::value::Value;
15use js_gc::Gc;
16
17/// The compiled pattern an object of `ObjectKind::RegExp` carries.
18///
19/// Boxed through `Rc` because a `RegExp` object is shared by every reference to it and
20/// the pattern is immutable once compiled.
21#[derive(Clone)]
22pub struct RegExpData {
23    /// The compiled pattern, shared between `exec` calls.
24    pub regex: std::rc::Rc<Regex>,
25    /// Pattern source as written, which `.source` reports.
26    pub source: String,
27    /// The flags, in canonical order.
28    pub flags: String,
29}
30
31/// Install `RegExp` and its prototype methods.
32pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) -> Gc<JsObject> {
33    let prototype = interp.new_object(Some(object_proto.clone()));
34    let constructor = interp.new_native("RegExp", 2, constructor);
35    constructor.define(
36        "prototype",
37        Property::with_attributes(Value::Object(prototype.clone()), false, false),
38    );
39    prototype.define(
40        "constructor",
41        Property::with_attributes(Value::Object(constructor.clone()), true, false),
42    );
43
44    define_method(&prototype, "exec", 1, exec, interp);
45    define_method(&prototype, "test", 1, test, interp);
46    define_method(&prototype, "toString", 0, to_string, interp);
47    for (name, getter) in [
48        (
49            "source",
50            source as fn(&mut Interp<'_>, Value, &[Value]) -> JsResult<Value>,
51        ),
52        ("flags", flags),
53        ("global", global),
54        ("ignoreCase", ignore_case),
55        ("multiline", multiline),
56        ("sticky", sticky),
57        ("unicode", unicode),
58        ("dotAll", dot_all),
59        ("hasIndices", has_indices),
60    ] {
61        let getter = interp.new_native(name, 0, getter);
62        prototype.define(
63            name,
64            Property {
65                getter: Some(Value::Object(getter)),
66                enumerable: false,
67                configurable: true,
68                ..Property::default()
69            },
70        );
71    }
72
73    // `Symbol.match` and friends are what `String.prototype.match` looks up; without them
74    // a regexp is not recognised as a pattern by those methods.
75    install_symbol_methods(interp, &prototype, &constructor);
76    interp.realm.regexp_proto = Some(prototype.clone());
77    interp.realm.regexp_ctor = Some(constructor.clone());
78    constructor
79}
80
81fn install_symbol_methods(
82    interp: &mut Interp<'_>,
83    prototype: &Gc<JsObject>,
84    constructor: &Gc<JsObject>,
85) {
86    use crate::interp::WellKnown;
87    for (which, name, func, length) in [
88        (
89            WellKnown::Match,
90            "[Symbol.match]",
91            symbol_match as crate::object::NativeFn,
92            1,
93        ),
94        (WellKnown::Replace, "[Symbol.replace]", symbol_replace, 2),
95        (WellKnown::Search, "[Symbol.search]", symbol_search, 1),
96        (WellKnown::Split, "[Symbol.split]", symbol_split, 2),
97    ] {
98        let method = interp.new_native(name, length, func);
99        prototype.define_key(
100            &interp.realm.well_known_key(which),
101            Property::with_attributes(Value::Object(method), true, false),
102        );
103    }
104    let _ = constructor;
105}
106
107/// `new RegExp(pattern, flags)`.
108fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
109    let pattern = arg(args, 0);
110    let flags = arg(args, 1);
111    // `new RegExp(existingRegExp)` copies the pattern and flags.
112    let (source, flags) = match &pattern {
113        Value::Object(object) if object.regexp().is_some() => {
114            let data = object.regexp().expect("checked");
115            let flags = if matches!(flags, Value::Undefined) {
116                data.flags.clone()
117            } else {
118                interp.to_js_string(&flags)?
119            };
120            (data.source.clone(), flags)
121        }
122        Value::Undefined => (String::new(), String::new()),
123        other => (
124            interp.to_js_string(other)?,
125            if matches!(flags, Value::Undefined) {
126                String::new()
127            } else {
128                interp.to_js_string(&flags)?
129            },
130        ),
131    };
132    Ok(Value::Object(new_regexp(interp, &source, &flags)?))
133}
134
135/// `RegExp.prototype.exec(string)`.
136fn exec(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
137    let Some(object) = this.as_object() else {
138        return Err(interp.type_error("RegExp.prototype.exec called on a non-object"));
139    };
140    let text = interp.to_js_string(&arg(args, 0))?;
141    exec_on(interp, object, &text)
142}
143
144/// The shared implementation of `exec`, used by the `String` methods as well.
145pub fn exec_on(interp: &mut Interp<'_>, object: &Gc<JsObject>, text: &str) -> JsResult<Value> {
146    let Some(data) = object.regexp() else {
147        return Err(interp.type_error("method called on a non-RegExp"));
148    };
149    let sticky_or_global = data.regex.flags.global || data.regex.flags.sticky;
150    let mut start = if sticky_or_global {
151        let index = interp.get_property(object, "lastIndex")?;
152        let index = interp.to_js_number(&index.unwrap_or(Value::Int(0)))?;
153        if !index.is_finite() || index < 0.0 {
154            interp.set_property(object, "lastIndex", Value::Int(0))?;
155            return Ok(Value::Null);
156        }
157        index as usize
158    } else {
159        0
160    };
161    let input: Vec<char> = text.chars().collect();
162    // `lastIndex`, `index` and the `d` flag's pairs all count **UTF-16 code units**, while the
163    // matcher works in characters. `unit_start[i]` is the code-unit offset of character `i`,
164    // with one extra entry for the end, so the two unit systems convert both ways.
165    let mut unit_start = Vec::with_capacity(input.len() + 1);
166    let mut units = 0;
167    for character in &input {
168        unit_start.push(units);
169        units += character.len_utf16();
170    }
171    unit_start.push(units);
172    // A `lastIndex` inside a surrogate pair has no character of its own; it belongs to the
173    // character that contains it, which is the same as rounding down to a code point
174    // boundary — what the reference does, and what makes `/(?:)/gu` with `lastIndex = 1` on
175    // `"🐱"` report `index === 0`.
176    if start > units {
177        if sticky_or_global {
178            interp.set_property(object, "lastIndex", Value::Int(0))?;
179        }
180        return Ok(Value::Null);
181    }
182    start = unit_start
183        .partition_point(|offset| *offset <= start)
184        .saturating_sub(1);
185    let found = data.regex.exec_at(&input, start);
186    let Some(found) = found else {
187        if sticky_or_global {
188            interp.set_property(object, "lastIndex", Value::Int(0))?;
189        }
190        return Ok(Value::Null);
191    };
192    // `lastIndex` moves to the end of the match, in code units — not characters, which is
193    // why an astral match advances by two.
194    if sticky_or_global {
195        let units = unit_start[found.end.min(unit_start.len() - 1)];
196        interp.set_property(object, "lastIndex", Value::Int(units as i32))?;
197    }
198    // The result array: the whole match, then one element per group. A group that did not
199    // participate is `undefined`, not a hole.
200    let mut elements: Vec<Value> = Vec::with_capacity(found.captures.len());
201    for capture in &found.captures {
202        elements.push(match capture {
203            Some((start, end)) => interp.string(slice(&input, *start, *end)),
204            None => Value::Undefined,
205        });
206    }
207    let array = interp.new_array(elements);
208    let index = unit_start[found.start.min(unit_start.len() - 1)];
209    let input_value = interp.string(text);
210    interp.set_property(&array, "index", Value::Int(index as i32))?;
211    interp.set_property(&array, "input", input_value.clone())?;
212    interp.set_property(
213        &array,
214        "groups",
215        if found.captures.len() > 1 {
216            // Named groups are not supported, so there is nothing to report.
217            Value::Undefined
218        } else {
219            Value::Undefined
220        },
221    )?;
222    if data.regex.flags.has_indices {
223        let mut pairs = Vec::with_capacity(found.captures.len());
224        for capture in &found.captures {
225            pairs.push(match capture {
226                Some((start, end)) => {
227                    let (start, end) = (
228                        unit_start[(*start).min(unit_start.len() - 1)],
229                        unit_start[(*end).min(unit_start.len() - 1)],
230                    );
231                    let pair =
232                        interp.new_array(vec![Value::Int(start as i32), Value::Int(end as i32)]);
233                    Value::Object(pair)
234                }
235                None => Value::Undefined,
236            });
237        }
238        let indices = interp.new_array(pairs);
239        interp.set_property(&array, "indices", Value::Object(indices))?;
240    }
241    Ok(Value::Object(array))
242}
243
244fn slice(input: &[char], start: usize, end: usize) -> String {
245    input
246        .get(start..end)
247        .map(|chars| chars.iter().collect())
248        .unwrap_or_default()
249}
250
251/// `RegExp.prototype.test(string)`.
252fn test(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
253    let result = exec(interp, this, args)?;
254    Ok(Value::Bool(!matches!(result, Value::Null)))
255}
256
257fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
258    let Some(object) = this.as_object() else {
259        return Err(interp.type_error("RegExp.prototype.toString called on a non-object"));
260    };
261    let Some(data) = object.regexp() else {
262        return Err(interp.type_error("RegExp.prototype.toString called on a non-RegExp"));
263    };
264    let source = if data.source.is_empty() {
265        "(?:)".to_string()
266    } else {
267        data.source.clone()
268    };
269    Ok(interp.string(format!("/{source}/{}", data.flags)))
270}
271
272fn source(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
273    let data = data_of(interp, &this)?;
274    // An empty pattern reports `(?:)` so that `/` + source + `/` parses again.
275    let text = if data.source.is_empty() {
276        "(?:)".to_string()
277    } else {
278        data.source.clone()
279    };
280    Ok(interp.string(&text))
281}
282
283fn flags(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
284    let data = data_of(interp, &this)?;
285    Ok(interp.string(&data.flags))
286}
287
288fn data_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<RegExpData> {
289    match this.as_object().and_then(|object| object.regexp()) {
290        Some(data) => Ok(data.clone()),
291        None => Err(interp.type_error("method called on a non-RegExp")),
292    }
293}
294
295/// One of the boolean flag accessors.
296fn flag_getter(interp: &mut Interp<'_>, this: Value, pick: fn(&Flags) -> bool) -> JsResult<Value> {
297    let data = data_of(interp, &this)?;
298    Ok(Value::Bool(pick(&data.regex.flags)))
299}
300
301fn global(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
302    flag_getter(interp, this, |flags| flags.global)
303}
304fn ignore_case(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
305    flag_getter(interp, this, |flags| flags.ignore_case)
306}
307fn multiline(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
308    flag_getter(interp, this, |flags| flags.multiline)
309}
310fn sticky(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
311    flag_getter(interp, this, |flags| flags.sticky)
312}
313fn unicode(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
314    flag_getter(interp, this, |flags| flags.unicode)
315}
316fn dot_all(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
317    flag_getter(interp, this, |flags| flags.dot_all)
318}
319fn has_indices(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
320    flag_getter(interp, this, |flags| flags.has_indices)
321}
322
323// -- the Symbol methods ------------------------------------------------------
324//
325// These are what `String.prototype.match` and friends dispatch to. Each one re-reads the
326// pattern's flags through the object's own properties, as the spec does, so a subclass
327// that overrides `lastIndex` keeps working.
328
329/// `String.prototype.match`'s hook.
330fn symbol_match(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
331    let Some(object) = this.as_object() else {
332        return Err(interp.type_error("Symbol.match called on a non-object"));
333    };
334    let text = interp.to_js_string(&arg(args, 0))?;
335    let is_global = interp
336        .get_property(object, "global")?
337        .unwrap_or(Value::Undefined)
338        .to_boolean();
339    if !is_global {
340        return exec_on(interp, object, &text);
341    }
342    interp.set_property(object, "lastIndex", Value::Int(0))?;
343    let mut results = Vec::new();
344    let input: Vec<char> = text.chars().collect();
345    loop {
346        let result = exec_on(interp, object, &text)?;
347        if matches!(result, Value::Null) {
348            break;
349        }
350        let Value::Object(array) = &result else {
351            break;
352        };
353        let matched = interp.get_property(array, "0")?.unwrap_or(Value::Undefined);
354        let empty = interp.to_js_string(&matched)?.is_empty();
355        results.push(result);
356        if empty {
357            let next = interp
358                .get_property(object, "lastIndex")?
359                .unwrap_or(Value::Int(0));
360            let next = interp.to_js_number(&next)? as usize + 1;
361            interp.set_property(object, "lastIndex", Value::Int(next as i32))?;
362            if next > input.len() {
363                break;
364            }
365        }
366    }
367    if results.is_empty() {
368        return Ok(Value::Null);
369    }
370    Ok(Value::Object(interp.new_array(results)))
371}
372
373/// `String.prototype.search`'s hook: the index of the first match, or -1.
374fn symbol_search(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
375    let Some(object) = this.as_object() else {
376        return Err(interp.type_error("Symbol.search called on a non-object"));
377    };
378    let text = interp.to_js_string(&arg(args, 0))?;
379    // `search` ignores the caller's `lastIndex`: it always looks from the start, and
380    // leaves the property alone afterwards.
381    interp.set_property(object, "lastIndex", Value::Int(0))?;
382    let result = exec_on(interp, object, &text)?;
383    match result {
384        Value::Null => Ok(Value::Int(-1)),
385        Value::Object(array) => Ok(interp
386            .get_property(&array, "index")?
387            .unwrap_or(Value::Int(-1))),
388        other => Ok(other),
389    }
390}
391
392/// `String.prototype.split`'s hook.
393fn symbol_split(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
394    let Some(object) = this.as_object() else {
395        return Err(interp.type_error("Symbol.split called on a non-object"));
396    };
397    let text = interp.to_js_string(&arg(args, 0))?;
398    let limit = match arg(args, 1) {
399        Value::Undefined => u32::MAX,
400        other => {
401            let number = interp.to_js_number(&other)?;
402            if number.is_nan() || number < 0.0 {
403                0
404            } else {
405                number as u32
406            }
407        }
408    };
409    if limit == 0 {
410        return Ok(Value::Object(interp.new_array(Vec::new())));
411    }
412    let data = data_of(interp, &Value::Object(object.clone()))?;
413    let input: Vec<char> = text.chars().collect();
414    let mut parts: Vec<Value> = Vec::new();
415    let mut last = 0usize;
416    let mut scan = 0usize;
417    while scan <= input.len() {
418        let Some(found) = data.regex.exec_at(&input, scan) else {
419            break;
420        };
421        // A zero-length match cannot split anything, and taking it would loop forever.
422        if found.end == found.start {
423            scan = found.start + 1;
424            continue;
425        }
426        parts.push(interp.string(slice(&input, last, found.start)));
427        if parts.len() as u32 >= limit {
428            return Ok(Value::Object(interp.new_array(parts)));
429        }
430        for group in found.captures.iter().skip(1) {
431            parts.push(match group {
432                Some((start, end)) => interp.string(slice(&input, *start, *end)),
433                None => Value::Undefined,
434            });
435            if parts.len() as u32 >= limit {
436                return Ok(Value::Object(interp.new_array(parts)));
437            }
438        }
439        last = found.end;
440        scan = found.end;
441    }
442    parts.push(interp.string(slice(&input, last, input.len())));
443    Ok(Value::Object(interp.new_array(parts)))
444}
445
446/// `String.prototype.replace`'s hook, for a regexp pattern.
447fn symbol_replace(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
448    let Some(object) = this.as_object() else {
449        return Err(interp.type_error("Symbol.replace called on a non-object"));
450    };
451    let text = interp.to_js_string(&arg(args, 0))?;
452    let replacement = arg(args, 1);
453    let is_global = interp
454        .get_property(object, "global")?
455        .unwrap_or(Value::Undefined)
456        .to_boolean();
457    let data = data_of(interp, &Value::Object(object.clone()))?;
458    let input: Vec<char> = text.chars().collect();
459    let mut out = String::new();
460    let mut last = 0usize;
461    let mut scan = 0usize;
462    let mut replaced = false;
463    while scan <= input.len() {
464        let Some(found) = data.regex.exec_at(&input, scan) else {
465            break;
466        };
467        out.extend(input[last..found.start].iter());
468        let matched = slice(&input, found.start, found.end);
469        let substituted = substitute(interp, &replacement, &matched, &input, &found)?;
470        out.push_str(&substituted);
471        last = found.end;
472        let empty = found.start == found.end;
473        scan = if empty { found.end + 1 } else { found.end };
474        replaced = true;
475        if !is_global {
476            break;
477        }
478        if empty && found.end >= input.len() {
479            break;
480        }
481    }
482    if !replaced {
483        return Ok(interp.string(&text));
484    }
485    out.extend(input[last.min(input.len())..].iter());
486    Ok(interp.string(&out))
487}
488
489/// Apply a replacement: a function receives the match and its groups, a string
490/// understands `$&`, `$1`, `$\``, `$'` and `$$`.
491fn substitute(
492    interp: &mut Interp<'_>,
493    replacement: &Value,
494    matched: &str,
495    input: &[char],
496    found: &crate::regexp::Match,
497) -> JsResult<String> {
498    if let Value::Object(function) = replacement
499        && function.is_callable()
500    {
501        let mut args: Vec<Value> = vec![interp.string(matched)];
502        for group in found.captures.iter().skip(1) {
503            args.push(match group {
504                Some((start, end)) => interp.string(slice(input, *start, *end)),
505                None => Value::Undefined,
506            });
507        }
508        args.push(Value::Int(found.start as i32));
509        args.push(interp.string(input.iter().collect::<String>()));
510        let this = Value::Undefined;
511        let result = interp.call_value(Value::Object(function.clone()), this, args)?;
512        return interp.to_js_string(&result);
513    }
514    let template = interp.to_js_string(replacement)?;
515    let mut out = String::new();
516    let mut chars = template.chars().peekable();
517    while let Some(c) = chars.next() {
518        if c != '$' {
519            out.push(c);
520            continue;
521        }
522        match chars.peek() {
523            Some('$') => {
524                chars.next();
525                out.push('$');
526            }
527            Some('&') => {
528                chars.next();
529                out.push_str(matched);
530            }
531            Some('`') => {
532                chars.next();
533                out.extend(input[..found.start].iter());
534            }
535            Some('\'') => {
536                chars.next();
537                out.extend(input[found.end..].iter());
538            }
539            Some(digit) if digit.is_ascii_digit() => {
540                let mut digits = String::new();
541                while let Some(digit) = chars.peek().copied() {
542                    if !digit.is_ascii_digit() || digits.len() == 2 {
543                        break;
544                    }
545                    digits.push(digit);
546                    chars.next();
547                }
548                let index: usize = digits.parse().unwrap_or(0);
549                match found.captures.get(index) {
550                    Some(Some((start, end))) => out.extend(input[*start..*end].iter()),
551                    // An index beyond the group count leaves the `$n` as written.
552                    _ => {
553                        out.push('$');
554                        out.push_str(&digits);
555                    }
556                }
557            }
558            _ => out.push('$'),
559        }
560    }
561    Ok(out)
562}
563
564/// Build a `RegExp` object for `source`/`flags`, reusing an existing one when the same
565/// pattern was compiled before.
566pub fn new_regexp(interp: &mut Interp<'_>, source: &str, flags: &str) -> JsResult<Gc<JsObject>> {
567    let Some(parsed) = Flags::parse(flags) else {
568        return Err(invalid_pattern(interp, String::new(), "flags"));
569    };
570    let regex = match Regex::compile(source, parsed) {
571        Ok(regex) => regex,
572        Err(error) => {
573            // The reference reports the engine's own message, not a generic one.
574            return Err(invalid_pattern(interp, error.message, ""));
575        }
576    };
577    let prototype = interp
578        .realm
579        .regexp_proto
580        .clone()
581        .unwrap_or_else(|| interp.realm.object_proto.clone());
582    let object = interp.new_object(Some(prototype));
583    object.set_regexp(RegExpData {
584        regex: std::rc::Rc::new(regex),
585        source: source.to_string(),
586        flags: parsed.as_flag_string(),
587    });
588    object.define(
589        "lastIndex",
590        Property::with_attributes(Value::Int(0), true, false),
591    );
592    Ok(object)
593}
594
595/// The `SyntaxError` a malformed pattern raises.
596///
597/// The two forms the reference uses: a bad flag string reports `invalid regular expression
598/// flags`, and a bad pattern reports the engine's own message.
599fn invalid_pattern(interp: &Interp<'_>, message: String, flags: &str) -> crate::interp::Signal {
600    let text = if flags.is_empty() {
601        message
602    } else {
603        "invalid regular expression flags".to_string()
604    };
605    crate::interp::Signal::Throw(interp.make_error("SyntaxError", &text))
606}
607
608/// Whether `value` is a `RegExp` object.
609pub fn is_regexp(object: &Gc<JsObject>) -> bool {
610    object.regexp().is_some()
611}