use crate::builtins::number;
use crate::builtins::{arg, define_method};
use crate::interp::{Interp, JsResult};
use crate::object::{JsObject, NativeFn, Property};
use crate::value::Value;
use js_gc::Gc;
pub fn install(interp: &mut Interp<'_>, boolean_proto: &Gc<JsObject>) {
number::install_boolean(interp, boolean_proto);
let global = interp.realm.global.clone();
for (name, length, func) in [
("isNaN", 1, number::global_is_nan as NativeFn),
("isFinite", 1, number::global_is_finite),
("eval", 1, eval),
("__gc", 0, gc),
("encodeURIComponent", 1, encode_uri_component),
("decodeURIComponent", 1, decode_uri_component),
("encodeURI", 1, encode_uri),
("decodeURI", 1, decode_uri),
("escape", 1, escape),
("unescape", 1, unescape),
] {
define_method(&global, name, length, func, interp);
}
for name in ["parseInt", "parseFloat"] {
let value = interp
.realm
.global
.own_property("Number")
.and_then(|property| property.value)
.and_then(|value| value.as_object().cloned())
.and_then(|number| number.own_property(name))
.and_then(|property| property.value);
if let Some(value) = value {
global.define(name, Property::with_attributes(value, true, false));
}
}
if let Some(property) = global.own_property("eval")
&& let Some(Value::Object(eval_fn)) = property.value
{
eval_fn.define(
"_frame_less",
Property::with_attributes(Value::Bool(true), false, false),
);
}
let print = interp.new_native("print", 0, js_print);
global.define_data("print", Value::Object(print.clone()));
let console = interp.new_object(Some(interp.realm.object_proto.clone()));
for name in ["log", "info", "debug", "warn", "error"] {
console.define_data(name, Value::Object(print.clone()));
}
global.define_data("console", Value::Object(console));
global.define_data("globalThis", Value::Object(global.clone()));
for (name, value) in [
("undefined", Value::Undefined),
("NaN", Value::Float(f64::NAN)),
("Infinity", Value::Float(f64::INFINITY)),
] {
global.define(name, Property::with_attributes(value, false, false));
}
}
fn js_print(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let mut line = String::new();
for (index, argument) in args.iter().enumerate() {
if index > 0 {
line.push(' ');
}
line.push_str(&crate::interp::debug_display(interp, argument));
}
line.push('\n');
interp.output.push_str(&line);
if let Some(sink) = interp.output_sink.as_mut() {
let _ = sink.write_all(line.as_bytes());
let _ = sink.flush();
}
Ok(Value::Undefined)
}
fn eval(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let source = match args.first() {
Some(Value::String(text)) => text.to_string_lossy().into_owned(),
Some(other) => return Ok(other.clone()),
None => return Ok(Value::Undefined),
};
interp.eval_in_global(&source)
}
fn gc(interp: &mut Interp<'_>, _this: Value, _args: &[Value]) -> JsResult<Value> {
interp.heap.collect();
crate::builtins::weak::drain_finalizers(interp)?;
Ok(Value::Undefined)
}
fn encode_uri_component(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let text = crate::builtins::to_string_wtf8(interp, &arg(args, 0))?;
let encoded = percent_encode(interp, &text, false)?;
Ok(interp.string(encoded))
}
fn encode_uri(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let text = crate::builtins::to_string_wtf8(interp, &arg(args, 0))?;
let encoded = percent_encode(interp, &text, true)?;
Ok(interp.string(encoded))
}
fn percent_encode(
interp: &mut Interp<'_>,
text: &crate::value::Wtf8,
keep_reserved: bool,
) -> JsResult<String> {
let mut out = String::new();
for point in text.code_points() {
let units = point.to_units();
if units.len() == 1 && (0xD800..0xE000).contains(&units[0]) {
return Err(uri_error(interp));
}
for byte in point.as_bytes() {
let unreserved = byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')'
);
let reserved = keep_reserved
&& matches!(
byte,
b';' | b'/' | b'?' | b':' | b'@' | b'&' | b'=' | b'+' | b'$' | b',' | b'#'
);
if unreserved || reserved {
out.push(*byte as char);
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
}
Ok(out)
}
fn decode_uri_component(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let text = crate::builtins::to_string_wtf8(interp, &arg(args, 0))?;
decode_percent(interp, &text, false)
}
fn decode_uri(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let text = crate::builtins::to_string_wtf8(interp, &arg(args, 0))?;
decode_percent(interp, &text, true)
}
fn decode_percent(
interp: &mut Interp<'_>,
text: &crate::value::Wtf8,
keep_reserved: bool,
) -> JsResult<Value> {
let bytes = text.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut pending: Vec<(u8, usize, usize)> = Vec::new();
let mut index = 0;
while index < bytes.len() {
if bytes[index] != b'%' {
flush_escapes(interp, &mut pending, &mut out, keep_reserved, bytes)?;
let width = sequence_width(bytes[index]);
let end = (index + width).min(bytes.len());
out.extend_from_slice(&bytes[index..end]);
index = end;
continue;
}
let (byte, next) = read_escape(bytes, index).ok_or_else(|| uri_error(interp))?;
pending.push((byte, index, next));
index = next;
}
flush_escapes(interp, &mut pending, &mut out, keep_reserved, bytes)?;
match crate::value::Wtf8::from_wtf8_bytes(&out) {
Some(decoded) => Ok(interp.string_wtf8(decoded)),
None => Err(uri_error(interp)),
}
}
fn flush_escapes(
interp: &mut Interp<'_>,
pending: &mut Vec<(u8, usize, usize)>,
out: &mut Vec<u8>,
keep_reserved: bool,
source: &[u8],
) -> JsResult<()> {
if pending.is_empty() {
return Ok(());
}
let decoded_bytes: Vec<u8> = pending.iter().map(|(byte, _, _)| *byte).collect();
let decoded = std::str::from_utf8(&decoded_bytes).map_err(|_| uri_error(interp))?;
let mut offset = 0;
for character in decoded.chars() {
if keep_reserved && character.is_ascii() && is_uri_reserved(character as u8) {
let (_, start, end) = pending[offset];
out.extend_from_slice(&source[start..end]);
} else {
out.extend_from_slice(character.to_string().as_bytes());
}
offset += character.len_utf8();
}
pending.clear();
Ok(())
}
fn is_uri_reserved(byte: u8) -> bool {
matches!(
byte,
b';' | b'/' | b'?' | b':' | b'@' | b'&' | b'=' | b'+' | b'$' | b',' | b'#'
)
}
fn sequence_width(lead: u8) -> usize {
match lead {
0x00..=0x7F => 1,
0xC0..=0xDF => 2,
0xE0..=0xEF => 3,
0xF0..=0xF7 => 4,
_ => 1,
}
}
fn read_escape(bytes: &[u8], index: usize) -> Option<(u8, usize)> {
let high = hex_digit(*bytes.get(index + 1)?)?;
let low = hex_digit(*bytes.get(index + 2)?)?;
Some((high * 16 + low, index + 3))
}
fn hex_digit(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn escape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let text = arg(args, 0).to_js_string();
let mut out = String::new();
for unit in text.encode_utf16() {
let kept = unit < 0x80
&& (char::from(unit as u8).is_ascii_alphanumeric()
|| matches!(unit as u8, b'@' | b'*' | b'_' | b'+' | b'-' | b'.' | b'/'));
if kept {
out.push(unit as u8 as char);
} else if unit < 0x100 {
out.push_str(&format!("%{unit:02X}"));
} else {
out.push_str(&format!("%u{unit:04X}"));
}
}
Ok(interp.string(out))
}
fn unescape(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let text = arg(args, 0).to_js_string();
let units: Vec<u16> = text.encode_utf16().collect();
let mut out: Vec<u16> = Vec::with_capacity(units.len());
let mut index = 0;
while index < units.len() {
if units[index] != b'%' as u16 {
out.push(units[index]);
index += 1;
continue;
}
if units.get(index + 1) == Some(&(b'u' as u16)) {
if let Some(hex) = units.get(index + 2..index + 6) {
let digits: String = hex.iter().map(|unit| *unit as u8 as char).collect();
if let Ok(unit) = u16::from_str_radix(&digits, 16) {
out.push(unit);
index += 6;
continue;
}
}
} else if let Some(hex) = units.get(index + 1..index + 3) {
let digits: String = hex.iter().map(|unit| *unit as u8 as char).collect();
if let Ok(byte) = u8::from_str_radix(&digits, 16) {
out.push(byte as u16);
index += 3;
continue;
}
}
out.push(units[index]);
index += 1;
}
Ok(Value::String(js_gc::Gc::new(
interp.heap,
crate::value::JsString::from_wtf8(crate::value::Wtf8::from_units(&out)),
)))
}
fn uri_error(interp: &Interp<'_>) -> crate::interp::Signal {
crate::interp::Signal::Throw(interp.make_error("URIError", "malformed URI sequence"))
}