feat(codemode): cross strings to the host losslessly, unpaired surrogates included (HostString)

This commit is contained in:
Sebastian Herrlinger 2026-11-19 02:41:41 +01:00
parent 4c7e4da0d7
commit 6cfcfcf628
13 changed files with 315 additions and 125 deletions

View file

@ -1,6 +1,6 @@
{
"boundary": {
"samples": {"date":{"date":0},"invalidDate":{"date":"NaN"},"regexp":{"regexp":["a+\\/b","gi"]},"url":{"url":"https://user@a.test:8080/p%20a?q=1&r=%20#h"},"params":{"params":[["a","1"],["b","2"],["a","3"]]},"headers":{"headers":[["x-a","1, 3"],["x-b","2"]]},"bytes":{"bytes":[1,2,3]},"buffer":{"buffer":[104,105]},"arrayBuffer":{"arrayBuffer":[4,5]},"nested":{"object":[["when",{"date":1000000000000}],["links",{"array":[{"url":"https://b.test/x"}]}],["table",{"map":[[{"date":5},{"headers":[["k","v"]]}]]}],["tags",{"set":[{"bytes":[9]}]}],["failure",{"error":{"name":"RangeError","message":"bad","cause":{"date":7},"fields":[["at",{"url":"https://c.test/"}]]}}]]}},
"samples": {"date":{"date":0},"invalidDate":{"date":"NaN"},"regexp":{"regexp":["a+\\/b","gi"]},"url":{"url":"https://user@a.test:8080/p%20a?q=1&r=%20#h"},"params":{"params":[["a","1"],["b","2"],["a","3"]]},"headers":{"headers":[["x-a","1, 3"],["x-b","2"]]},"bytes":{"bytes":[1,2,3]},"buffer":{"buffer":[104,105]},"arrayBuffer":{"arrayBuffer":[4,5]},"nested":{"object":[["when",{"date":1000000000000}],["links",{"array":[{"url":"https://b.test/x"}]}],["table",{"map":[[{"date":5},{"headers":[["k","v"]]}]]}],["tags",{"set":[{"bytes":[9]}]}],["failure",{"error":{"name":"RangeError","message":"bad","cause":{"date":7},"fields":[["at",{"url":"https://c.test/"}]]}}]]},"lone":{"string":[97,55296,98]},"loneKeys":{"object":[[{"string":[56320]},{"string":[120,55357]}],["pair","😀"],["list",{"array":[{"string":[56319]}]}]]},"loneError":{"error":{"name":"Error","message":{"string":[98,97,100,32,55296]},"fields":[[{"string":[57343]},{"string":[55296]}]]}}},
"programs": [
{"code":"const o = { n: 1, list: [1], d: new Date(0), u: new URL(\"https://a.test/\") }; keep(o); o.n = 2; o.list.push(2); return o.n","outcome":{"ok":true,"value":2},"kept":[{"object":[["n",1],["list",{"array":[1]}],["d",{"date":0}],["u",{"url":"https://a.test/"}]]}]},
{"code":"const h = make(\"headers\"); h.set(\"x-a\", \"2\"); const back = keep(h); back.set(\"x-a\", \"3\"); return [h instanceof Headers, h.get(\"x-a\"), back === h, back.get(\"x-a\"), [...back], [...make(\"headers\")]]","outcome":{"ok":true,"value":[true,"2",false,"3",[["x-a","3"],["x-b","2"]],[["x-a","1, 3"],["x-b","2"]]]},"kept":[{"headers":[["x-a","2"],["x-b","2"]]}]},
@ -20,6 +20,11 @@
{"code":"try { keep(new Map().entries()) } catch (e) { return e.message }","outcome":{"ok":true,"value":"Argument 1 to keep contains an iterator, which cannot be passed to the host."},"kept":[]},
{"code":"try { keep({ p: Promise.resolve(1) }) } catch (e) { return e.message }","outcome":{"ok":true,"value":null},"kept":[{"object":[["p",1]]}]},
{"code":"return JSON.stringify([make(\"date\"), make(\"url\"), make(\"params\"), make(\"headers\"), make(\"bytes\"), make(\"buffer\"), make(\"regexp\")])","outcome":{"ok":true,"value":"[\"1970-01-01T00:00:00.000Z\",\"https://user@a.test:8080/p%20a?q=1&r=%20#h\",{},{\"x-a\":\"1, 3\",\"x-b\":\"2\"},{\"0\":1,\"1\":2,\"2\":3},{\"type\":\"Buffer\",\"data\":[104,105]},{}]"},"kept":[]},
{"code":"const s = \"a\\ud800b\"; const back = keep(s); return [back === s, back.length, back.charCodeAt(1), keep(\"\\udc00\") === \"\\udc00\", keep(\"\\ud83d\\ude00\") === \"\\ud83d\\ude00\", keep(\"\\ude00\\ud83d\").length]","outcome":{"ok":true,"value":[true,3,55296,true,true,2]},"kept":[{"string":[97,55296,98]},{"string":[56320]},"😀",{"string":[56832,55357]}]},
{"code":"const k = \"\\udc00\"; const back = keep({ [k]: \"x\\ud83d\", n: [\"\\udbff\"], m: new Map([[\"\\ud800\", new Set([\"\\udfff\"])]]) }); return [Object.keys(back)[0] === k, back[k] === \"x\\ud83d\", back.n[0] === \"\\udbff\", [...back.m.get(\"\\ud800\")][0] === \"\\udfff\"]","outcome":{"ok":true,"value":[true,true,true,true]},"kept":[{"object":[[{"string":[56320]},{"string":[120,55357]}],["n",{"array":[{"string":[56319]}]}],["m",{"map":[[{"string":[55296]},{"set":[{"string":[57343]}]}]]}]]}]},
{"code":"const e = new Error(\"bad \\ud800\"); e[\"\\udc00\"] = \"\\udfff\"; const back = keep(e); return [back.message === \"bad \\ud800\", back[\"\\udc00\"] === \"\\udfff\", back instanceof Error]","outcome":{"ok":true,"value":[true,true,true]},"kept":[{"error":{"name":"Error","message":{"string":[98,97,100,32,55296]},"fields":[[{"string":[56320]},{"string":[57343]}]]}}]},
{"code":"const l = make(\"lone\"); const o = make(\"loneKeys\"); const e = make(\"loneError\"); return [l === \"a\\ud800b\", l.length, Object.keys(o)[0] === \"\\udc00\", o[\"\\udc00\"] === \"x\\ud83d\", o.pair, o.list[0].charCodeAt(0), e.message === \"bad \\ud800\", e[\"\\udfff\"] === \"\\ud800\"]","outcome":{"ok":true,"value":[true,3,true,true,"😀",56319,true,true]},"kept":[]},
{"code":"const l = make(\"lone\"); return [l.isWellFormed(), l.toWellFormed(), encodeURIComponent(l.toWellFormed()), new TextEncoder().encode(l).length]","outcome":{"ok":true,"value":[false,"a<>b","a%EF%BF%BDb",5]},"kept":[]},
{"code":"keep({ f() {}, a: [1, () => 2, , 3], m: new Map([[\"k\", () => 1], [() => 2, \"v\"]]), s: new Set([() => 1, 2]), n: { g: Math.max, b: keep.bind(null), k: keep } }); keep(() => 1); keep([keep]); return 1","outcome":{"ok":true,"value":1},"kept":[{"object":[["a",{"array":[1,null,{"hole":true},3]}],["m",{"map":[["k",{"undefined":true}],[{"undefined":true},"v"]]}],["s",{"set":[{"undefined":true},2]}],["n",{"object":[]}]]},{"undefined":true},{"array":[null]}]},
{"code":"const later = (v) => (async () => { await null; return v })()\n keep({ a: Promise.resolve(1), b: [Promise.resolve(2), later(3)], m: new Map([[Promise.resolve(\"k\"), later(\"v\")]]), s: new Set([later(4)]) }); keep(later(5), 6); return 1","outcome":{"ok":true,"value":1},"kept":[{"object":[["a",1],["b",{"array":[2,3]}],["m",{"map":[["k","v"]]}],["s",{"set":[4]}]]},5]},
{"code":"const inner = (async () => { await null; return [() => 1, \"in\"] })(); keep({ outer: (async () => { await null; return { inner, f: () => 2 } })() }); return 1","outcome":{"ok":true,"value":1},"kept":[{"object":[["outer",{"object":[["inner",{"array":[null,"in"]}]]}]]}]},

View file

@ -76,6 +76,10 @@ const samples: Record<string, unknown> = {
tags: new Set([new Uint8Array([9])]),
failure: Object.assign(new RangeError("bad", { cause: new Date(7) }), { at: new URL("https://c.test/") }),
},
// Strings with unpaired surrogates, which have no UTF-8 form: as a value, a key, an error's message and field.
lone: "a\ud800b",
loneKeys: { "\udc00": "x\ud83d", pair: "\ud83d\ude00", list: ["\udbff"] },
loneError: Object.assign(new Error("bad \ud800"), { "\udfff": "\ud800" }),
}
const boundaryPrograms = [
`const o = { n: 1, list: [1], d: new Date(0), u: new URL("https://a.test/") }; keep(o); o.n = 2; o.list.push(2); return o.n`,
@ -97,6 +101,16 @@ const boundaryPrograms = [
`try { keep({ p: Promise.resolve(1) }) } catch (e) { return e.message }`,
`return JSON.stringify([make("date"), make("url"), make("params"), make("headers"), make("bytes"), make("buffer"), make("regexp")])`,
]
// Strings with unpaired surrogates cross both ways unchanged: the host sees, and gives back, the program's code units.
// The programs return what they compare, as the recording's JSON can't hold such a string.
boundaryPrograms.push(
`const s = "a\\ud800b"; const back = keep(s); return [back === s, back.length, back.charCodeAt(1), keep("\\udc00") === "\\udc00", keep("\\ud83d\\ude00") === "\\ud83d\\ude00", keep("\\ude00\\ud83d").length]`,
`const k = "\\udc00"; const back = keep({ [k]: "x\\ud83d", n: ["\\udbff"], m: new Map([["\\ud800", new Set(["\\udfff"])]]) }); return [Object.keys(back)[0] === k, back[k] === "x\\ud83d", back.n[0] === "\\udbff", [...back.m.get("\\ud800")][0] === "\\udfff"]`,
`const e = new Error("bad \\ud800"); e["\\udc00"] = "\\udfff"; const back = keep(e); return [back.message === "bad \\ud800", back["\\udc00"] === "\\udfff", back instanceof Error]`,
`const l = make("lone"); const o = make("loneKeys"); const e = make("loneError"); return [l === "a\\ud800b", l.length, Object.keys(o)[0] === "\\udc00", o["\\udc00"] === "x\\ud83d", o.pair, o.list[0].charCodeAt(0), e.message === "bad \\ud800", e["\\udfff"] === "\\ud800"]`,
`const l = make("lone"); return [l.isWellFormed(), l.toWellFormed(), encodeURIComponent(l.toWellFormed()), new TextEncoder().encode(l).length]`,
)
// What a host function receives under the runtime's translation: a function is left out (an object's key is skipped,
// an array's item is null, an argument is undefined, a Map's or Set's entry is undefined), a fulfilled promise is its
// value, and the call waits for one that hasn't fulfilled, then crosses its arguments again.

View file

@ -3,7 +3,7 @@
#![allow(dead_code)]
use psychoscript::{Failure, HostFunction, HostValue, Json, Namespace, Resolved};
use psychoscript::{Failure, HostFunction, HostString, HostValue, Json, Namespace, Resolved};
use serde_json::json;
/// The `tools` namespace of `conformance/reference.ts`: `tools.echo`, `tools.fail` and `tools.git.status`, all async;
@ -72,7 +72,7 @@ pub fn describe(v: &HostValue) -> Json {
json!({ "number": if *n > 0.0 { "Infinity" } else { "-Infinity" } })
}
HostValue::Number(n) => number(*n),
HostValue::String(s) => json!(s),
HostValue::String(s) => text(s),
HostValue::Function(f) => json!({ "function": f.name() }),
HostValue::Durable(_) | HostValue::Namespace(_) => json!({ "function": "" }),
HostValue::Date(t) if t.is_nan() => json!({ "date": "NaN" }),
@ -96,7 +96,7 @@ pub fn describe(v: &HostValue) -> Json {
HostValue::Error(e) => {
let mut error = serde_json::Map::new();
error.insert("name".into(), json!(e.name));
error.insert("message".into(), json!(e.message));
error.insert("message".into(), text(&e.message));
if let Some(cause) = &e.cause {
error.insert("cause".into(), describe(cause));
}
@ -105,7 +105,7 @@ pub fn describe(v: &HostValue) -> Json {
Json::Array(
e.fields
.iter()
.map(|(k, x)| json!([k, describe(x)]))
.map(|(k, x)| json!([text(k), describe(x)]))
.collect(),
),
);
@ -116,11 +116,20 @@ pub fn describe(v: &HostValue) -> Json {
}),
HostValue::Response(_) => json!({ "object": [] }),
HostValue::Object(fields) => json!({
"object": fields.iter().map(|(k, x)| json!([k, describe(x)])).collect::<Vec<_>>()
"object": fields.iter().map(|(k, x)| json!([text(k), describe(x)])).collect::<Vec<_>>()
}),
}
}
/// A string as `describe` writes it: the string itself, or `{ string: [code units] }` when it has an unpaired
/// surrogate, which JSON can't hold.
pub fn text(s: &HostString) -> Json {
match s.as_str() {
Some(s) => json!(s),
None => json!({ "string": s.to_utf16() }),
}
}
/// A number as JSON writes it: an integer when it is one.
fn number(n: f64) -> Json {
if n.fract() == 0.0 && n.abs() < 9.0e15 && !(n == 0.0 && n.is_sign_negative()) {

View file

@ -77,12 +77,14 @@ export const toolsGlobal = (ref: Reference) => {
* `{ number: "NaN" | "Infinity" | "-Infinity" }`, JSON primitives as they are, `{ function: name }`,
* `{ date: ms | "NaN" }`, `{ regexp: [source, flags] }`, `{ url: href }`, `{ params: [[k, v], ...] }`,
* `{ headers: [[k, v], ...] }`, `{ buffer: [bytes] }`, `{ bytes: [bytes] }`, `{ arrayBuffer: [bytes] }`,
* `{ map: [[k, v], ...] }`, `{ set: [v, ...] }`, `{ array: [v | { hole: true }, ...] }`,
* `{ map: [[k, v], ...] }`, `{ set: [v, ...] }`, `{ array: [v | { hole: true }, ...] }`, and a string, an object key
* or an error message with an unpaired surrogate as `{ string: [code units] }`,
* `{ error: { name, message, cause?, fields: [[k, v], ...] } }`, `{ object: [[k, v], ...] }`.
*/
export const describe = (v: unknown): unknown => {
if (v === undefined) return { undefined: true }
if (typeof v === "number" && !Number.isFinite(v)) return { number: String(v) }
if (typeof v === "string") return text(v)
if (v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean") return v
if (typeof v === "function") return { function: v.name }
if (v instanceof Date) return { date: Number.isNaN(v.getTime()) ? "NaN" : v.getTime() }
@ -102,11 +104,15 @@ export const describe = (v: unknown): unknown => {
return {
error: {
name: v.name,
message: v.message,
message: text(v.message),
...("cause" in v ? { cause: describe(v.cause) } : {}),
fields: Object.keys(v).map((k) => [k, describe(fields[k])]),
fields: Object.keys(v).map((k) => [text(k), describe(fields[k])]),
},
}
}
return { object: Object.entries(v as Record<string, unknown>).map(([k, x]) => [k, describe(x)]) }
return { object: Object.entries(v as Record<string, unknown>).map(([k, x]) => [text(k), describe(x)]) }
}
/** A string as `describe` writes it: itself, or `{ string: [code units] }` when it has an unpaired surrogate. */
const text = (s: string): unknown =>
s.isWellFormed() ? s : { string: Array.from({ length: s.length }, (_, i) => s.charCodeAt(i)) }

View file

@ -10,8 +10,8 @@ use rustc_hash::FxHashMap;
use crate::exec::{BoxFuture, Tasks, block_on};
use crate::host_function::{
Body, DurableCall, DurableFunction, HostError, HostFunction, HostResult, HostValue, Namespace,
Resolved, Returned, SnapshotHooks,
Body, DurableCall, DurableFunction, HostError, HostFunction, HostResult, HostString, HostValue,
Namespace, Resolved, Returned, SnapshotHooks,
};
use crate::object::*;
use crate::runtime::{Run, Translate, TranslateFunctions, TranslatePromises};
@ -96,8 +96,6 @@ pub struct Settled {
pub label: String,
/// The global host function whose `snapshot` hooks save functions in the value, by label.
pub owner: Option<String>,
/// Whether its strings are run text already (`HostFunction::carrier`).
pub carrier: bool,
/// The source offset of the call, where an error converting its value points.
pub site: Option<u32>,
}
@ -107,14 +105,12 @@ impl Settlement {
result: HostResult,
label: String,
owner: Option<String>,
carrier: bool,
site: Option<u32>,
) -> Self {
Settlement::Host(Box::new(Settled {
result,
label,
owner,
carrier,
site,
}))
}
@ -320,8 +316,6 @@ pub struct RunHost<'rt> {
pub(crate) epoch: crate::streaming::Epoch,
/// The VM's fuel counters, which it checks only when its step budget runs out.
pub(crate) meter: Meter,
/// Set while a carrier result (`HostFunction::carrier`) crosses in.
pub(crate) carrier: bool,
}
/// A call in flight a resumed run starts again: its promise, id, label, path, arguments, owner, site, and how.
@ -403,7 +397,6 @@ impl<'rt> RunHost<'rt> {
namespaces: FxHashMap::default(),
host_namespaces: FxHashMap::default(),
epoch: Default::default(),
carrier: false,
meter: Meter {
start: crate::vm::HANDOVER_FUEL,
handover: crate::vm::HANDOVER_FUEL,
@ -658,14 +651,11 @@ pub fn settle(vm: &mut Vm, p: Id, s: Settlement) {
result,
label,
owner,
carrier,
site,
} = *settled;
match result {
Ok(v) => {
vm.host.carrier = carrier;
let v = result_from_host(vm, v, &label, owner.as_deref());
vm.host.carrier = false;
match v {
Ok(v) => vm.fulfill(p, v),
Err(e) => {
@ -861,9 +851,9 @@ fn call_host(vm: &mut Vm, f: &Callee, args: &[Value], target: Target, callee: Va
Returned::Pending(work) => {
let site = vm.call_offset();
let p = vm.new_promise();
let (label, owner, carrier) = (target.label.clone(), target.owner.clone(), f.carrier);
let (label, owner) = (target.label.clone(), target.owner.clone());
let future: BoxFuture<'_, Settlement> =
Box::pin(async move { Settlement::host(work.await, label, owner, carrier, site) });
Box::pin(async move { Settlement::host(work.await, label, owner, site) });
let in_flight = InFlight {
promise: p,
call: call_id,
@ -951,10 +941,9 @@ fn spawn_call(vm: &mut Vm, p: Id, f: &Callee, mut r: Restart, holds_functions: b
false => (CallKind::Blocking, std::mem::take(&mut r.args)),
};
let work = body(args, call);
let carrier = f.carrier;
(
kind,
Box::pin(async move { Settlement::host(work.await, label, owner, carrier, site) }),
Box::pin(async move { Settlement::host(work.await, label, owner, site) }),
)
}
Callee::Durable(d) => {
@ -985,7 +974,7 @@ fn spawn_call(vm: &mut Vm, p: Id, f: &Callee, mut r: Restart, holds_functions: b
}
Err(e) => Err(e),
};
Settlement::host(result, label, owner, false, site)
Settlement::host(result, label, owner, site)
});
(CallKind::Durable(data, d.clone(), durable), future)
}
@ -1260,9 +1249,9 @@ fn to_host(
Value::Bool(b) => return Ok(Some(HostValue::Bool(*b))),
Value::Num(n) => return Ok(Some(HostValue::Number(*n))),
Value::Str(s) => {
return Ok(Some(HostValue::String(
crate::strings::host_text(vm.text(*s)).into_owned(),
)));
return Ok(Some(HostValue::String(HostString::from_run_text(
vm.text(*s),
))));
}
Value::Sym(_) => {
let msg = format!(
@ -1367,7 +1356,7 @@ fn to_host(
let name = crate::cross::host_error_name(vm, id, name);
let mut error = HostError::named(
crate::strings::host_text(&name).into_owned(),
crate::strings::host_text(&message).into_owned(),
HostString::from_run_text(&message),
);
let cause_key = vm.names.cause;
// A field that cannot cross is left behind, so the error itself always arrives.
@ -1389,8 +1378,8 @@ fn to_host(
}
}
for (k, val) in vm.own_entries(id) {
let key = crate::strings::host_text(vm.atoms.text(k)).into_owned();
if crate::cross::uncrossed(&key) || k == cause_key {
let key = HostString::from_run_text(vm.atoms.text(k));
if key.as_str().is_some_and(crate::cross::uncrossed) || k == cause_key {
continue;
}
if let Some(item) = left_behind(vm, &val, cx)? {
@ -1402,7 +1391,7 @@ fn to_host(
_ => {
let mut out = Vec::new();
for (k, val) in vm.own_entries(id) {
let key = crate::strings::host_text(vm.atoms.text(k)).into_owned();
let key = HostString::from_run_text(vm.atoms.text(k));
if key == "__proto__" {
continue;
}
@ -1438,8 +1427,7 @@ fn from_host(
HostValue::Null => Value::Null,
HostValue::Bool(b) => Value::Bool(*b),
HostValue::Number(n) => Value::Num(*n),
HostValue::String(s) if vm.host.carrier => vm.str_val(s),
HostValue::String(s) => vm.string_val(crate::strings::external_text(s.clone())),
HostValue::String(s) => vm.string_val(s.to_run_text()),
HostValue::Function(f) => {
// A global host function with `snapshot` hooks saves what it returns; a function inside such a value
// saves with the same hooks.
@ -1495,8 +1483,15 @@ fn from_host(
HostValue::Object(fields) => {
let id = vm.new_object();
for (k, item) in fields {
let val = from_host(vm, item, &next(k), &place.child(Some(k)), depth + 1)?;
let key = vm.atoms.intern(k);
let shown = k.to_string_lossy();
let val = from_host(
vm,
item,
&next(&shown),
&place.child(Some(&shown)),
depth + 1,
)?;
let key = vm.atoms.intern(&k.to_run_text());
vm.define(id, key, val);
}
Value::Obj(id)
@ -1574,7 +1569,7 @@ fn from_host(
}
_ => vm.realm.error_proto,
};
let err = vm.make_error(proto, &e.message);
let err = vm.make_error(proto, &e.message.to_run_text());
if let Value::Obj(id) = err {
if let Some(cause) = &e.cause
&& let Ok(c) =
@ -1586,7 +1581,7 @@ fn from_host(
for (k, item) in &e.fields {
if matches!(
k.as_str(),
"stack" | "message" | "constructor" | "toString" | "__proto__"
Some("stack" | "message" | "constructor" | "toString" | "__proto__")
) {
continue;
}
@ -1596,8 +1591,11 @@ fn from_host(
) {
continue;
}
if let Ok(val) = from_host(vm, item, &next(k), &Place::default(), depth + 1) {
let key = vm.atoms.intern(k);
let shown = k.to_string_lossy();
if let Ok(val) =
from_host(vm, item, &next(&shown), &Place::default(), depth + 1)
{
let key = vm.atoms.intern(&k.to_run_text());
vm.define(id, key, val);
}
}
@ -1658,12 +1656,9 @@ fn response_from_host(
None => Value::Null,
};
let fields = [
("url", HostValue::String(response.url.clone())),
("url", HostValue::from(response.url.as_str())),
("status", HostValue::Number(response.status as f64)),
(
"statusText",
HostValue::String(response.status_text.clone()),
),
("statusText", HostValue::from(response.status_text.as_str())),
("ok", HostValue::Bool(response.ok())),
("headers", HostValue::Headers(response.headers.clone())),
];

View file

@ -16,6 +16,140 @@ use crate::Json;
use crate::exec::BoxFuture;
use crate::host::RunId;
/// A string crossing the boundary: any string a program can hold, including one with an unpaired surrogate, which
/// has no UTF-8 form. It keeps such a string's UTF-16 code units, so a host sees and returns exactly what the program
/// had; [`HostString::to_string_lossy`] gives a Rust `String` when one is wanted, with U+FFFD for each unpaired
/// surrogate.
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct HostString(Text);
#[derive(Clone, PartialEq, Eq, Hash)]
enum Text {
Utf8(String),
/// Code units holding at least one unpaired surrogate.
Utf16(Box<[u16]>),
}
impl Default for Text {
fn default() -> Self {
Text::Utf8(String::new())
}
}
impl HostString {
/// The string of UTF-16 code units, well formed or not.
pub fn from_utf16(units: &[u16]) -> Self {
match String::from_utf16(units) {
Ok(s) => HostString(Text::Utf8(s)),
Err(_) => HostString(Text::Utf16(units.into())),
}
}
/// The string as UTF-8, when it has no unpaired surrogate.
pub fn as_str(&self) -> Option<&str> {
match &self.0 {
Text::Utf8(s) => Some(s),
Text::Utf16(_) => None,
}
}
/// Whether it has no unpaired surrogate, so it has a UTF-8 form.
pub fn is_well_formed(&self) -> bool {
matches!(self.0, Text::Utf8(_))
}
/// The string as UTF-8, with U+FFFD for each unpaired surrogate.
pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
match &self.0 {
Text::Utf8(s) => std::borrow::Cow::Borrowed(s),
Text::Utf16(units) => std::borrow::Cow::Owned(String::from_utf16_lossy(units)),
}
}
/// The string's UTF-16 code units.
pub fn to_utf16(&self) -> std::borrow::Cow<'_, [u16]> {
match &self.0 {
Text::Utf8(s) => std::borrow::Cow::Owned(s.encode_utf16().collect()),
Text::Utf16(units) => std::borrow::Cow::Borrowed(units),
}
}
/// The string as UTF-8 when it is well formed, or itself.
pub fn into_string(self) -> Result<String, Self> {
match self.0 {
Text::Utf8(s) => Ok(s),
text => Err(HostString(text)),
}
}
/// The text a run's string has (its carrier form: see `strings`).
pub(crate) fn from_run_text(text: &str) -> Self {
if !crate::strings::has_mark(text) {
return HostString(Text::Utf8(text.to_owned()));
}
Self::from_utf16(&crate::strings::units_of(text))
}
/// The string as a run's text: its carrier form when it has an unpaired surrogate or a `MARK`.
pub(crate) fn to_run_text(&self) -> String {
match &self.0 {
Text::Utf8(s) => crate::strings::external_text(s.clone()),
Text::Utf16(units) => crate::strings::from_units(units),
}
}
}
impl From<String> for HostString {
fn from(s: String) -> Self {
HostString(Text::Utf8(s))
}
}
impl From<&str> for HostString {
fn from(s: &str) -> Self {
HostString(Text::Utf8(s.to_owned()))
}
}
impl From<&String> for HostString {
fn from(s: &String) -> Self {
HostString(Text::Utf8(s.clone()))
}
}
impl PartialEq<str> for HostString {
fn eq(&self, other: &str) -> bool {
self.as_str() == Some(other)
}
}
impl PartialEq<&str> for HostString {
fn eq(&self, other: &&str) -> bool {
self.as_str() == Some(*other)
}
}
impl PartialEq<String> for HostString {
fn eq(&self, other: &String) -> bool {
self.as_str() == Some(other.as_str())
}
}
impl fmt::Display for HostString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_string_lossy())
}
}
impl fmt::Debug for HostString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
Text::Utf8(s) => fmt::Debug::fmt(s, f),
Text::Utf16(units) => write!(f, "HostString::from_utf16(&{units:?})"),
}
}
}
/// A value on the host's side of the boundary.
#[derive(Clone, Debug, Default)]
pub enum HostValue {
@ -24,10 +158,10 @@ pub enum HostValue {
Null,
Bool(bool),
Number(f64),
String(String),
String(HostString),
/// `None` is a hole.
Array(Vec<Option<HostValue>>),
Object(Vec<(String, HostValue)>),
Object(Vec<(HostString, HostValue)>),
Map(Vec<(HostValue, HostValue)>),
Set(Vec<HostValue>),
Function(HostFunction),
@ -62,7 +196,7 @@ pub enum HostValue {
}
impl HostValue {
pub fn object<K: Into<String>>(fields: impl IntoIterator<Item = (K, HostValue)>) -> Self {
pub fn object<K: Into<HostString>>(fields: impl IntoIterator<Item = (K, HostValue)>) -> Self {
HostValue::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
}
@ -80,7 +214,7 @@ impl HostValue {
pub fn as_str(&self) -> Option<&str> {
match self {
HostValue::String(s) => Some(s),
HostValue::String(s) => s.as_str(),
_ => None,
}
}
@ -98,11 +232,11 @@ impl HostValue {
Json::Null => HostValue::Null,
Json::Bool(b) => HostValue::Bool(*b),
Json::Number(n) => HostValue::Number(n.as_f64().unwrap_or(f64::NAN)),
Json::String(s) => HostValue::String(s.clone()),
Json::String(s) => HostValue::String(s.into()),
Json::Array(items) => HostValue::array(items.iter().map(HostValue::from_json)),
Json::Object(map) => HostValue::Object(
map.iter()
.map(|(k, v)| (k.clone(), HostValue::from_json(v)))
.map(|(k, v)| (k.into(), HostValue::from_json(v)))
.collect(),
),
}
@ -122,7 +256,7 @@ impl HostValue {
HostValue::Number(n) => {
serde_json::Number::from_f64(*n).map_or(Json::Null, Json::Number)
}
HostValue::String(s) => Json::String(s.clone()),
HostValue::String(s) => Json::String(s.to_string_lossy().into_owned()),
HostValue::Array(items) => Json::Array(
items
.iter()
@ -142,7 +276,7 @@ impl HostValue {
HostValue::Object(fields) => Json::Object(
fields
.iter()
.filter_map(|(k, v)| v.to_json().map(|j| (k.clone(), j)))
.filter_map(|(k, v)| v.to_json().map(|j| (k.to_string_lossy().into_owned(), j)))
.collect(),
),
HostValue::Map(_)
@ -167,7 +301,10 @@ impl HostValue {
HostValue::Error(e) => {
let mut map = serde_json::Map::new();
map.insert("name".into(), Json::String(e.name.clone()));
map.insert("message".into(), Json::String(e.message.clone()));
map.insert(
"message".into(),
Json::String(e.message.to_string_lossy().into_owned()),
);
Json::Object(map)
}
HostValue::Failure(f) => {
@ -179,13 +316,13 @@ impl HostValue {
impl From<&str> for HostValue {
fn from(s: &str) -> Self {
HostValue::String(s.to_owned())
HostValue::String(s.into())
}
}
impl From<String> for HostValue {
fn from(s: String) -> Self {
HostValue::String(s)
HostValue::String(s.into())
}
}
@ -235,19 +372,19 @@ impl From<Failure> for HostValue {
#[derive(Clone, Debug, Default)]
pub struct HostError {
pub name: String,
pub message: String,
pub message: HostString,
pub cause: Option<Box<HostValue>>,
pub fields: Vec<(String, HostValue)>,
pub fields: Vec<(HostString, HostValue)>,
}
impl HostError {
/// An `Error`.
pub fn new(message: impl Into<String>) -> Self {
pub fn new(message: impl Into<HostString>) -> Self {
Self::named("Error", message)
}
/// An error of a built-in type: `TypeError`, `RangeError`, `SyntaxError`, ... Other names become `Error`.
pub fn named(name: impl Into<String>, message: impl Into<String>) -> Self {
pub fn named(name: impl Into<String>, message: impl Into<HostString>) -> Self {
Self {
name: name.into(),
message: message.into(),
@ -261,7 +398,7 @@ impl HostError {
self
}
pub fn with_field(mut self, key: impl Into<String>, value: impl Into<HostValue>) -> Self {
pub fn with_field(mut self, key: impl Into<HostString>, value: impl Into<HostValue>) -> Self {
self.fields.push((key.into(), value.into()));
self
}
@ -269,7 +406,7 @@ impl HostError {
impl fmt::Display for HostError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.message.is_empty() {
if self.message == "" {
f.write_str(&self.name)
} else {
write!(f, "{}: {}", self.name, self.message)
@ -442,8 +579,6 @@ pub struct HostFunction {
pub(crate) snapshot: Option<SnapshotHooks>,
/// Whether its name is its own, even when empty; otherwise an unnamed function is named by where it is.
pub(crate) own_name: bool,
/// Its results' strings are already run text, lone surrogates in carrier form (see `strings::from_units`).
pub(crate) carrier: bool,
}
impl HostFunction {
@ -506,7 +641,6 @@ impl HostFunction {
takes_functions: false,
snapshot: None,
own_name: false,
carrier: false,
}
}

View file

@ -40,7 +40,7 @@ pub use diagnostic::{Diagnostic, DiagnosticKind, Interrupted, Limits};
pub use exec::BoxFuture;
pub use host_function::{
Call, CallType, DurableCall, DurableFunction, Failure, HostError, HostFunction, HostResult,
HostValue, Namespace, Resolved, Returned, SnapshotHooks,
HostString, HostValue, Namespace, Resolved, Returned, SnapshotHooks,
};
pub use program::{Program, RunOutcome, RunningCall, SuspendError, Suspended, Suspender};
pub use runtime::{

View file

@ -780,7 +780,6 @@ impl Enc<'_, '_> {
result,
label,
owner,
carrier,
site,
} = h.as_ref();
let (ok, v) = match result {
@ -794,17 +793,7 @@ impl Enc<'_, '_> {
}
_ => (false, v.clone()),
};
json!([
p,
"host",
ok,
label,
owner,
hooked,
host_value(&data),
carrier,
site
])
json!([p, "host", ok, label, owner, hooked, host_value(&data), site])
}
Settlement::Interrupted => json!([p, "interrupted"]),
})
@ -977,7 +966,7 @@ fn host_value(v: &HostValue) -> J {
HostValue::Null => J::Null,
HostValue::Bool(b) => J::Bool(*b),
HostValue::Number(n) => json!(["n", num(*n)]),
HostValue::String(s) => J::from(s.as_str()),
HostValue::String(s) => text(s),
HostValue::Array(items) => json!([
"a",
items
@ -989,7 +978,7 @@ fn host_value(v: &HostValue) -> J {
"o",
fields
.iter()
.map(|(k, v)| json!([k, host_value(v)]))
.map(|(k, v)| json!([text(k), host_value(v)]))
.collect::<Vec<_>>()
]),
HostValue::Map(entries) => json!([
@ -1015,11 +1004,11 @@ fn host_value(v: &HostValue) -> J {
HostValue::Error(e) => json!([
"e",
e.name,
e.message,
text(&e.message),
e.cause.as_ref().map_or(J::Null, |c| host_value(c)),
e.fields
.iter()
.map(|(k, v)| json!([k, host_value(v)]))
.map(|(k, v)| json!([text(k), host_value(v)]))
.collect::<Vec<_>>()
]),
}
@ -1048,12 +1037,36 @@ fn lost_path(j: &J, label: &str) -> Option<String> {
}
}
/// A host string as saved: JSON text when well formed, else its UTF-16 code units.
fn text(s: &crate::HostString) -> J {
match s.as_str() {
Some(s) => J::from(s),
None => json!(["s16", s.to_utf16()]),
}
}
fn text_from(j: &J) -> R<crate::HostString> {
match j {
J::String(s) => Ok(s.into()),
J::Array(a) if a.first().and_then(J::as_str) == Some("s16") => {
let units = list(a.get(1))?
.iter()
.map(|u| u.as_u64().and_then(|u| u16::try_from(u).ok()))
.collect::<Option<Vec<u16>>>()
.ok_or_else(|| invalid("a string's code units are malformed."))?;
Ok(crate::HostString::from_utf16(&units))
}
_ => Err(invalid("a string is malformed.")),
}
}
fn host_value_from(j: &J) -> R<HostValue> {
Ok(match j {
J::Null => HostValue::Null,
J::Bool(b) => HostValue::Bool(*b),
J::String(s) => HostValue::String(s.clone()),
J::String(s) => HostValue::String(s.into()),
J::Array(a) => match a.first().and_then(J::as_str) {
Some("s16") => HostValue::String(text_from(j)?),
Some("u") => HostValue::Undefined,
Some("n") => HostValue::Number(unnum(a.get(1).unwrap_or(&J::Null))?),
Some("a") => HostValue::Array(
@ -1068,7 +1081,7 @@ fn host_value_from(j: &J) -> R<HostValue> {
Some("o") => HostValue::Object(
list(a.get(1))?
.iter()
.map(|p| Ok((string(at(p, 0)?)?, host_value_from(at(p, 1)?)?)))
.map(|p| Ok((text_from(at(p, 0)?)?, host_value_from(at(p, 1)?)?)))
.collect::<R<_>>()?,
),
Some("m") => HostValue::Map(
@ -1104,14 +1117,14 @@ fn host_value_from(j: &J) -> R<HostValue> {
Some("resp") => HostValue::Undefined,
Some("e") => HostValue::Error(Box::new(HostError {
name: string(at(j, 1)?)?,
message: string(at(j, 2)?)?,
message: text_from(at(j, 2)?)?,
cause: match at(j, 3)? {
J::Null => None,
c => Some(Box::new(host_value_from(c)?)),
},
fields: list(a.get(4))?
.iter()
.map(|p| Ok((string(at(p, 0)?)?, host_value_from(at(p, 1)?)?)))
.map(|p| Ok((text_from(at(p, 0)?)?, host_value_from(at(p, 1)?)?)))
.collect::<R<_>>()?,
})),
_ => return Err(invalid("a host value has an unknown tag.")),
@ -2038,7 +2051,7 @@ fn restore_settlement(vm: &mut Vm, dec: &Dec, j: &J) -> R<(Id, Settlement)> {
let saved = at(j, 6)?;
// The reference saves a value with no data form (a live response) as a `Lost`, which can't cross into the
// program once the run resumes: the call fails there, at the place that names it.
let site = j.get(8).and_then(J::as_u64).map(|s| s as u32);
let site = j.get(7).and_then(J::as_u64).map(|s| s as u32);
if ok && let Some(at_label) = lost_path(saved, &label) {
let message = format!("{at_label} produced a Lost, which the program cannot hold.");
return Ok((p, Settlement::Lost(message, site)));
@ -2047,8 +2060,7 @@ fn restore_settlement(vm: &mut Vm, dec: &Dec, j: &J) -> R<(Id, Settlement)> {
if hooked && let Some(owner) = &owner {
v = decode(vm, owner, v)?;
}
let carrier = j.get(7).and_then(J::as_bool).unwrap_or(false);
Settlement::host(if ok { Ok(v) } else { Err(v) }, label, owner, carrier, site)
Settlement::host(if ok { Ok(v) } else { Err(v) }, label, owner, site)
}
Some("lost") => Settlement::Lost(
string(at(j, 2)?)?,

View file

@ -434,7 +434,7 @@ impl Stream {
fn consumed(kind: Consume, buf: Vec<u8>) -> HostResult {
match kind {
Consume::Bytes | Consume::ArrayBuffer => Ok(HostValue::Bytes(buf)),
Consume::Text => Ok(HostValue::String(decode(&buf))),
Consume::Text => Ok(HostValue::String(decode(&buf).into())),
Consume::Json => parse_json(&decode(&buf)),
}
}
@ -524,7 +524,7 @@ pub(crate) fn surface(response: &StreamingResponse, epoch: &Epoch) -> Surface {
.map(|(key, kind)| {
let stream = response.body.clone();
let epoch = epoch.clone();
let mut f = HostFunction::internal_async("", 0, move |_| {
let f = HostFunction::internal_async("", 0, move |_| {
let call = stream
.as_ref()
.map(|s| op_call(s, &epoch, Op::Consume(kind)));
@ -541,7 +541,6 @@ pub(crate) fn surface(response: &StreamingResponse, epoch: &Epoch) -> Surface {
}
}
});
f.carrier = matches!(kind, Consume::Json);
(key, f)
})
.collect();
@ -651,7 +650,7 @@ fn reader_object(stream: &Arc<Mutex<Stream>>, epoch: &Epoch, reader: u64) -> Hos
/// Why the reference's host runtime can't parse `text` as JSON, as its `JSON.parse` says it (`JSON Parse error: ...`).
pub(crate) fn json_parse_error(text: &str) -> String {
match parse_json(text) {
Err(HostValue::Error(e)) => e.message,
Err(HostValue::Error(e)) => e.message.to_string_lossy().into_owned(),
_ => "JSON Parse error: Unable to parse JSON string".into(),
}
}
@ -834,7 +833,7 @@ impl Json<'_> {
fn value(&mut self, tok: Tok) -> J<HostValue> {
match tok {
Tok::Eof => Err("Unexpected EOF".into()),
Tok::Str(s) => Ok(HostValue::String(s)),
Tok::Str(s) => Ok(HostValue::String(crate::HostString::from_run_text(&s))),
Tok::Num(n) => Ok(HostValue::Number(n)),
Tok::Lit(v) => Ok(v),
Tok::Ident(name) => Err(format!("Unexpected identifier \"{name}\"")),
@ -861,10 +860,10 @@ impl Json<'_> {
}
}
Tok::Punct(b'{') => {
let mut fields: Vec<(String, HostValue)> = Vec::new();
let mut fields: Vec<(crate::HostString, HostValue)> = Vec::new();
let mut key = match self.lex()? {
Tok::Punct(b'}') => return Ok(HostValue::Object(fields)),
Tok::Str(s) => s,
Tok::Str(s) => crate::HostString::from_run_text(&s),
_ => return Err("Expected '}'".into()),
};
loop {
@ -881,7 +880,7 @@ impl Json<'_> {
}
match self.lex()? {
Tok::Punct(b',') => match self.lex()? {
Tok::Str(s) => key = s,
Tok::Str(s) => key = crate::HostString::from_run_text(&s),
_ => return Err("Property name must be a string literal".into()),
},
Tok::Punct(b'}') => return Ok(HostValue::Object(fields)),

View file

@ -3,8 +3,8 @@
use std::sync::{Arc, Mutex};
use psychoscript::{
DiagnosticKind, HostFunction, HostValue, Json, Limits, ProgramOptions, Runtime, Translate,
TranslateFunctions,
DiagnosticKind, HostFunction, HostString, HostValue, Json, Limits, ProgramOptions, Runtime,
Translate, TranslateFunctions,
};
use serde_json::json;
@ -177,23 +177,24 @@ fn string_building_does_not_alias() {
/// Rust text can't hold a lone surrogate, so where the reference hands the host and the outcome the surrogate
/// itself, these get U+FFFD; inside the program it stays a surrogate.
#[test]
fn lone_surrogates_reach_the_host_as_replacement_characters() {
fn lone_surrogates_reach_the_host_unchanged() {
let (rt, seen) = echo();
let outcome = run(
&rt,
r#"const h = "\ud83d"
console.log("log " + h)
const back = echo({ [h]: h + "x" })
return { s: h, pair: h + "\ude00", back, keys: Object.keys(back).length, error: (() => { try { throw new Error(h) } catch (e) { return e.message } })() }"#,
return [Object.keys(back)[0] === h, back[h] === h + "x", back[h].length, (h + "\ude00").isWellFormed()]"#,
);
assert_eq!(
outcome.result.unwrap(),
json!({ "s": "\u{fffd}", "pair": "\u{1f600}", "back": { "\u{fffd}": "\u{fffd}x" }, "keys": 1, "error": "\u{fffd}" })
);
assert_eq!(outcome.logs, vec!["log \u{fffd}"]);
assert_eq!(
seen.lock().unwrap()[0].to_json(),
Some(json!({ "\u{fffd}": "\u{fffd}x" }))
assert_eq!(outcome.result.unwrap(), json!([true, true, 2, true]));
let seen = seen.lock().unwrap()[0].clone();
let HostValue::Object(fields) = seen else {
panic!("not an object");
};
assert_eq!(fields[0].0, HostString::from_utf16(&[0xd83d]));
assert!(!fields[0].0.is_well_formed());
assert_eq!(fields[0].0.to_string_lossy(), "\u{fffd}");
assert!(
matches!(&fields[0].1, HostValue::String(s) if s.to_utf16().as_ref() == [0xd83d, u16::from(b'x')])
);
}

View file

@ -5,8 +5,8 @@
use std::sync::{Arc, Mutex};
use psychoscript::{
HostError, HostFunction, HostValue, Json, Returned, Runtime, Translate, TranslateFunctions,
TranslatePromises,
HostError, HostFunction, HostString, HostValue, Json, Returned, Runtime, Translate,
TranslateFunctions, TranslatePromises,
};
use serde_json::json;
@ -62,6 +62,21 @@ fn bytes(j: &Json) -> Vec<u8> {
.collect()
}
/// A string as `describe` writes it: itself, or `{ string: [code units] }`.
fn text_of(j: &Json) -> HostString {
match j {
Json::String(s) => s.into(),
j => HostString::from_utf16(
&j["string"]
.as_array()
.unwrap()
.iter()
.map(|u| u.as_u64().unwrap() as u16)
.collect::<Vec<_>>(),
),
}
}
/// A host value from the data `describe` writes: the generator's samples, as the host gives them.
fn undescribe(j: &Json) -> HostValue {
let Json::Object(map) = j else {
@ -77,6 +92,7 @@ fn undescribe(j: &Json) -> HostValue {
flags: v[1].as_str().unwrap().to_owned(),
},
"url" => HostValue::Url(v.as_str().unwrap().to_owned()),
"string" => HostValue::String(text_of(j)),
"params" => HostValue::SearchParams(pairs(v)),
"headers" => HostValue::Headers(pairs(v)),
"bytes" | "arrayBuffer" => HostValue::Bytes(bytes(v)),
@ -97,13 +113,12 @@ fn undescribe(j: &Json) -> HostValue {
.collect(),
),
"error" => {
let mut e =
HostError::named(v["name"].as_str().unwrap(), v["message"].as_str().unwrap());
let mut e = HostError::named(v["name"].as_str().unwrap(), text_of(&v["message"]));
if let Some(cause) = v.get("cause") {
e = e.with_cause(undescribe(cause));
}
for f in v["fields"].as_array().unwrap() {
e = e.with_field(f[0].as_str().unwrap(), undescribe(&f[1]));
e = e.with_field(text_of(&f[0]), undescribe(&f[1]));
}
e.into()
}
@ -111,7 +126,7 @@ fn undescribe(j: &Json) -> HostValue {
v.as_array()
.unwrap()
.iter()
.map(|f| (f[0].as_str().unwrap().to_owned(), undescribe(&f[1])))
.map(|f| (text_of(&f[0]), undescribe(&f[1])))
.collect(),
),
other => panic!("unknown sample tag {other}"),

View file

@ -231,15 +231,15 @@ fn a_program_error_crosses_with_its_name_message_cause_and_data() {
let HostValue::Error(e) = &held.lock().unwrap()[0] else {
panic!("not an error");
};
assert_eq!((e.name.as_str(), e.message.as_str()), ("Error", "m"));
assert_eq!((e.name.as_str(), e.message.as_str()), ("Error", Some("m")));
let Some(HostValue::Error(cause)) = e.cause.as_deref() else {
panic!("no cause");
};
assert_eq!(
(cause.name.as_str(), cause.message.as_str()),
("RangeError", "root")
("RangeError", Some("root"))
);
let keys: Vec<&str> = e.fields.iter().map(|(k, _)| k.as_str()).collect();
let keys: Vec<&str> = e.fields.iter().filter_map(|(k, _)| k.as_str()).collect();
assert_eq!(keys, ["code", "detail"]);
}
@ -369,7 +369,7 @@ fn a_host_function_passed_back_arrives_as_itself_wherever_it_sits() {
let name = args[0].as_str().unwrap_or_default().to_owned();
let text = HostFunction::new(|_, _| HostValue::from("text"))
.named(format!("text:{name}"));
HostValue::object([("name", HostValue::String(name)), ("text", text.into())])
HostValue::object([("name", HostValue::from(name)), ("text", text.into())])
}),
),
(
@ -379,7 +379,7 @@ fn a_host_function_passed_back_arrives_as_itself_wherever_it_sits() {
Some(HostValue::Function(f)) => f.name().to_owned(),
_ => "no function".to_owned(),
};
Ok(HostValue::array([args[0].clone(), HostValue::String(name)]))
Ok(HostValue::array([args[0].clone(), HostValue::from(name)]))
})
.takes_functions(),
),

View file

@ -78,7 +78,7 @@ fn respond(spec: &HostValue, log: &Log) -> HostValue {
.into_iter()
.flatten()
.map(|c| match c {
HostValue::String(s) => s.into_bytes(),
HostValue::String(s) => s.to_string_lossy().into_owned().into_bytes(),
HostValue::Array(bytes) => bytes
.into_iter()
.flatten()
@ -102,7 +102,7 @@ fn respond(spec: &HostValue, log: &Log) -> HostValue {
}
if let HostValue::Object(headers) = get("headers") {
for (k, v) in headers {
response = response.with_header(k, v.as_str().unwrap());
response = response.with_header(k.to_string_lossy(), v.as_str().unwrap());
}
}
HostValue::Response(response)