| @@ -0,0 +1,641 @@ |
| 1 | +//! C emission. See the crate documentation for the conventions. |
| 2 | + |
| 3 | +use std::collections::{BTreeSet, HashMap}; |
| 4 | +use std::fmt::Write; |
| 5 | + |
| 6 | +use tilc_core::ir::{Atom, Expr, FnDecl, FnId, Lit, Prim, Program, Value, VarId}; |
| 7 | + |
| 8 | +use crate::Unsupported; |
| 9 | + |
| 10 | +/// Arguments passed in registers; the rest go through `ctx->xargs`. |
| 11 | +const REGS: usize = 6; |
| 12 | +/// Must match `TL_XARGS` in tilrt.h. |
| 13 | +const XARGS: usize = 26; |
| 14 | + |
| 15 | +const PRELUDE: &str = r#"/* Generated by tilc (tilcayo native backend). Do not edit. */ |
| 16 | +#include "tilrt.h" |
| 17 | + |
| 18 | +#define TL_MUSTTAIL __attribute__((musttail)) |
| 19 | + |
| 20 | +static inline uint32_t tl_tag_of(tl_value v) { |
| 21 | + return tl_is_int(v) ? (uint32_t)tl_int_get(v) : tl_as_block(v)->h.tag; |
| 22 | +} |
| 23 | + |
| 24 | +static inline bool tl_str_is(tl_value s, const char *p, size_t n) { |
| 25 | + return tl_string_len(s) == n && memcmp(tl_string_ptr(s), p, n) == 0; |
| 26 | +} |
| 27 | + |
| 28 | +/* Function entry: count a reduction (preemption point). */ |
| 29 | +#define TL_TICK(ctx) \ |
| 30 | + do { if (tl_unlikely(--(ctx)->reductions <= 0)) tl_preempt(ctx); } while (0) |
| 31 | + |
| 32 | +"#; |
| 33 | + |
| 34 | +/// Runtime functions declared in tilrt.h (or defined inline there). |
| 35 | +const DECLARED: &[&str] = &[ |
| 36 | + "tl_int_add", |
| 37 | + "tl_int_sub", |
| 38 | + "tl_println", |
| 39 | + "tl_panic", |
| 40 | + "tl_float_add", |
| 41 | + "tl_float_sub", |
| 42 | + "tl_float_mul", |
| 43 | + "tl_float_div", |
| 44 | + "tl_float_rem", |
| 45 | + "tl_float_eq", |
| 46 | + "tl_float_compare", |
| 47 | + "tl_float_show", |
| 48 | + "tl_hash_float", |
| 49 | + "tl_int_eq", |
| 50 | + "tl_int_compare", |
| 51 | + "tl_int_mul", |
| 52 | + "tl_int_div", |
| 53 | + "tl_int_rem", |
| 54 | + "tl_int_show", |
| 55 | + "tl_hash_int", |
| 56 | + "tl_hash_combine", |
| 57 | + "tl_string_eq", |
| 58 | + "tl_string_compare", |
| 59 | + "tl_string_concat", |
| 60 | + "tl_string_length", |
| 61 | + "tl_string_debug", |
| 62 | + "tl_hash_string", |
| 63 | + "tl_html_escape", |
| 64 | + "tl_print", |
| 65 | + "tl_eprintln", |
| 66 | +]; |
| 67 | + |
| 68 | +pub(crate) fn emit( |
| 69 | + program: &Program, |
| 70 | + entry: FnId, |
| 71 | + reachable: &BTreeSet<FnId>, |
| 72 | +) -> Result<String, Unsupported> { |
| 73 | + let mut e = Emitter { |
| 74 | + program, |
| 75 | + lits: String::new(), |
| 76 | + lit_ids: HashMap::new(), |
| 77 | + entries: BTreeSet::new(), |
| 78 | + externs: BTreeSet::new(), |
| 79 | + body: String::new(), |
| 80 | + labels: 0, |
| 81 | + }; |
| 82 | + for f in reachable { |
| 83 | + e.function(*f, &program.fns[*f as usize])?; |
| 84 | + } |
| 85 | + let mut out = String::from(PRELUDE); |
| 86 | + for sym in &e.externs { |
| 87 | + let _ = writeln!(out, "tl_value {sym}(tl_ctx *ctx, ...);"); |
| 88 | + } |
| 89 | + out.push_str(&e.lits); |
| 90 | + out.push('\n'); |
| 91 | + for f in reachable { |
| 92 | + let _ = writeln!( |
| 93 | + out, |
| 94 | + "static tl_value f{f}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5);" |
| 95 | + ); |
| 96 | + } |
| 97 | + for (f, n) in &e.entries { |
| 98 | + let _ = writeln!( |
| 99 | + out, |
| 100 | + "static tl_value f{f}_c{n}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5);" |
| 101 | + ); |
| 102 | + } |
| 103 | + out.push('\n'); |
| 104 | + out.push_str(&e.body); |
| 105 | + for (f, n) in e.entries.clone() { |
| 106 | + e.closure_entry(&mut out, f, n); |
| 107 | + } |
| 108 | + let main_params = program.fns[entry as usize].params.len(); |
| 109 | + if main_params > REGS { |
| 110 | + return Err(Unsupported( |
| 111 | + "an entry function with many capabilities".into(), |
| 112 | + )); |
| 113 | + } |
| 114 | + let _ = write!( |
| 115 | + out, |
| 116 | + r#" |
| 117 | +static tl_value tl_entry(tl_ctx *ctx) {{ |
| 118 | + return f{entry}(ctx, TL_UNIT, TL_UNIT, TL_UNIT, TL_UNIT, TL_UNIT, TL_UNIT); |
| 119 | +}} |
| 120 | + |
| 121 | +int main(void) {{ |
| 122 | + tl_set_fatal_panics(); |
| 123 | + int code = tl_main(tl_entry); |
| 124 | + tl_report_leaks(); |
| 125 | + return code; |
| 126 | +}} |
| 127 | +"# |
| 128 | + ); |
| 129 | + Ok(out) |
| 130 | +} |
| 131 | + |
| 132 | +/// Where the value of an expression goes. |
| 133 | +#[derive(Clone, Copy)] |
| 134 | +enum Dest { |
| 135 | + /// Return it from the function (tail position). |
| 136 | + Return, |
| 137 | + /// Assign it to a variable and jump to a label (end of a block). |
| 138 | + Assign(VarId, u32), |
| 139 | +} |
| 140 | + |
| 141 | +struct Emitter<'p> { |
| 142 | + program: &'p Program, |
| 143 | + /// Static literal blocks. |
| 144 | + lits: String, |
| 145 | + lit_ids: HashMap<String, usize>, |
| 146 | + /// Closure entries needed: (function, number of captures). |
| 147 | + entries: BTreeSet<(FnId, usize)>, |
| 148 | + /// Foreign symbols to declare. |
| 149 | + externs: BTreeSet<String>, |
| 150 | + body: String, |
| 151 | + labels: u32, |
| 152 | +} |
| 153 | + |
| 154 | +/// C arguments for a call with these value slots: registers, padded. |
| 155 | +fn register_args(slots: &[String]) -> String { |
| 156 | + (0..REGS) |
| 157 | + .map(|i| slots.get(i).cloned().unwrap_or_else(|| "TL_UNIT".into())) |
| 158 | + .collect::<Vec<_>>() |
| 159 | + .join(", ") |
| 160 | +} |
| 161 | + |
| 162 | +/// Statements storing the slots after the sixth into `ctx->xargs`. |
| 163 | +fn store_xargs(slots: &[String], indent: &str, out: &mut String) { |
| 164 | + for (i, s) in slots.iter().enumerate().skip(REGS) { |
| 165 | + let _ = writeln!(out, "{indent}ctx->xargs[{}] = {s};", i - REGS); |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +impl Emitter<'_> { |
| 170 | + fn function(&mut self, id: FnId, decl: &FnDecl) -> Result<(), Unsupported> { |
| 171 | + if decl.params.len() > REGS + XARGS { |
| 172 | + return Err(Unsupported(format!( |
| 173 | + "functions with more than {} parameters (`{}`)", |
| 174 | + REGS + XARGS, |
| 175 | + decl.name |
| 176 | + ))); |
| 177 | + } |
| 178 | + let mut out = String::new(); |
| 179 | + let _ = writeln!(out, "/* {} */", decl.name); |
| 180 | + let _ = writeln!( |
| 181 | + out, |
| 182 | + "static tl_value f{id}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5) {{" |
| 183 | + ); |
| 184 | + let params: BTreeSet<VarId> = decl.params.iter().copied().collect(); |
| 185 | + for (i, p) in decl.params.iter().enumerate() { |
| 186 | + if i < REGS { |
| 187 | + let _ = writeln!(out, " tl_value v{p} = a{i};"); |
| 188 | + } else { |
| 189 | + let _ = writeln!(out, " tl_value v{p} = ctx->xargs[{}];", i - REGS); |
| 190 | + } |
| 191 | + } |
| 192 | + for i in decl.params.len()..REGS { |
| 193 | + let _ = writeln!(out, " (void)a{i};"); |
| 194 | + } |
| 195 | + let locals: Vec<String> = (0..decl.n_vars) |
| 196 | + .filter(|v| !params.contains(v)) |
| 197 | + .map(|v| format!("v{v} = TL_UNIT")) |
| 198 | + .collect(); |
| 199 | + for chunk in locals.chunks(8) { |
| 200 | + let _ = writeln!(out, " tl_value {};", chunk.join(", ")); |
| 201 | + } |
| 202 | + out.push_str("entry:\n TL_TICK(ctx);\n"); |
| 203 | + self.expr(&mut out, id, decl, &decl.body, Dest::Return, 1)?; |
| 204 | + out.push_str("}\n\n"); |
| 205 | + self.body.push_str(&out); |
| 206 | + Ok(()) |
| 207 | + } |
| 208 | + |
| 209 | + fn atom(&mut self, a: &Atom) -> Result<String, Unsupported> { |
| 210 | + Ok(match a { |
| 211 | + Atom::Var(v) => format!("v{v}"), |
| 212 | + Atom::Unit => "TL_UNIT".into(), |
| 213 | + Atom::Lit(Lit::Int(n)) => { |
| 214 | + if !(-(1i64 << 62)..(1i64 << 62)).contains(n) { |
| 215 | + return Err(Unsupported(format!( |
| 216 | + "the integer literal {n} (Int is 63-bit)" |
| 217 | + ))); |
| 218 | + } |
| 219 | + format!("tl_int(INT64_C({n}))") |
| 220 | + } |
| 221 | + Atom::Lit(Lit::String(s)) => { |
| 222 | + let name = self.string_lit(s); |
| 223 | + format!("((tl_value)&{name})") |
| 224 | + } |
| 225 | + Atom::Lit(Lit::Float(x)) => { |
| 226 | + let name = self.float_lit(*x); |
| 227 | + format!("((tl_value)&{name})") |
| 228 | + } |
| 229 | + }) |
| 230 | + } |
| 231 | + |
| 232 | + fn atoms(&mut self, atoms: &[Atom]) -> Result<Vec<String>, Unsupported> { |
| 233 | + atoms.iter().map(|a| self.atom(a)).collect() |
| 234 | + } |
| 235 | + |
| 236 | + fn string_lit(&mut self, s: &str) -> String { |
| 237 | + let key = format!("s{s}"); |
| 238 | + if let Some(id) = self.lit_ids.get(&key) { |
| 239 | + return format!("tl_lit{id}"); |
| 240 | + } |
| 241 | + let id = self.lit_ids.len(); |
| 242 | + self.lit_ids.insert(key, id); |
| 243 | + let _ = writeln!( |
| 244 | + self.lits, |
| 245 | + "static struct {{ tl_header h; int64_t len; char bytes[{}]; }} __attribute__((aligned(8))) tl_lit{id} = {{ {{0, TL_TAG_STRING, 0, 0}}, {}, \"{}\" }};", |
| 246 | + s.len() + 1, |
| 247 | + s.len(), |
| 248 | + c_escape(s) |
| 249 | + ); |
| 250 | + format!("tl_lit{id}") |
| 251 | + } |
| 252 | + |
| 253 | + fn float_lit(&mut self, x: f64) -> String { |
| 254 | + let key = format!("f{}", x.to_bits()); |
| 255 | + if let Some(id) = self.lit_ids.get(&key) { |
| 256 | + return format!("tl_lit{id}"); |
| 257 | + } |
| 258 | + let id = self.lit_ids.len(); |
| 259 | + self.lit_ids.insert(key, id); |
| 260 | + let _ = writeln!( |
| 261 | + self.lits, |
| 262 | + "static struct {{ tl_header h; double x; }} __attribute__((aligned(8))) tl_lit{id} = {{ {{0, TL_TAG_FLOAT, 0, 0}}, {x:e} }};" |
| 263 | + ); |
| 264 | + format!("tl_lit{id}") |
| 265 | + } |
| 266 | + |
| 267 | + /// Code calling a closure value `f` (consumed) with `args`. |
| 268 | + fn closure_call(f: &str, args: &[String], indent: &str, out: &mut String) -> String { |
| 269 | + let mut slots = vec![f.to_owned()]; |
| 270 | + slots.extend(args.iter().cloned()); |
| 271 | + store_xargs(&slots, indent, out); |
| 272 | + format!( |
| 273 | + "((tl_fn)tl_closure_code({f}))(ctx, {})", |
| 274 | + register_args(&slots) |
| 275 | + ) |
| 276 | + } |
| 277 | + |
| 278 | + #[allow(clippy::too_many_arguments)] |
| 279 | + fn expr( |
| 280 | + &mut self, |
| 281 | + out: &mut String, |
| 282 | + id: FnId, |
| 283 | + decl: &FnDecl, |
| 284 | + e: &Expr, |
| 285 | + dest: Dest, |
| 286 | + depth: usize, |
| 287 | + ) -> Result<(), Unsupported> { |
| 288 | + let ind = " ".repeat(depth); |
| 289 | + match e { |
| 290 | + Expr::Let(v, value, rest) => { |
| 291 | + let tail = matches!(dest, Dest::Return) |
| 292 | + && matches!(&**rest, Expr::Return(Atom::Var(r)) if r == v); |
| 293 | + if tail { |
| 294 | + match &**value { |
| 295 | + Value::Block(inner) => return self.expr(out, id, decl, inner, dest, depth), |
| 296 | + Value::CallFn(g, args) if *g == id => { |
| 297 | + // Self tail call: a jump. |
| 298 | + let args = self.atoms(args)?; |
| 299 | + let _ = writeln!(out, "{ind}{{"); |
| 300 | + for (i, a) in args.iter().enumerate() { |
| 301 | + let _ = writeln!(out, "{ind} tl_value t{i} = {a};"); |
| 302 | + } |
| 303 | + for (i, p) in decl.params.iter().enumerate() { |
| 304 | + let _ = writeln!(out, "{ind} v{p} = t{i};"); |
| 305 | + } |
| 306 | + let _ = writeln!(out, "{ind} goto entry;\n{ind}}}"); |
| 307 | + return Ok(()); |
| 308 | + } |
| 309 | + Value::CallFn(g, args) => { |
| 310 | + let slots = self.atoms(args)?; |
| 311 | + store_xargs(&slots, &ind, out); |
| 312 | + let _ = writeln!( |
| 313 | + out, |
| 314 | + "{ind}TL_MUSTTAIL return f{g}(ctx, {});", |
| 315 | + register_args(&slots) |
| 316 | + ); |
| 317 | + return Ok(()); |
| 318 | + } |
| 319 | + Value::Call(f, args) => { |
| 320 | + let f = self.atom(f)?; |
| 321 | + let args = self.atoms(args)?; |
| 322 | + let call = Self::closure_call(&f, &args, &ind, out); |
| 323 | + let _ = writeln!(out, "{ind}TL_MUSTTAIL return {call};"); |
| 324 | + return Ok(()); |
| 325 | + } |
| 326 | + _ => {} |
| 327 | + } |
| 328 | + } |
| 329 | + if let Value::Block(inner) = &**value { |
| 330 | + self.labels += 1; |
| 331 | + let label = self.labels; |
| 332 | + self.expr(out, id, decl, inner, Dest::Assign(*v, label), depth)?; |
| 333 | + let _ = writeln!(out, "{ind}b{label}:;"); |
| 334 | + } else { |
| 335 | + self.value(out, *v, value, &ind)?; |
| 336 | + } |
| 337 | + self.expr(out, id, decl, rest, dest, depth) |
| 338 | + } |
| 339 | + Expr::Return(a) => { |
| 340 | + let a = self.atom(a)?; |
| 341 | + match dest { |
| 342 | + Dest::Return => { |
| 343 | + let _ = writeln!(out, "{ind}return {a};"); |
| 344 | + } |
| 345 | + Dest::Assign(v, label) => { |
| 346 | + let _ = writeln!(out, "{ind}v{v} = {a};\n{ind}goto b{label};"); |
| 347 | + } |
| 348 | + } |
| 349 | + Ok(()) |
| 350 | + } |
| 351 | + Expr::Dup(v, rest) => { |
| 352 | + let _ = writeln!(out, "{ind}tl_dup(v{v});"); |
| 353 | + self.expr(out, id, decl, rest, dest, depth) |
| 354 | + } |
| 355 | + Expr::Drop(v, rest) => { |
| 356 | + let _ = writeln!(out, "{ind}tl_drop(ctx, v{v});"); |
| 357 | + self.expr(out, id, decl, rest, dest, depth) |
| 358 | + } |
| 359 | + Expr::Panic(msg) => { |
| 360 | + let _ = writeln!( |
| 361 | + out, |
| 362 | + "{ind}tl_panic_str(ctx, \"{}\");\n{ind}return TL_UNIT;", |
| 363 | + c_escape(msg) |
| 364 | + ); |
| 365 | + Ok(()) |
| 366 | + } |
| 367 | + Expr::Switch { on, cases, default } => { |
| 368 | + let on = self.atom(on)?; |
| 369 | + let _ = writeln!(out, "{ind}switch (tl_tag_of({on})) {{"); |
| 370 | + for (tag, body) in cases { |
| 371 | + let _ = writeln!(out, "{ind}case {tag}: {{"); |
| 372 | + self.expr(out, id, decl, body, dest, depth + 1)?; |
| 373 | + let _ = writeln!(out, "{ind}}}"); |
| 374 | + } |
| 375 | + match default { |
| 376 | + Some(d) => { |
| 377 | + let _ = writeln!(out, "{ind}default: {{"); |
| 378 | + self.expr(out, id, decl, d, dest, depth + 1)?; |
| 379 | + let _ = writeln!(out, "{ind}}}"); |
| 380 | + } |
| 381 | + None => { |
| 382 | + let _ = writeln!(out, "{ind}default: __builtin_unreachable();"); |
| 383 | + } |
| 384 | + } |
| 385 | + let _ = writeln!(out, "{ind}}}"); |
| 386 | + Ok(()) |
| 387 | + } |
| 388 | + Expr::SwitchLit { on, cases, default } => { |
| 389 | + let on = self.atom(on)?; |
| 390 | + for (i, (lit, body)) in cases.iter().enumerate() { |
| 391 | + let test = match lit { |
| 392 | + Lit::Int(n) => format!("{on} == tl_int(INT64_C({n}))"), |
| 393 | + Lit::Float(x) => format!("tl_float_get({on}) == {x:e}"), |
| 394 | + Lit::String(s) => { |
| 395 | + format!("tl_str_is({on}, \"{}\", {})", c_escape(s), s.len()) |
| 396 | + } |
| 397 | + }; |
| 398 | + let kw = if i == 0 { "if" } else { "} else if" }; |
| 399 | + let _ = writeln!(out, "{ind}{kw} ({test}) {{"); |
| 400 | + self.expr(out, id, decl, body, dest, depth + 1)?; |
| 401 | + } |
| 402 | + if cases.is_empty() { |
| 403 | + return self.expr(out, id, decl, default, dest, depth); |
| 404 | + } |
| 405 | + let _ = writeln!(out, "{ind}}} else {{"); |
| 406 | + self.expr(out, id, decl, default, dest, depth + 1)?; |
| 407 | + let _ = writeln!(out, "{ind}}}"); |
| 408 | + Ok(()) |
| 409 | + } |
| 410 | + } |
| 411 | + } |
| 412 | + |
| 413 | + /// `v = value;` (not a block). |
| 414 | + fn value( |
| 415 | + &mut self, |
| 416 | + out: &mut String, |
| 417 | + v: VarId, |
| 418 | + value: &Value, |
| 419 | + ind: &str, |
| 420 | + ) -> Result<(), Unsupported> { |
| 421 | + match value { |
| 422 | + Value::Atom(a) => { |
| 423 | + let a = self.atom(a)?; |
| 424 | + let _ = writeln!(out, "{ind}v{v} = {a};"); |
| 425 | + } |
| 426 | + Value::CallFn(g, args) => { |
| 427 | + let slots = self.atoms(args)?; |
| 428 | + store_xargs(&slots, ind, out); |
| 429 | + let _ = writeln!(out, "{ind}v{v} = f{g}(ctx, {});", register_args(&slots)); |
| 430 | + } |
| 431 | + Value::Call(f, args) => { |
| 432 | + let f = self.atom(f)?; |
| 433 | + let args = self.atoms(args)?; |
| 434 | + let call = Self::closure_call(&f, &args, ind, out); |
| 435 | + let _ = writeln!(out, "{ind}v{v} = {call};"); |
| 436 | + } |
| 437 | + Value::CallExtern(sym, args) => { |
| 438 | + if !DECLARED.contains(&sym.as_str()) { |
| 439 | + self.externs.insert(sym.clone()); |
| 440 | + } |
| 441 | + let mut args = self.atoms(args)?; |
| 442 | + args.insert(0, "ctx".into()); |
| 443 | + let _ = writeln!(out, "{ind}v{v} = {sym}({});", args.join(", ")); |
| 444 | + } |
| 445 | + Value::Prim(p, args) => { |
| 446 | + let a = self.atom(&args[0])?; |
| 447 | + let text = match p { |
| 448 | + Prim::Not => format!("({a} == TL_TRUE) ? TL_FALSE : TL_TRUE"), |
| 449 | + Prim::TagIs(t) => format!("tl_tag_of({a}) == {t} ? TL_TRUE : TL_FALSE"), |
| 450 | + Prim::Tag => format!("tl_int(tl_tag_of({a}))"), |
| 451 | + }; |
| 452 | + let _ = writeln!(out, "{ind}v{v} = {text};"); |
| 453 | + } |
| 454 | + Value::Construct { tag, args, .. } => { |
| 455 | + let args = self.atoms(args)?; |
| 456 | + self.block(out, v, *tag, &args, ind)?; |
| 457 | + } |
| 458 | + Value::Tuple(args) => { |
| 459 | + let args = self.atoms(args)?; |
| 460 | + self.block(out, v, 0, &args, ind)?; |
| 461 | + } |
| 462 | + Value::Field(base, i) => { |
| 463 | + let b = self.atom(base)?; |
| 464 | + let _ = writeln!(out, "{ind}v{v} = tl_dup(tl_as_block({b})->fields[{i}]);"); |
| 465 | + } |
| 466 | + Value::Closure(f, caps) => { |
| 467 | + let caps = self.atoms(caps)?; |
| 468 | + if caps.len() > 254 { |
| 469 | + return Err(Unsupported( |
| 470 | + "closures capturing more than 254 values".into(), |
| 471 | + )); |
| 472 | + } |
| 473 | + self.entries.insert((*f, caps.len())); |
| 474 | + let _ = writeln!( |
| 475 | + out, |
| 476 | + "{ind}v{v} = tl_closure_alloc(ctx, (tl_closure_fn)f{f}_c{}, {});", |
| 477 | + caps.len(), |
| 478 | + caps.len() |
| 479 | + ); |
| 480 | + for (i, c) in caps.iter().enumerate() { |
| 481 | + let _ = writeln!(out, "{ind}tl_as_block(v{v})->fields[{i}] = {c};"); |
| 482 | + } |
| 483 | + } |
| 484 | + Value::Perform { |
| 485 | + cap, |
| 486 | + effect, |
| 487 | + op, |
| 488 | + args, |
| 489 | + } => { |
| 490 | + let decl = &self.program.effects[*effect as usize]; |
| 491 | + let cap = self.atom(cap)?; |
| 492 | + let args = self.atoms(args)?; |
| 493 | + let op_name = decl.ops[*op as usize].0.as_str(); |
| 494 | + match (decl.name.as_str(), op_name) { |
| 495 | + ("std/ref.alloc", _) => { |
| 496 | + let _ = writeln!(out, "{ind}v{v} = tl_ref_new(ctx, {cap}, {});", args[0]); |
| 497 | + } |
| 498 | + ("std/ref.st", "get") => { |
| 499 | + let _ = writeln!( |
| 500 | + out, |
| 501 | + "{ind}v{v} = tl_ref_get(ctx, {r});\n{ind}tl_drop(ctx, {r});", |
| 502 | + r = args[0] |
| 503 | + ); |
| 504 | + } |
| 505 | + ("std/ref.st", _) => { |
| 506 | + let _ = writeln!( |
| 507 | + out, |
| 508 | + "{ind}v{v} = tl_ref_set(ctx, {r}, {x});\n{ind}tl_drop(ctx, {r});", |
| 509 | + r = args[0], |
| 510 | + x = args[1] |
| 511 | + ); |
| 512 | + } |
| 513 | + _ => { |
| 514 | + // A `fn` operation: call the clause in the handler. |
| 515 | + let clause = format!("tl_dup(tl_as_block({cap})->fields[{op}])"); |
| 516 | + let _ = writeln!(out, "{ind}{{\n{ind} tl_value clause = {clause};"); |
| 517 | + let inner = format!("{ind} "); |
| 518 | + let call = Self::closure_call("clause", &args, &inner, out); |
| 519 | + let _ = writeln!(out, "{inner}v{v} = {call};\n{ind}}}"); |
| 520 | + } |
| 521 | + } |
| 522 | + } |
| 523 | + Value::Handle { |
| 524 | + body, ret, clauses, .. |
| 525 | + } => { |
| 526 | + let body = self.atom(body)?; |
| 527 | + let ret = ret.as_ref().map(|r| self.atom(r)).transpose()?; |
| 528 | + let clauses = self.atoms(clauses)?; |
| 529 | + let _ = writeln!(out, "{ind}{{"); |
| 530 | + let inner = format!("{ind} "); |
| 531 | + // The capability: a block holding the clauses. |
| 532 | + self.block(out, v, 0, &clauses, &inner)?; |
| 533 | + let _ = writeln!(out, "{inner}tl_value cap = v{v};"); |
| 534 | + let call = Self::closure_call(&body, &["cap".into()], &inner, out); |
| 535 | + let _ = writeln!(out, "{inner}v{v} = {call};"); |
| 536 | + if let Some(r) = ret { |
| 537 | + let call = Self::closure_call(&r, &[format!("v{v}")], &inner, out); |
| 538 | + let _ = writeln!(out, "{inner}v{v} = {call};"); |
| 539 | + } |
| 540 | + let _ = writeln!(out, "{ind}}}"); |
| 541 | + } |
| 542 | + Value::Region { body, .. } => { |
| 543 | + let body = self.atom(body)?; |
| 544 | + let _ = writeln!(out, "{ind}{{\n{ind} tl_value region = tl_region_new(ctx);"); |
| 545 | + let inner = format!("{ind} "); |
| 546 | + let call = Self::closure_call(&body, &["tl_dup(region)".into()], &inner, out); |
| 547 | + let _ = writeln!( |
| 548 | + out, |
| 549 | + "{inner}v{v} = {call};\n{inner}tl_region_end(ctx, region);\n{inner}tl_drop(ctx, region);\n{ind}}}" |
| 550 | + ); |
| 551 | + } |
| 552 | + Value::Block(_) => unreachable!("blocks are emitted by `expr`"), |
| 553 | + } |
| 554 | + Ok(()) |
| 555 | + } |
| 556 | + |
| 557 | + /// `v = Constructor(args)`: a heap block, or a tagged int if nullary. |
| 558 | + fn block( |
| 559 | + &mut self, |
| 560 | + out: &mut String, |
| 561 | + v: VarId, |
| 562 | + tag: u32, |
| 563 | + args: &[String], |
| 564 | + ind: &str, |
| 565 | + ) -> Result<(), Unsupported> { |
| 566 | + if args.is_empty() { |
| 567 | + let _ = writeln!(out, "{ind}v{v} = tl_int({tag});"); |
| 568 | + return Ok(()); |
| 569 | + } |
| 570 | + if args.len() > 254 || tag >= 0xFF00 { |
| 571 | + return Err(Unsupported("constructors with more than 254 fields".into())); |
| 572 | + } |
| 573 | + let _ = writeln!( |
| 574 | + out, |
| 575 | + "{ind}v{v} = tl_from_block(tl_alloc(ctx, {tag}, {}, 0));", |
| 576 | + args.len() |
| 577 | + ); |
| 578 | + for (i, a) in args.iter().enumerate() { |
| 579 | + let _ = writeln!(out, "{ind}tl_as_block(v{v})->fields[{i}] = {a};"); |
| 580 | + } |
| 581 | + Ok(()) |
| 582 | + } |
| 583 | + |
| 584 | + /// The entry of closures of `f` capturing `n` values: unpack the |
| 585 | + /// closure (first argument), then tail-call `f` with captures first. |
| 586 | + fn closure_entry(&self, out: &mut String, f: FnId, n: usize) { |
| 587 | + let total = self.program.fns[f as usize].params.len(); |
| 588 | + let _ = writeln!( |
| 589 | + out, |
| 590 | + "static tl_value f{f}_c{n}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5) {{" |
| 591 | + ); |
| 592 | + // Incoming slots: the closure, then the call's arguments. |
| 593 | + let incoming = 1 + total.saturating_sub(n); |
| 594 | + let mut slots: Vec<String> = Vec::new(); |
| 595 | + for i in 0..incoming { |
| 596 | + if i < REGS { |
| 597 | + slots.push(format!("a{i}")); |
| 598 | + } else { |
| 599 | + let _ = writeln!(out, " tl_value x{i} = ctx->xargs[{}];", i - REGS); |
| 600 | + slots.push(format!("x{i}")); |
| 601 | + } |
| 602 | + } |
| 603 | + for i in incoming..REGS { |
| 604 | + let _ = writeln!(out, " (void)a{i};"); |
| 605 | + } |
| 606 | + let mut outgoing = Vec::new(); |
| 607 | + for i in 0..n { |
| 608 | + let _ = writeln!( |
| 609 | + out, |
| 610 | + " tl_value c{i} = tl_dup(tl_as_block(a0)->fields[{i}]);" |
| 611 | + ); |
| 612 | + outgoing.push(format!("c{i}")); |
| 613 | + } |
| 614 | + let _ = writeln!(out, " tl_drop(ctx, a0);"); |
| 615 | + outgoing.extend(slots.into_iter().skip(1)); |
| 616 | + store_xargs(&outgoing, " ", out); |
| 617 | + let _ = writeln!( |
| 618 | + out, |
| 619 | + " TL_MUSTTAIL return f{f}(ctx, {});\n}}\n", |
| 620 | + register_args(&outgoing) |
| 621 | + ); |
| 622 | + } |
| 623 | +} |
| 624 | + |
| 625 | +/// A C string literal body: printable ASCII as is, everything else (and |
| 626 | +/// `"`, `\`, `?`) as three-digit octal escapes. |
| 627 | +fn c_escape(s: &str) -> String { |
| 628 | + let mut out = String::new(); |
| 629 | + for b in s.bytes() { |
| 630 | + match b { |
| 631 | + b'"' | b'\\' | b'?' => { |
| 632 | + let _ = write!(out, "\\{b:03o}"); |
| 633 | + } |
| 634 | + 0x20..=0x7e => out.push(b as char), |
| 635 | + _ => { |
| 636 | + let _ = write!(out, "\\{b:03o}"); |
| 637 | + } |
| 638 | + } |
| 639 | + } |
| 640 | + out |
| 641 | +} |