use crate::design::{declare, params, source, Declared, El, Json};
use std::cell::RefCell;
thread_local! {
static OUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
static STEM_IN: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
static INPUT_IN: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}
pub fn input_alloc(len: u32) -> u32 {
INPUT_IN.with(|b| {
let mut b = b.borrow_mut();
*b = vec![0; len as usize];
b.as_mut_ptr() as usize as u32
})
}
pub fn stem_alloc(len: u32) -> u32 {
STEM_IN.with(|b| {
let mut b = b.borrow_mut();
*b = vec![0; len as usize];
b.as_mut_ptr() as usize as u32
})
}
fn set_out(text: String) {
OUT.with(|o| *o.borrow_mut() = text.into_bytes());
}
fn failed(error: String) -> String {
Json::obj().with("ok", false).with("error", error).text()
}
pub fn answer(declared: Result<Declared, String>) -> Result<Json, String> {
let out = Json::obj().with("ok", true);
Ok(match declared? {
Declared::Graph(graph) => out.with("graph", graph).with("params", params::declared()).with("sites", source::sites()),
Declared::Document { format, document, sources } => out
.with("graph", Json::obj().with("id", "Document").with("nodes", Json::obj()))
.with("params", params::declared())
.with("sites", source::sites())
.with("document", Json::obj().with("format", format).with("document", document).with("sources", sources)),
})
}
pub fn run(document: impl FnOnce() -> El) -> u32 {
std::panic::set_hook(Box::new(|info| {
let what = info
.payload()
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| info.payload().downcast_ref::<String>().cloned())
.unwrap_or_else(|| "the file panicked".to_string());
let at = info.location().map(|l| format!(" (line {})", l.line())).unwrap_or_default();
set_out(failed(format!("{what}{at}")));
}));
set_out(failed("the file did not finish".into()));
STEM_IN.with(|b| source::set_stem(&String::from_utf8_lossy(&b.borrow())));
INPUT_IN.with(|b| {
if !b.borrow().is_empty() {
params::set_inputs(Json::parse(&String::from_utf8_lossy(&b.borrow())).unwrap_or(Json::Null));
}
});
match answer(declare(document())) {
Ok(answer) => {
set_out(answer.text());
1
}
Err(error) => {
set_out(failed(error));
0
}
}
}
pub fn out_ptr() -> u32 {
OUT.with(|o| o.borrow().as_ptr() as usize as u32)
}
pub fn out_len() -> u32 {
OUT.with(|o| o.borrow().len() as u32)
}
pub fn out_text() -> String {
OUT.with(|o| String::from_utf8_lossy(&o.borrow()).into_owned())
}