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 [
("parseInt", 2, number::parse_int as NativeFn),
("parseFloat", 1, number::parse_float),
("isNaN", 1, number::global_is_nan),
("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);
}
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);
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 = arg(args, 0).to_js_string();
Ok(interp.string(percent_encode(&text, false)))
}
fn encode_uri(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let text = arg(args, 0).to_js_string();
Ok(interp.string(percent_encode(&text, true)))
}
fn percent_encode(text: &str, keep_reserved: bool) -> String {
let mut out = String::new();
for byte in text.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}"));
}
}
out
}
fn decode_uri_component(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let text = arg(args, 0).to_js_string();
decode_percent(interp, &text, false)
}
fn decode_uri(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
let text = arg(args, 0).to_js_string();
decode_percent(interp, &text, true)
}
fn decode_percent(interp: &mut Interp<'_>, text: &str, keep_reserved: bool) -> JsResult<Value> {
let bytes = text.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] != b'%' {
out.push(bytes[index]);
index += 1;
continue;
}
let decoded = read_escape(bytes, index).ok_or_else(|| uri_error(interp))?;
let (byte, next) = decoded;
if keep_reserved
&& matches!(
byte,
b';' | b'/' | b'?' | b':' | b'@' | b'&' | b'=' | b'+' | b'$' | b',' | b'#'
)
{
out.extend_from_slice(&bytes[index..next]);
} else {
out.push(byte);
}
index = next;
}
String::from_utf8(out)
.map(|text| interp.string(text))
.map_err(|_| uri_error(interp))
}
fn read_escape(bytes: &[u8], index: usize) -> Option<(u8, usize)> {
let hex = bytes.get(index + 1..index + 3)?;
let hex = std::str::from_utf8(hex).ok()?;
let byte = u8::from_str_radix(hex, 16).ok()?;
Some((byte, index + 3))
}
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"))
}