use crate::{
builtins::{iterable::create_iter_result_object, regexp, BuiltInBuilder, IntrinsicObject},
context::intrinsics::Intrinsics,
error::JsNativeError,
object::{JsObject, ObjectData},
property::Attribute,
realm::Realm,
string::utf16,
symbol::JsSymbol,
Context, JsResult, JsString, JsValue,
};
use boa_gc::{Finalize, Trace};
use boa_profiler::Profiler;
use regexp::{advance_string_index, RegExp};
#[derive(Debug, Clone, Finalize, Trace)]
pub struct RegExpStringIterator {
matcher: JsObject,
string: JsString,
global: bool,
unicode: bool,
completed: bool,
}
impl IntrinsicObject for RegExpStringIterator {
fn init(realm: &Realm) {
let _timer = Profiler::global().start_event("RegExpStringIterator", "init");
BuiltInBuilder::with_intrinsic::<Self>(realm)
.prototype(
realm
.intrinsics()
.objects()
.iterator_prototypes()
.iterator(),
)
.static_method(Self::next, "next", 0)
.static_property(
JsSymbol::to_string_tag(),
"RegExp String Iterator",
Attribute::CONFIGURABLE,
)
.build();
}
fn get(intrinsics: &Intrinsics) -> JsObject {
intrinsics.objects().iterator_prototypes().regexp_string()
}
}
impl RegExpStringIterator {
fn new(matcher: JsObject, string: JsString, global: bool, unicode: bool) -> Self {
Self {
matcher,
string,
global,
unicode,
completed: false,
}
}
pub(crate) fn create_regexp_string_iterator(
matcher: JsObject,
string: JsString,
global: bool,
unicode: bool,
context: &mut Context<'_>,
) -> JsValue {
let regexp_string_iterator = JsObject::from_proto_and_data_with_shared_shape(
context.root_shape(),
context
.intrinsics()
.objects()
.iterator_prototypes()
.regexp_string(),
ObjectData::reg_exp_string_iterator(Self::new(matcher, string, global, unicode)),
);
regexp_string_iterator.into()
}
pub fn next(this: &JsValue, _: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
let mut iterator = this.as_object().map(JsObject::borrow_mut);
let iterator = iterator
.as_mut()
.and_then(|obj| obj.as_regexp_string_iterator_mut())
.ok_or_else(|| {
JsNativeError::typ().with_message("`this` is not a RegExpStringIterator")
})?;
if iterator.completed {
return Ok(create_iter_result_object(
JsValue::undefined(),
true,
context,
));
}
let m = RegExp::abstract_exec(&iterator.matcher, iterator.string.clone(), context)?;
if let Some(m) = m {
if !iterator.global {
iterator.completed = true;
return Ok(create_iter_result_object(m.into(), false, context));
}
let m_str = m.get(0, context)?.to_string(context)?;
if m_str.is_empty() {
let this_index = iterator
.matcher
.get(utf16!("lastIndex"), context)?
.to_length(context)?;
let next_index =
advance_string_index(&iterator.string, this_index, iterator.unicode);
iterator
.matcher
.set(utf16!("lastIndex"), next_index, true, context)?;
}
Ok(create_iter_result_object(m.into(), false, context))
} else {
iterator.completed = true;
Ok(create_iter_result_object(
JsValue::undefined(),
true,
context,
))
}
}
}