feat: 增加 CreateRegExp 字节码,正则字面量每次执行创建新对象

This commit is contained in:
爱特每羊队
2026-06-25 10:28:35 +08:00
parent 5007e7af7c
commit 1ef8349208
4 changed files with 48 additions and 5 deletions
@@ -18,7 +18,11 @@ impl Compiler {
}
pub(in crate::counter) fn count_regexp_literal(&self, ctx: &mut CompileCtx) {
ctx.alloc_reg();
ctx.alloc_reg(); // pattern reg (LOAD_CONST)
ctx.projected_pc += 1;
ctx.alloc_reg(); // flags reg (LOAD_CONST)
ctx.projected_pc += 1;
ctx.alloc_reg(); // result reg (CREATE_REGEXP)
ctx.projected_pc += 1;
}
@@ -68,11 +68,16 @@ impl Compiler {
let raw_str = raw.to_string();
if raw_str.len() >= 2 && raw_str.starts_with('/') {
let last_slash = raw_str.rfind('/').unwrap_or(raw_str.len() - 1);
let pattern = &raw_str[1..last_slash];
let flags = &raw_str[last_slash + 1..];
let ci = ctx.add_constant(Constant::RegExp(pattern.to_string(), flags.to_string()));
let pattern = raw_str[1..last_slash].to_string();
let flags = raw_str[last_slash + 1..].to_string();
let pat_ci = ctx.add_constant(Constant::String(pattern));
let pat_reg = ctx.alloc_reg();
ctx.emit_load_const(pat_reg, pat_ci);
let flags_ci = ctx.add_constant(Constant::String(flags));
let flags_reg = ctx.alloc_reg();
ctx.emit_load_const(flags_reg, flags_ci);
let r = ctx.alloc_reg();
ctx.emit_load_const(r, ci);
ctx.emit(opcode::encode(OpCode::CREATE_REGEXP, r, pat_reg, flags_reg));
Ok(r)
} else {
Err(format!("unsupported regexp literal: {:?}", lit))