| @@ -1,1290 +0,0 @@ |
| 1 | | −//! C emission. See the crate documentation for the conventions. |
| 2 | | − |
| 3 | | −use std::collections::{BTreeMap, BTreeSet, HashMap}; |
| 4 | | −use std::fmt::Write; |
| 5 | | − |
| 6 | | −use tilc_core::ir::{Atom, Expr, FnDecl, FnId, Lit, OpKind, Prim, Program, Span, Value, VarId}; |
| 7 | | −use tilc_span::{FileId, SourceDb}; |
| 8 | | − |
| 9 | | −use crate::Unsupported; |
| 10 | | − |
| 11 | | −/// Arguments passed in registers; the rest go through `ctx->xargs`. |
| 12 | | −const REGS: usize = 6; |
| 13 | | −/// Must match `TL_XARGS` in tilrt.h. |
| 14 | | −const XARGS: usize = 26; |
| 15 | | − |
| 16 | | −const PRELUDE: &str = r#"/* Generated by tilc (tilcayo native backend). Do not edit. */ |
| 17 | | −#include <stdlib.h> |
| 18 | | −#include "tilrt.h" |
| 19 | | − |
| 20 | | −#define TL_MUSTTAIL __attribute__((musttail)) |
| 21 | | − |
| 22 | | −static inline uint32_t tl_tag_of(tl_value v) { |
| 23 | | − return tl_is_int(v) ? (uint32_t)tl_int_get(v) : tl_as_block(v)->h.tag; |
| 24 | | −} |
| 25 | | − |
| 26 | | −static inline bool tl_str_is(tl_value s, const char *p, size_t n) { |
| 27 | | − return tl_string_len(s) == n && memcmp(tl_string_ptr(s), p, n) == 0; |
| 28 | | −} |
| 29 | | − |
| 30 | | −/* Call a `final ctl` clause with the arguments in `payload` (the |
| 31 | | − * operation's index, then its arguments), consuming both. Unused argument |
| 32 | | − * slots are never read (all functions share one signature). */ |
| 33 | | −static tl_value tl_call_payload(tl_ctx *ctx, tl_value clause, tl_value payload) { |
| 34 | | − tl_block *p = tl_as_block(payload); |
| 35 | | − int n = p->h.scan_fsize - 1; |
| 36 | | − tl_value a[5] = {TL_UNIT, TL_UNIT, TL_UNIT, TL_UNIT, TL_UNIT}; |
| 37 | | − for (int i = 0; i < n; i++) { |
| 38 | | − tl_value x = tl_dup(p->fields[1 + i]); |
| 39 | | − if (i < 5) a[i] = x; else ctx->xargs[i - 5] = x; |
| 40 | | − } |
| 41 | | − tl_drop(ctx, payload); |
| 42 | | − return ((tl_fn)tl_closure_code(clause))(ctx, clause, a[0], a[1], a[2], a[3], a[4]); |
| 43 | | −} |
| 44 | | − |
| 45 | | −/* Drop specialisation: free the unique cell `b`, `moved` of whose fields |
| 46 | | − * were moved out (set to unit); its other fields are dropped. */ |
| 47 | | −static inline void tl_free_moved(tl_ctx *ctx, tl_block *b, int moved) { |
| 48 | | − if (b->h.scan_fsize == moved && b->h.tag < TL_TAG_RUNTIME_MIN) tl_free(ctx, b); |
| 49 | | − else tl_drop_slow(ctx, b); |
| 50 | | −} |
| 51 | | − |
| 52 | | −/* Reuse: keep the unique cell `b`, whose moved-out fields are unit, as a |
| 53 | | − * token for a later constructor: drop its other fields. Tokens are only |
| 54 | | − * taken from matched constructor cells; a runtime block would be freed |
| 55 | | − * instead (token unit). */ |
| 56 | | −static inline tl_value tl_reuse_token(tl_ctx *ctx, tl_block *b) { |
| 57 | | − if (b->h.tag >= TL_TAG_RUNTIME_MIN) { |
| 58 | | − tl_drop_slow(ctx, b); |
| 59 | | − return TL_UNIT; |
| 60 | | − } |
| 61 | | − for (int i = 0; i < b->h.scan_fsize; i++) { |
| 62 | | − tl_value f = b->fields[i]; |
| 63 | | − b->fields[i] = TL_UNIT; |
| 64 | | − tl_drop(ctx, f); |
| 65 | | − } |
| 66 | | − return tl_from_block(b); |
| 67 | | −} |
| 68 | | − |
| 69 | | −"#; |
| 70 | | − |
| 71 | | −/// Runtime functions declared in tilrt.h (or defined inline there). |
| 72 | | −/// Externs that may unwind: they may panic, or park the actor (which may |
| 73 | | −/// be stopped meanwhile). |
| 74 | | −pub(crate) const PANICKING: &[&str] = &[ |
| 75 | | − "tl_net_accept", |
| 76 | | − "tl_net_connect", |
| 77 | | − "tl_net_read", |
| 78 | | − "tl_net_write", |
| 79 | | − "tl_net_write_string", |
| 80 | | − "tl_bytes_from_list", |
| 81 | | − "tl_bytes_append_byte", |
| 82 | | − "tl_array_at", |
| 83 | | − "tl_array_set", |
| 84 | | − "tl_random_int", |
| 85 | | − "tl_int_div", |
| 86 | | − "tl_int_rem", |
| 87 | | − "tl_panic", |
| 88 | | −]; |
| 89 | | − |
| 90 | | −const DECLARED: &[&str] = &[ |
| 91 | | − "tl_coerce", |
| 92 | | − "tl_url_decode", |
| 93 | | − "tl_os_env", |
| 94 | | − "tl_string_byte_length", |
| 95 | | − "tl_string_to_lower", |
| 96 | | − "tl_string_trim", |
| 97 | | − "tl_string_split", |
| 98 | | − "tl_string_parse_int", |
| 99 | | − "tl_net_listen", |
| 100 | | − "tl_net_port", |
| 101 | | − "tl_net_accept", |
| 102 | | − "tl_net_connect", |
| 103 | | − "tl_net_read", |
| 104 | | − "tl_net_write", |
| 105 | | − "tl_net_write_string", |
| 106 | | − "tl_net_close", |
| 107 | | − "tl_http_parse_request", |
| 108 | | − "tl_http_parse_chunk", |
| 109 | | − "tl_string_starts_with", |
| 110 | | − "tl_string_ends_with", |
| 111 | | − "tl_string_contains", |
| 112 | | − "tl_random_int", |
| 113 | | − "tl_random_token", |
| 114 | | − "tl_pid_eq", |
| 115 | | − "tl_int_add", |
| 116 | | − "tl_int_sub", |
| 117 | | − "tl_println", |
| 118 | | − "tl_panic", |
| 119 | | − "tl_float_add", |
| 120 | | − "tl_float_sub", |
| 121 | | − "tl_float_mul", |
| 122 | | − "tl_float_div", |
| 123 | | − "tl_float_rem", |
| 124 | | − "tl_float_eq", |
| 125 | | − "tl_float_compare", |
| 126 | | − "tl_float_show", |
| 127 | | − "tl_hash_float", |
| 128 | | − "tl_int_eq", |
| 129 | | − "tl_int_compare", |
| 130 | | − "tl_int_mul", |
| 131 | | − "tl_int_div", |
| 132 | | − "tl_int_rem", |
| 133 | | − "tl_int_show", |
| 134 | | − "tl_hash_int", |
| 135 | | − "tl_hash_combine", |
| 136 | | − "tl_string_eq", |
| 137 | | − "tl_string_compare", |
| 138 | | − "tl_string_concat", |
| 139 | | − "tl_string_length", |
| 140 | | − "tl_string_debug", |
| 141 | | − "tl_hash_string", |
| 142 | | − "tl_html_escape", |
| 143 | | − "tl_print", |
| 144 | | − "tl_eprintln", |
| 145 | | −]; |
| 146 | | − |
| 147 | | −/// Generated C below this size stays in one translation unit: a unit |
| 148 | | −/// costs a compiler process and loses inlining across units. |
| 149 | | −const MIN_UNIT_BYTES: usize = 64 * 1024; |
| 150 | | − |
| 151 | | −/// The C of a whole program, in at most `units` translation units (one if |
| 152 | | −/// the program is small). With `sources`, the functions that have a span |
| 153 | | −/// are emitted last, under `#line` directives pointing at their source; |
| 154 | | −/// everything before them (runtime glue, constants, closure entries, |
| 155 | | −/// `main`, generated functions) keeps its own C line numbers, so no |
| 156 | | −/// directive has to point back into the generated file. |
| 157 | | −/// |
| 158 | | −/// Several units are compiled in parallel. Each starts with the same |
| 159 | | −/// declarations (runtime glue, externs, literals, prototypes and constant |
| 160 | | −/// dictionaries, which stay `static` copies so calls through them are |
| 161 | | −/// still direct); the first also has the closure entries and `main`; the |
| 162 | | −/// functions are split between them in order, by size. Functions are then |
| 163 | | −/// `TL_FN`: `static` with one unit, external with several. |
| 164 | | −pub(crate) fn emit( |
| 165 | | − program: &Program, |
| 166 | | − entries: &[FnId], |
| 167 | | − reachable: &BTreeSet<FnId>, |
| 168 | | − sources: Option<&SourceDb>, |
| 169 | | − units: usize, |
| 170 | | −) -> Result<Vec<String>, Unsupported> { |
| 171 | | − let mut e = Emitter { |
| 172 | | − program, |
| 173 | | − sources, |
| 174 | | − lits: String::new(), |
| 175 | | − lit_ids: HashMap::new(), |
| 176 | | − entries: BTreeSet::new(), |
| 177 | | − externs: BTreeMap::new(), |
| 178 | | − thunks: String::new(), |
| 179 | | − constants: BTreeSet::new(), |
| 180 | | − never_unwinds: BTreeSet::new(), |
| 181 | | − constant_defs: String::new(), |
| 182 | | − generated: Vec::new(), |
| 183 | | − located: Vec::new(), |
| 184 | | − labels: 0, |
| 185 | | − line: None, |
| 186 | | − written: None, |
| 187 | | − }; |
| 188 | | − for f in reachable { |
| 189 | | − e.constant(*f, &program.fns[*f as usize]); |
| 190 | | − } |
| 191 | | − e.never_unwinds = crate::unwind::never_unwinding(program, reachable, &e.constants); |
| 192 | | − for f in reachable { |
| 193 | | − if !e.constants.contains(f) { |
| 194 | | − e.function(*f, &program.fns[*f as usize])?; |
| 195 | | − } |
| 196 | | − } |
| 197 | | − let size: usize = e.generated.iter().chain(&e.located).map(String::len).sum(); |
| 198 | | − let units = units.min(size / MIN_UNIT_BYTES).max(1); |
| 199 | | − let mut out = String::from(PRELUDE); |
| 200 | | − let _ = writeln!( |
| 201 | | − out, |
| 202 | | − "#define TL_FN{}\n", |
| 203 | | − if units == 1 { " static" } else { "" } |
| 204 | | − ); |
| 205 | | − for (sym, arity) in &e.externs { |
| 206 | | − let params: String = (0..*arity).map(|_| ", tl_value").collect(); |
| 207 | | − let _ = writeln!(out, "tl_value {sym}(tl_ctx *ctx{params});"); |
| 208 | | − } |
| 209 | | − out.push_str(&e.thunks); |
| 210 | | − out.push_str(&e.lits); |
| 211 | | − out.push('\n'); |
| 212 | | − for f in reachable.difference(&e.constants) { |
| 213 | | − let _ = writeln!( |
| 214 | | − out, |
| 215 | | − "TL_FN 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);" |
| 216 | | − ); |
| 217 | | − } |
| 218 | | − for (f, n) in &e.entries { |
| 219 | | − let _ = writeln!( |
| 220 | | − out, |
| 221 | | − "TL_FN 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);" |
| 222 | | − ); |
| 223 | | − } |
| 224 | | − out.push('\n'); |
| 225 | | − out.push_str(&e.constant_defs); |
| 226 | | − let header = out.clone(); |
| 227 | | − for (f, n) in e.entries.clone() { |
| 228 | | − e.closure_entry(&mut out, f, n); |
| 229 | | − } |
| 230 | | − // `main` (or a test) receives a root capability per label of its row: |
| 231 | | − // only `proc` can be there (checked by `tilc_core::runnable`). |
| 232 | | − let mut cases = String::new(); |
| 233 | | − for (k, entry) in entries.iter().enumerate() { |
| 234 | | − let n = program.fns[*entry as usize].params.len(); |
| 235 | | − if n > REGS { |
| 236 | | − return Err(Unsupported( |
| 237 | | − "an entry function with many capabilities".into(), |
| 238 | | − )); |
| 239 | | − } |
| 240 | | − let decl = &program.fns[*entry as usize]; |
| 241 | | − let _ = writeln!(cases, " case {k}: {{"); |
| 242 | | − for i in 0..n { |
| 243 | | − let _ = writeln!( |
| 244 | | − cases, |
| 245 | | − " tl_value c{i} = tl_root_cap(ctx, {});", |
| 246 | | − crate::PROC_OPS.len() |
| 247 | | − ); |
| 248 | | − } |
| 249 | | − let caps: Vec<String> = (0..n).map(|i| format!("c{i}")).collect(); |
| 250 | | − let _ = writeln!( |
| 251 | | − cases, |
| 252 | | − " tl_value r = f{entry}(ctx, {});", |
| 253 | | − register_args(&caps) |
| 254 | | − ); |
| 255 | | − // A borrowed capability is still the caller's. |
| 256 | | − for i in &decl.borrowed { |
| 257 | | − let _ = writeln!(cases, " tl_drop(ctx, c{i});"); |
| 258 | | − } |
| 259 | | − let _ = writeln!(cases, " return r;\n }}"); |
| 260 | | − } |
| 261 | | − let _ = write!( |
| 262 | | − out, |
| 263 | | − r#" |
| 264 | | −static int tl_which; |
| 265 | | − |
| 266 | | −static tl_value tl_entry(tl_ctx *ctx) {{ |
| 267 | | − switch (tl_which) {{ |
| 268 | | −{cases} default: return TL_UNIT; |
| 269 | | − }} |
| 270 | | −}} |
| 271 | | − |
| 272 | | −int main(int argc, char **argv) {{ |
| 273 | | − tl_abi_check(TL_ABI_VERSION); |
| 274 | | − tl_which = argc > 1 ? atoi(argv[1]) : 0; |
| 275 | | − int code = tl_main_program(tl_entry); |
| 276 | | − tl_report_leaks(); |
| 277 | | − return code; |
| 278 | | −}} |
| 279 | | − |
| 280 | | −"# |
| 281 | | − ); |
| 282 | | − // Generated functions come before located ones in every unit, so no |
| 283 | | − // `#line` directive applies to them. |
| 284 | | − let functions: Vec<String> = e.generated.into_iter().chain(e.located).collect(); |
| 285 | | − let mut result = vec![out]; |
| 286 | | − let mut done = 0; |
| 287 | | − for f in functions { |
| 288 | | − // Start the next unit once this one has its share. |
| 289 | | − if done >= size * result.len() / units && result.len() < units { |
| 290 | | − result.push(header.clone()); |
| 291 | | − } |
| 292 | | − done += f.len(); |
| 293 | | − result.last_mut().expect("one unit at least").push_str(&f); |
| 294 | | − } |
| 295 | | − Ok(result) |
| 296 | | −} |
| 297 | | − |
| 298 | | −/// The function being emitted. |
| 299 | | −struct Func<'a> { |
| 300 | | − id: FnId, |
| 301 | | − decl: &'a FnDecl, |
| 302 | | −} |
| 303 | | − |
| 304 | | −/// Remove one reference to `v` from `held`. |
| 305 | | −fn take(held: &mut Vec<VarId>, v: VarId) { |
| 306 | | − if let Some(i) = held.iter().position(|h| *h == v) { |
| 307 | | − held.swap_remove(i); |
| 308 | | − } |
| 309 | | −} |
| 310 | | − |
| 311 | | −/// Unwinding out of this frame: drop what it holds, return. (A copying |
| 312 | | −/// pass over a `multi ctl` continuation, ADR 0017, takes the same path |
| 313 | | −/// and dups instead.) |
| 314 | | −fn unwind(held: &[VarId]) -> String { |
| 315 | | − let mut s = String::from("{ "); |
| 316 | | − for v in held { |
| 317 | | − let _ = write!(s, "TL_UNWIND_DROP(ctx, v{v}); "); |
| 318 | | − } |
| 319 | | − s.push_str("return TL_UNIT; }"); |
| 320 | | − s |
| 321 | | −} |
| 322 | | − |
| 323 | | −/// Where the value of an expression goes. |
| 324 | | −#[derive(Clone, Copy)] |
| 325 | | −enum Dest { |
| 326 | | − /// Return it from the function (tail position). |
| 327 | | − Return, |
| 328 | | − /// Assign it to a variable and jump to a label (end of a block). |
| 329 | | − Assign(VarId, u32), |
| 330 | | −} |
| 331 | | − |
| 332 | | −/// A line of a source file. |
| 333 | | −#[derive(Clone, Copy, PartialEq, Eq)] |
| 334 | | −struct Line { |
| 335 | | − file: FileId, |
| 336 | | − line: u32, |
| 337 | | −} |
| 338 | | − |
| 339 | | −struct Emitter<'p> { |
| 340 | | − program: &'p Program, |
| 341 | | − /// The source files, to point `#line` directives at (none: no |
| 342 | | − /// directives). |
| 343 | | − sources: Option<&'p SourceDb>, |
| 344 | | − /// Static literal blocks. |
| 345 | | − lits: String, |
| 346 | | − lit_ids: HashMap<String, usize>, |
| 347 | | − /// Closure entries needed: (function, number of captures). |
| 348 | | − entries: BTreeSet<(FnId, usize)>, |
| 349 | | − /// Foreign symbols to declare, with their arity. |
| 350 | | − externs: BTreeMap<String, usize>, |
| 351 | | − /// Thunks for `blocking` externs. |
| 352 | | − thunks: String, |
| 353 | | − /// Functions that never unwind: calls of them need no yield check, and |
| 354 | | − /// they have no preemption point (`crate::unwind`). |
| 355 | | − never_unwinds: BTreeSet<FnId>, |
| 356 | | − /// Functions emitted as a static, immortal value (see `constant`). |
| 357 | | − constants: BTreeSet<FnId>, |
| 358 | | − constant_defs: String, |
| 359 | | − /// Functions without a source location, then those with one. |
| 360 | | − generated: Vec<String>, |
| 361 | | − located: Vec<String>, |
| 362 | | − labels: u32, |
| 363 | | − /// The source line of the code being emitted (none outside located |
| 364 | | − /// functions), and the line the last `#line` directive set. |
| 365 | | − line: Option<Line>, |
| 366 | | − written: Option<Line>, |
| 367 | | −} |
| 368 | | − |
| 369 | | −/// C arguments for a call with these value slots: registers, padded. |
| 370 | | −fn register_args(slots: &[String]) -> String { |
| 371 | | − (0..REGS) |
| 372 | | − .map(|i| slots.get(i).cloned().unwrap_or_else(|| "TL_UNIT".into())) |
| 373 | | − .collect::<Vec<_>>() |
| 374 | | − .join(", ") |
| 375 | | −} |
| 376 | | − |
| 377 | | −/// Statements storing the slots after the sixth into `ctx->xargs`. |
| 378 | | −fn store_xargs(slots: &[String], indent: &str, out: &mut String) { |
| 379 | | − for (i, s) in slots.iter().enumerate().skip(REGS) { |
| 380 | | − let _ = writeln!(out, "{indent}ctx->xargs[{}] = {s};", i - REGS); |
| 381 | | − } |
| 382 | | −} |
| 383 | | − |
| 384 | | −impl Emitter<'_> { |
| 385 | | − fn function(&mut self, id: FnId, decl: &FnDecl) -> Result<(), Unsupported> { |
| 386 | | − if decl.params.len() > REGS + XARGS { |
| 387 | | − return Err(Unsupported(format!( |
| 388 | | − "functions with more than {} parameters (`{}`)", |
| 389 | | − REGS + XARGS, |
| 390 | | − decl.name |
| 391 | | − ))); |
| 392 | | − } |
| 393 | | − let mut out = String::new(); |
| 394 | | − let _ = writeln!(out, "/* {} */", decl.name); |
| 395 | | − self.line = decl.span.and_then(|s| self.line_of(s)); |
| 396 | | − self.written = None; |
| 397 | | − self.sync_line(&mut out); |
| 398 | | − let _ = writeln!( |
| 399 | | − out, |
| 400 | | − "TL_FN 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) {{" |
| 401 | | − ); |
| 402 | | − let params: BTreeSet<VarId> = decl.params.iter().copied().collect(); |
| 403 | | − for (i, p) in decl.params.iter().enumerate() { |
| 404 | | − if i < REGS { |
| 405 | | − let _ = writeln!(out, " tl_value v{p} = a{i};"); |
| 406 | | − } else { |
| 407 | | − let _ = writeln!(out, " tl_value v{p} = ctx->xargs[{}];", i - REGS); |
| 408 | | − } |
| 409 | | − } |
| 410 | | − for i in decl.params.len()..REGS { |
| 411 | | − let _ = writeln!(out, " (void)a{i};"); |
| 412 | | − } |
| 413 | | − // The references the frame holds on entry: borrowed parameters are |
| 414 | | − // the caller's. |
| 415 | | − let owned: Vec<VarId> = decl |
| 416 | | − .params |
| 417 | | − .iter() |
| 418 | | − .enumerate() |
| 419 | | − .filter(|(i, _)| !decl.borrowed.contains(i)) |
| 420 | | − .map(|(_, p)| *p) |
| 421 | | − .collect(); |
| 422 | | − let locals: Vec<String> = (0..decl.n_vars) |
| 423 | | − .filter(|v| !params.contains(v)) |
| 424 | | − .map(|v| format!("v{v} = TL_UNIT")) |
| 425 | | − .collect(); |
| 426 | | − for chunk in locals.chunks(8) { |
| 427 | | − let _ = writeln!(out, " tl_value {};", chunk.join(", ")); |
| 428 | | − } |
| 429 | | − // A preemption point; an exit signal unwinds from here. |
| 430 | | − if !self.never_unwinds.contains(&id) { |
| 431 | | − let _ = writeln!( |
| 432 | | − out, |
| 433 | | − "entry:\n if (tl_unlikely(--ctx->reductions <= 0)) {{\n tl_preempt(ctx);\n if (TL_YIELDING(ctx)) {}\n }}", |
| 434 | | − unwind(&owned) |
| 435 | | − ); |
| 436 | | − } |
| 437 | | − let func = Func { id, decl }; |
| 438 | | − self.expr(&mut out, &func, &decl.body, Dest::Return, owned, 1)?; |
| 439 | | − out.push_str("}\n\n"); |
| 440 | | − if self.line.is_some() { |
| 441 | | − self.located.push(pin_lines(&out)); |
| 442 | | − } else { |
| 443 | | − self.generated.push(out); |
| 444 | | − } |
| 445 | | − Ok(()) |
| 446 | | − } |
| 447 | | − |
| 448 | | − /// Where `span` starts, if `#line` directives are wanted. |
| 449 | | − fn line_of(&self, span: Span) -> Option<Line> { |
| 450 | | − let file = self.sources?.get(span.file); |
| 451 | | − Some(Line { |
| 452 | | − file: span.file, |
| 453 | | − line: file.line_col(span.range.start()).line + 1, |
| 454 | | − }) |
| 455 | | − } |
| 456 | | − |
| 457 | | − /// Point the C that follows at the current source line, if it is not |
| 458 | | − /// already. |
| 459 | | − fn sync_line(&mut self, out: &mut String) { |
| 460 | | − let (Some(line), Some(sources)) = (self.line, self.sources) else { |
| 461 | | − return; |
| 462 | | − }; |
| 463 | | − if self.written != Some(line) { |
| 464 | | − let path = sources.get(line.file).path(); |
| 465 | | − let _ = writeln!(out, "#line {} \"{}\"", line.line, c_escape(path)); |
| 466 | | − self.written = Some(line); |
| 467 | | − } |
| 468 | | − } |
| 469 | | − |
| 470 | | − /// Record `decl` as a constant if it has no parameters and only builds |
| 471 | | − /// closures without captures and tuples of them: a trait dictionary |
| 472 | | − /// without constraints, such as `Num<Int>`. It is emitted as static, |
| 473 | | − /// immortal blocks (count 0, like literals), so a call to it costs no |
| 474 | | − /// allocation and its result needs no counting. |
| 475 | | − fn constant(&mut self, id: FnId, decl: &FnDecl) { |
| 476 | | − if !decl.params.is_empty() { |
| 477 | | − return; |
| 478 | | − } |
| 479 | | − let mut defs = String::new(); |
| 480 | | − let mut entries = Vec::new(); |
| 481 | | − let mut e = &decl.body; |
| 482 | | − loop { |
| 483 | | − match e { |
| 484 | | − Expr::Let(v, value, rest, _) => { |
| 485 | | − let name = format!("tl_const{id}_{v}"); |
| 486 | | − match &**value { |
| 487 | | − Value::Closure(f, caps) if caps.is_empty() => { |
| 488 | | − entries.push(*f); |
| 489 | | − let _ = writeln!( |
| 490 | | − defs, |
| 491 | | − "static const struct {{ tl_header h; tl_closure_fn code; }} __attribute__((aligned(8))) {name} = {{ {{0, TL_TAG_CLOSURE, 0, 0}}, (tl_closure_fn)f{f}_c0 }};" |
| 492 | | − ); |
| 493 | | − } |
| 494 | | − Value::Tuple(args) if !args.is_empty() && args.len() <= 254 => { |
| 495 | | − let mut fields = Vec::new(); |
| 496 | | − for a in args { |
| 497 | | − let Atom::Var(x) = a else { return }; |
| 498 | | − fields.push(format!("(tl_value)&tl_const{id}_{x}")); |
| 499 | | − } |
| 500 | | − let _ = writeln!( |
| 501 | | − defs, |
| 502 | | − "static const struct {{ tl_header h; tl_value fields[{n}]; }} __attribute__((aligned(8))) {name} = {{ {{0, 0, {n}, 0}}, {{ {} }} }};", |
| 503 | | − fields.join(", "), |
| 504 | | − n = args.len() |
| 505 | | − ); |
| 506 | | − } |
| 507 | | − _ => return, |
| 508 | | − } |
| 509 | | − e = rest; |
| 510 | | − } |
| 511 | | − Expr::Return(Atom::Var(r)) => { |
| 512 | | − let _ = writeln!( |
| 513 | | − defs, |
| 514 | | − "/* {} */\n#define tl_const{id} ((tl_value)&tl_const{id}_{r})", |
| 515 | | − decl.name |
| 516 | | − ); |
| 517 | | − break; |
| 518 | | − } |
| 519 | | − _ => return, |
| 520 | | − } |
| 521 | | − } |
| 522 | | − // Only now: a closure's entry is emitted only if it is used. |
| 523 | | − for f in entries { |
| 524 | | − self.entries.insert((f, 0)); |
| 525 | | − } |
| 526 | | − self.constants.insert(id); |
| 527 | | − self.constant_defs.push_str(&defs); |
| 528 | | − } |
| 529 | | − |
| 530 | | − fn atom(&mut self, a: &Atom) -> Result<String, Unsupported> { |
| 531 | | − Ok(match a { |
| 532 | | − Atom::Var(v) => format!("v{v}"), |
| 533 | | − Atom::Unit => "TL_UNIT".into(), |
| 534 | | − Atom::Lit(Lit::Int(n)) => { |
| 535 | | − if !(-(1i64 << 62)..(1i64 << 62)).contains(n) { |
| 536 | | − return Err(Unsupported(format!( |
| 537 | | − "the integer literal {n} (literals are 63-bit)" |
| 538 | | − ))); |
| 539 | | − } |
| 540 | | − format!("tl_int(INT64_C({n}))") |
| 541 | | − } |
| 542 | | − Atom::Lit(Lit::String(s)) => { |
| 543 | | − let name = self.string_lit(s); |
| 544 | | − format!("((tl_value)&{name})") |
| 545 | | − } |
| 546 | | − Atom::Lit(Lit::Float(x)) => { |
| 547 | | − let name = self.float_lit(*x); |
| 548 | | − format!("((tl_value)&{name})") |
| 549 | | − } |
| 550 | | − }) |
| 551 | | − } |
| 552 | | − |
| 553 | | − fn atoms(&mut self, atoms: &[Atom]) -> Result<Vec<String>, Unsupported> { |
| 554 | | − atoms.iter().map(|a| self.atom(a)).collect() |
| 555 | | − } |
| 556 | | − |
| 557 | | − fn string_lit(&mut self, s: &str) -> String { |
| 558 | | − let key = format!("s{s}"); |
| 559 | | − if let Some(id) = self.lit_ids.get(&key) { |
| 560 | | − return format!("tl_lit{id}"); |
| 561 | | − } |
| 562 | | − let id = self.lit_ids.len(); |
| 563 | | − self.lit_ids.insert(key, id); |
| 564 | | − let _ = writeln!( |
| 565 | | − self.lits, |
| 566 | | − "static struct {{ tl_header h; int64_t len; char bytes[{}]; }} __attribute__((aligned(8))) tl_lit{id} = {{ {{0, TL_TAG_STRING, 0, 0}}, {}, \"{}\" }};", |
| 567 | | − s.len() + 1, |
| 568 | | − s.len(), |
| 569 | | − c_escape(s) |
| 570 | | − ); |
| 571 | | − format!("tl_lit{id}") |
| 572 | | − } |
| 573 | | − |
| 574 | | − fn float_lit(&mut self, x: f64) -> String { |
| 575 | | − let key = format!("f{}", x.to_bits()); |
| 576 | | − if let Some(id) = self.lit_ids.get(&key) { |
| 577 | | − return format!("tl_lit{id}"); |
| 578 | | − } |
| 579 | | − let id = self.lit_ids.len(); |
| 580 | | − self.lit_ids.insert(key, id); |
| 581 | | − let _ = writeln!( |
| 582 | | − self.lits, |
| 583 | | − "static struct {{ tl_header h; double x; }} __attribute__((aligned(8))) tl_lit{id} = {{ {{0, TL_TAG_FLOAT, 0, 0}}, {x:e} }};" |
| 584 | | − ); |
| 585 | | − format!("tl_lit{id}") |
| 586 | | − } |
| 587 | | − |
| 588 | | − /// Code calling a closure value `f` (consumed) with `args`. |
| 589 | | − fn closure_call(f: &str, args: &[String], indent: &str, out: &mut String) -> String { |
| 590 | | − let mut slots = vec![f.to_owned()]; |
| 591 | | − slots.extend(args.iter().cloned()); |
| 592 | | − store_xargs(&slots, indent, out); |
| 593 | | − format!( |
| 594 | | − "((tl_fn)tl_closure_code({f}))(ctx, {})", |
| 595 | | − register_args(&slots) |
| 596 | | − ) |
| 597 | | − } |
| 598 | | − |
| 599 | | − /// Emit `e`. `held` are the references the frame holds before it (a |
| 600 | | − /// multiset, as in `tilc_perceus::verify`): what an unwind from inside |
| 601 | | − /// `e` must drop. Returns the references held when a block's value is |
| 602 | | − /// produced (`Dest::Assign`), or `None` if every path leaves the |
| 603 | | − /// function. |
| 604 | | − fn expr( |
| 605 | | − &mut self, |
| 606 | | − out: &mut String, |
| 607 | | − f: &Func, |
| 608 | | − e: &Expr, |
| 609 | | − dest: Dest, |
| 610 | | − mut held: Vec<VarId>, |
| 611 | | − depth: usize, |
| 612 | | − ) -> Result<Option<Vec<VarId>>, Unsupported> { |
| 613 | | − let ind = " ".repeat(depth); |
| 614 | | − // Statements are emitted in a loop, not by recursion: a function |
| 615 | | − // can be a long sequence of them. |
| 616 | | − let mut e = e; |
| 617 | | − loop { |
| 618 | | − if self.line.is_some() |
| 619 | | − && let Some(span) = statement_span(e) |
| 620 | | − { |
| 621 | | − self.line = self.line_of(span); |
| 622 | | − } |
| 623 | | − self.sync_line(out); |
| 624 | | − match e { |
| 625 | | − Expr::Let(v, value, rest, _) => { |
| 626 | | − let tail = matches!(dest, Dest::Return) |
| 627 | | − && matches!(&**rest, Expr::Return(Atom::Var(r)) if r == v); |
| 628 | | − if tail { |
| 629 | | − match &**value { |
| 630 | | − Value::Block(inner) => { |
| 631 | | − e = inner; |
| 632 | | − continue; |
| 633 | | − } |
| 634 | | − Value::CallFn(g, args) if *g == f.id => { |
| 635 | | − // Self tail call: a jump. Perceus consumed or |
| 636 | | − // dropped everything else before it. |
| 637 | | − let args = self.atoms(args)?; |
| 638 | | − let _ = writeln!(out, "{ind}{{"); |
| 639 | | − for (i, a) in args.iter().enumerate() { |
| 640 | | − let _ = writeln!(out, "{ind} tl_value t{i} = {a};"); |
| 641 | | − } |
| 642 | | − for (i, p) in f.decl.params.iter().enumerate() { |
| 643 | | − let _ = writeln!(out, "{ind} v{p} = t{i};"); |
| 644 | | − } |
| 645 | | − let _ = writeln!(out, "{ind} goto entry;\n{ind}}}"); |
| 646 | | − return Ok(None); |
| 647 | | − } |
| 648 | | − Value::CallFn(g, args) if !self.constants.contains(g) => { |
| 649 | | − let slots = self.atoms(args)?; |
| 650 | | − store_xargs(&slots, &ind, out); |
| 651 | | − let _ = writeln!( |
| 652 | | − out, |
| 653 | | − "{ind}TL_MUSTTAIL return f{g}(ctx, {});", |
| 654 | | − register_args(&slots) |
| 655 | | − ); |
| 656 | | − return Ok(None); |
| 657 | | − } |
| 658 | | − Value::Call(c, args) => { |
| 659 | | − let c = self.atom(c)?; |
| 660 | | − let args = self.atoms(args)?; |
| 661 | | − let call = Self::closure_call(&c, &args, &ind, out); |
| 662 | | − let _ = writeln!(out, "{ind}TL_MUSTTAIL return {call};"); |
| 663 | | − return Ok(None); |
| 664 | | − } |
| 665 | | − _ => {} |
| 666 | | − } |
| 667 | | − } |
| 668 | | − if let Value::Block(inner) = &**value { |
| 669 | | − self.labels += 1; |
| 670 | | − let label = self.labels; |
| 671 | | − let line = self.line; |
| 672 | | − let after = |
| 673 | | − self.expr(out, f, inner, Dest::Assign(*v, label), held, depth)?; |
| 674 | | − self.line = line; |
| 675 | | − let _ = writeln!(out, "{ind}b{label}:;"); |
| 676 | | − let Some(mut after) = after else { |
| 677 | | − // Every path through the block leaves the function. |
| 678 | | − return Ok(None); |
| 679 | | − }; |
| 680 | | − after.push(*v); |
| 681 | | − held = after; |
| 682 | | − e = rest; |
| 683 | | − continue; |
| 684 | | − } |
| 685 | | − let (owned, _) = tilc_perceus::uses(value, self.program); |
| 686 | | − for o in owned { |
| 687 | | − take(&mut held, o); |
| 688 | | − } |
| 689 | | − self.value(out, *v, value, &ind, &held)?; |
| 690 | | − if self.may_unwind(value) { |
| 691 | | − let _ = writeln!(out, "{ind}if (TL_YIELDING(ctx)) {}", unwind(&held)); |
| 692 | | − } |
| 693 | | − // A projection is borrowed (a `dup` follows if it is owned). |
| 694 | | − if !matches!(&**value, Value::Field(..)) { |
| 695 | | − held.push(*v); |
| 696 | | − } |
| 697 | | − e = rest; |
| 698 | | − } |
| 699 | | − Expr::Return(a) => { |
| 700 | | − if let Atom::Var(x) = a { |
| 701 | | − take(&mut held, *x); |
| 702 | | − } |
| 703 | | − let a = self.atom(a)?; |
| 704 | | − match dest { |
| 705 | | − Dest::Return => { |
| 706 | | − let _ = writeln!(out, "{ind}return {a};"); |
| 707 | | − return Ok(None); |
| 708 | | − } |
| 709 | | − Dest::Assign(v, label) => { |
| 710 | | − let _ = writeln!(out, "{ind}v{v} = {a};\n{ind}goto b{label};"); |
| 711 | | − return Ok(Some(held)); |
| 712 | | − } |
| 713 | | − } |
| 714 | | − } |
| 715 | | − Expr::Dup(v, rest) => { |
| 716 | | − let _ = writeln!(out, "{ind}tl_dup(v{v});"); |
| 717 | | − held.push(*v); |
| 718 | | − e = rest; |
| 719 | | − } |
| 720 | | − Expr::Drop(v, rest) => { |
| 721 | | − let _ = writeln!(out, "{ind}tl_drop(ctx, v{v});"); |
| 722 | | − take(&mut held, *v); |
| 723 | | − e = rest; |
| 724 | | − } |
| 725 | | − Expr::Release { |
| 726 | | − var, |
| 727 | | − fields, |
| 728 | | − token, |
| 729 | | − rest, |
| 730 | | − } => { |
| 731 | | − Self::release(out, *var, fields, *token, &ind); |
| 732 | | − take(&mut held, *var); |
| 733 | | − held.extend(fields.iter().map(|(_, a)| *a)); |
| 734 | | − held.extend(token); |
| 735 | | − e = rest; |
| 736 | | − } |
| 737 | | − Expr::Panic(msg) => { |
| 738 | | − let _ = writeln!( |
| 739 | | − out, |
| 740 | | − "{ind}tl_panic_str(ctx, \"{}\");\n{ind}{}", |
| 741 | | − c_escape(msg), |
| 742 | | − unwind(&held) |
| 743 | | − ); |
| 744 | | − return Ok(None); |
| 745 | | − } |
| 746 | | − Expr::Switch { on, cases, default } => { |
| 747 | | − let on = self.atom(on)?; |
| 748 | | − let mut after = None; |
| 749 | | − let _ = writeln!(out, "{ind}switch (tl_tag_of({on})) {{"); |
| 750 | | − let line = self.line; |
| 751 | | − for (tag, body) in cases { |
| 752 | | − self.line = line; |
| 753 | | − self.sync_line(out); |
| 754 | | − let _ = writeln!(out, "{ind}case {tag}: {{"); |
| 755 | | − let a = self.expr(out, f, body, dest, held.clone(), depth + 1)?; |
| 756 | | − after = after.or(a); |
| 757 | | − let _ = writeln!(out, "{ind}}}"); |
| 758 | | − } |
| 759 | | − self.line = line; |
| 760 | | − self.sync_line(out); |
| 761 | | − match default { |
| 762 | | − Some(d) => { |
| 763 | | − let _ = writeln!(out, "{ind}default: {{"); |
| 764 | | − let a = self.expr(out, f, d, dest, held, depth + 1)?; |
| 765 | | − after = after.or(a); |
| 766 | | − let _ = writeln!(out, "{ind}}}"); |
| 767 | | − } |
| 768 | | − None => { |
| 769 | | − let _ = writeln!(out, "{ind}default: __builtin_unreachable();"); |
| 770 | | − } |
| 771 | | − } |
| 772 | | − let _ = writeln!(out, "{ind}}}"); |
| 773 | | − return Ok(after); |
| 774 | | − } |
| 775 | | − Expr::SwitchLit { on, cases, default } => { |
| 776 | | − if cases.is_empty() { |
| 777 | | − e = default; |
| 778 | | − continue; |
| 779 | | − } |
| 780 | | − let on = self.atom(on)?; |
| 781 | | − let mut after = None; |
| 782 | | − let line = self.line; |
| 783 | | − for (i, (lit, body)) in cases.iter().enumerate() { |
| 784 | | − self.line = line; |
| 785 | | − self.sync_line(out); |
| 786 | | − let test = match lit { |
| 787 | | − Lit::Int(n) => format!("{on} == tl_int(INT64_C({n}))"), |
| 788 | | − Lit::Float(x) => format!("tl_float_get({on}) == {x:e}"), |
| 789 | | − Lit::String(s) => { |
| 790 | | − format!("tl_str_is({on}, \"{}\", {})", c_escape(s), s.len()) |
| 791 | | − } |
| 792 | | − }; |
| 793 | | − let kw = if i == 0 { "if" } else { "} else if" }; |
| 794 | | − let _ = writeln!(out, "{ind}{kw} ({test}) {{"); |
| 795 | | − let a = self.expr(out, f, body, dest, held.clone(), depth + 1)?; |
| 796 | | − after = after.or(a); |
| 797 | | − } |
| 798 | | − self.line = line; |
| 799 | | − self.sync_line(out); |
| 800 | | − let _ = writeln!(out, "{ind}}} else {{"); |
| 801 | | − let a = self.expr(out, f, default, dest, held, depth + 1)?; |
| 802 | | − after = after.or(a); |
| 803 | | − let _ = writeln!(out, "{ind}}}"); |
| 804 | | − return Ok(after); |
| 805 | | − } |
| 806 | | − } |
| 807 | | − } |
| 808 | | − } |
| 809 | | − |
| 810 | | − /// `release x [fields]` (drop specialisation), keeping a unique cell |
| 811 | | − /// as `token` if there is one. |
| 812 | | − fn release( |
| 813 | | − out: &mut String, |
| 814 | | − var: VarId, |
| 815 | | − fields: &[(u32, VarId)], |
| 816 | | − token: Option<VarId>, |
| 817 | | − ind: &str, |
| 818 | | − ) { |
| 819 | | − // Unique: move the fields out and free (or keep) the cell. |
| 820 | | − // Shared: the fields take references of their own. |
| 821 | | − let _ = writeln!(out, "{ind}if (tl_is_unique(v{var})) {{"); |
| 822 | | − for (i, _) in fields { |
| 823 | | − let _ = writeln!(out, "{ind} tl_as_block(v{var})->fields[{i}] = TL_UNIT;"); |
| 824 | | − } |
| 825 | | − match token { |
| 826 | | − Some(t) => { |
| 827 | | − let _ = writeln!( |
| 828 | | − out, |
| 829 | | − "{ind} v{t} = tl_reuse_token(ctx, tl_as_block(v{var}));" |
| 830 | | − ); |
| 831 | | − } |
| 832 | | − None => { |
| 833 | | − let _ = writeln!( |
| 834 | | − out, |
| 835 | | − "{ind} tl_free_moved(ctx, tl_as_block(v{var}), {});", |
| 836 | | − fields.len() |
| 837 | | − ); |
| 838 | | − } |
| 839 | | − } |
| 840 | | − let _ = writeln!(out, "{ind}}} else {{"); |
| 841 | | − for (_, a) in fields { |
| 842 | | − let _ = writeln!(out, "{ind} tl_dup(v{a});"); |
| 843 | | − } |
| 844 | | − let _ = writeln!(out, "{ind} tl_drop(ctx, v{var});"); |
| 845 | | − if let Some(t) = token { |
| 846 | | − let _ = writeln!(out, "{ind} v{t} = TL_UNIT;"); |
| 847 | | − } |
| 848 | | − let _ = writeln!(out, "{ind}}}"); |
| 849 | | − } |
| 850 | | − |
| 851 | | − /// Whether computing `value` may start or continue unwinding. |
| 852 | | − fn may_unwind(&self, value: &Value) -> bool { |
| 853 | | − match value { |
| 854 | | − Value::CallFn(g, _) => !self.constants.contains(g) && !self.never_unwinds.contains(g), |
| 855 | | − value => crate::unwind::may_unwind_itself(self.program, value), |
| 856 | | − } |
| 857 | | − } |
| 858 | | − |
| 859 | | − /// `v = value;` (not a block). `held`: references held during it, |
| 860 | | − /// for the unwinding paths it contains. |
| 861 | | − fn value( |
| 862 | | − &mut self, |
| 863 | | − out: &mut String, |
| 864 | | − v: VarId, |
| 865 | | − value: &Value, |
| 866 | | − ind: &str, |
| 867 | | − held: &[VarId], |
| 868 | | − ) -> Result<(), Unsupported> { |
| 869 | | − match value { |
| 870 | | − Value::Atom(a) => { |
| 871 | | − let a = self.atom(a)?; |
| 872 | | − let _ = writeln!(out, "{ind}v{v} = {a};"); |
| 873 | | − } |
| 874 | | − Value::CallFn(g, _) if self.constants.contains(g) => { |
| 875 | | − let _ = writeln!(out, "{ind}v{v} = tl_const{g};"); |
| 876 | | − } |
| 877 | | − Value::CallFn(g, args) => { |
| 878 | | − let slots = self.atoms(args)?; |
| 879 | | − store_xargs(&slots, ind, out); |
| 880 | | − let _ = writeln!(out, "{ind}v{v} = f{g}(ctx, {});", register_args(&slots)); |
| 881 | | − } |
| 882 | | − Value::Call(c, args) => { |
| 883 | | − let c = self.atom(c)?; |
| 884 | | − let args = self.atoms(args)?; |
| 885 | | − let call = Self::closure_call(&c, &args, ind, out); |
| 886 | | − let _ = writeln!(out, "{ind}v{v} = {call};"); |
| 887 | | − } |
| 888 | | − Value::CallExtern(sym, args) => { |
| 889 | | − if !DECLARED.contains(&sym.as_str()) { |
| 890 | | − match self.externs.get(sym) { |
| 891 | | − Some(n) if *n != args.len() => { |
| 892 | | − return Err(Unsupported(format!( |
| 893 | | − "calling extern `{sym}` with {} and {n} arguments", |
| 894 | | − args.len() |
| 895 | | − ))); |
| 896 | | − } |
| 897 | | − _ => { |
| 898 | | − self.externs.insert(sym.clone(), args.len()); |
| 899 | | − } |
| 900 | | − } |
| 901 | | − } |
| 902 | | − let args = self.atoms(args)?; |
| 903 | | − if self.program.blocking.contains(sym) { |
| 904 | | − // Run it on the blocking pool (ADR 0005). |
| 905 | | − let thunk = format!("tl_blocking_{sym}"); |
| 906 | | − if !self.thunks.contains(&format!(" {thunk}(")) { |
| 907 | | − let call: Vec<String> = |
| 908 | | − (0..args.len()).map(|i| format!("a[{i}]")).collect(); |
| 909 | | − let mut all = vec!["ctx".to_owned()]; |
| 910 | | − all.extend(call); |
| 911 | | − let _ = writeln!( |
| 912 | | − self.thunks, |
| 913 | | − "static tl_value {thunk}(tl_ctx *ctx, const tl_value *a) {{ (void)a; return {sym}({}); }}", |
| 914 | | − all.join(", ") |
| 915 | | − ); |
| 916 | | − } |
| 917 | | − let list = if args.is_empty() { |
| 918 | | − "TL_UNIT".to_owned() |
| 919 | | − } else { |
| 920 | | − args.join(", ") |
| 921 | | − }; |
| 922 | | − let _ = writeln!( |
| 923 | | − out, |
| 924 | | − "{ind}{{\n{ind} tl_value args[] = {{{list}}};\n{ind} v{v} = tl_call_blocking(ctx, {thunk}, {}, args);\n{ind}}}", |
| 925 | | − args.len() |
| 926 | | − ); |
| 927 | | − } else { |
| 928 | | − let mut all = vec!["ctx".to_owned()]; |
| 929 | | − all.extend(args); |
| 930 | | − let _ = writeln!(out, "{ind}v{v} = {sym}({});", all.join(", ")); |
| 931 | | − } |
| 932 | | − } |
| 933 | | − Value::Prim(p, args) => { |
| 934 | | − let a = self.atom(&args[0])?; |
| 935 | | − let text = match p { |
| 936 | | − Prim::Not => format!("({a} == TL_TRUE) ? TL_FALSE : TL_TRUE"), |
| 937 | | − Prim::TagIs(t) => format!("tl_tag_of({a}) == {t} ? TL_TRUE : TL_FALSE"), |
| 938 | | − Prim::Tag => format!("tl_int(tl_tag_of({a}))"), |
| 939 | | − }; |
| 940 | | − let _ = writeln!(out, "{ind}v{v} = {text};"); |
| 941 | | − } |
| 942 | | − Value::Construct { tag, args, .. } => { |
| 943 | | − let args = self.atoms(args)?; |
| 944 | | − self.block(out, v, *tag, &args, ind)?; |
| 945 | | − } |
| 946 | | − Value::Tuple(args) => { |
| 947 | | − let args = self.atoms(args)?; |
| 948 | | − self.block(out, v, 0, &args, ind)?; |
| 949 | | − } |
| 950 | | − Value::Field(base, i) => { |
| 951 | | − let b = self.atom(base)?; |
| 952 | | − let _ = writeln!(out, "{ind}v{v} = tl_as_block({b})->fields[{i}];"); |
| 953 | | − } |
| 954 | | − Value::Reuse { token, value } => { |
| 955 | | − let (tag, args) = match &**value { |
| 956 | | − Value::Construct { tag, args, .. } => (*tag, args), |
| 957 | | − Value::Tuple(args) => (0, args), |
| 958 | | − _ => unreachable!("only constructions reuse cells"), |
| 959 | | − }; |
| 960 | | − let args = self.atoms(args)?; |
| 961 | | − Self::check_block(tag, args.len())?; |
| 962 | | − // In place if the token is a unique cell of the same size (a |
| 963 | | − // copied `multi ctl` continuation shares its tokens). |
| 964 | | − let n = args.len(); |
| 965 | | − let _ = writeln!( |
| 966 | | − out, |
| 967 | | − "{ind}if (tl_is_unique(v{token}) && tl_as_block(v{token})->h.scan_fsize == {n}) {{\n{ind} v{v} = v{token};\n{ind} tl_as_block(v{v})->h.tag = {tag};\n{ind}}} else {{\n{ind} tl_drop(ctx, v{token});\n{ind} v{v} = tl_from_block(tl_alloc(ctx, {tag}, {n}, 0));\n{ind}}}" |
| 968 | | − ); |
| 969 | | − for (i, a) in args.iter().enumerate() { |
| 970 | | − let _ = writeln!(out, "{ind}tl_as_block(v{v})->fields[{i}] = {a};"); |
| 971 | | − } |
| 972 | | − } |
| 973 | | − Value::Closure(fid, caps) => { |
| 974 | | − let caps = self.atoms(caps)?; |
| 975 | | − if caps.len() > 254 { |
| 976 | | − return Err(Unsupported( |
| 977 | | − "closures capturing more than 254 values".into(), |
| 978 | | − )); |
| 979 | | − } |
| 980 | | − self.entries.insert((*fid, caps.len())); |
| 981 | | − let _ = writeln!( |
| 982 | | − out, |
| 983 | | − "{ind}v{v} = tl_closure_alloc(ctx, (tl_closure_fn)f{fid}_c{}, {});", |
| 984 | | − caps.len(), |
| 985 | | − caps.len() |
| 986 | | − ); |
| 987 | | − for (i, c) in caps.iter().enumerate() { |
| 988 | | − let _ = writeln!(out, "{ind}tl_as_block(v{v})->fields[{i}] = {c};"); |
| 989 | | − } |
| 990 | | − } |
| 991 | | − Value::Perform { |
| 992 | | − cap, |
| 993 | | − effect, |
| 994 | | − op, |
| 995 | | − args, |
| 996 | | − } => { |
| 997 | | − let decl = &self.program.effects[*effect as usize]; |
| 998 | | − let n_ops = decl.ops.len(); |
| 999 | | − let kind = decl.ops[*op as usize].1; |
| 1000 | | − let cap = self.atom(cap)?; |
| 1001 | | − let args = self.atoms(args)?; |
| 1002 | | − let op_name = decl.ops[*op as usize].0.as_str(); |
| 1003 | | − match (decl.name.as_str(), op_name, kind) { |
| 1004 | | − ("std/ref.alloc", _, _) => { |
| 1005 | | − let _ = writeln!(out, "{ind}v{v} = tl_ref_new(ctx, {cap}, {});", args[0]); |
| 1006 | | − } |
| 1007 | | − ("std/ref.st", "get", _) => { |
| 1008 | | − let _ = writeln!( |
| 1009 | | − out, |
| 1010 | | − "{ind}v{v} = tl_ref_get(ctx, {r});\n{ind}tl_drop(ctx, {r});", |
| 1011 | | − r = args[0] |
| 1012 | | − ); |
| 1013 | | − } |
| 1014 | | − ("std/ref.st", _, _) => { |
| 1015 | | − let _ = writeln!( |
| 1016 | | − out, |
| 1017 | | − "{ind}v{v} = tl_ref_set(ctx, {r}, {x});\n{ind}tl_drop(ctx, {r});", |
| 1018 | | − r = args[0], |
| 1019 | | − x = args[1] |
| 1020 | | − ); |
| 1021 | | − } |
| 1022 | | − (_, _, OpKind::Ctl | OpKind::Multi) => { |
| 1023 | | − // Suspend to the handler's fiber with the |
| 1024 | | − // operation's index and arguments. |
| 1025 | | − let mut payload = vec![format!("tl_int({op})")]; |
| 1026 | | − payload.extend(args); |
| 1027 | | − self.block(out, v, 0, &payload, ind)?; |
| 1028 | | − let _ = writeln!(out, "{ind}v{v} = tl_perform_ctl(ctx, {cap}, v{v});"); |
| 1029 | | − } |
| 1030 | | − (_, _, OpKind::FinalCtl) => { |
| 1031 | | − // Unwind to the handler: the payload is the |
| 1032 | | − // operation's index and arguments. |
| 1033 | | − let mut payload = vec![format!("tl_int({op})")]; |
| 1034 | | − payload.extend(args); |
| 1035 | | − let _ = writeln!(out, "{ind}{{"); |
| 1036 | | − let inner = format!("{ind} "); |
| 1037 | | − self.block(out, v, 0, &payload, &inner)?; |
| 1038 | | − let _ = writeln!( |
| 1039 | | − out, |
| 1040 | | − "{inner}uint64_t marker = (uint64_t)tl_int_get(tl_as_block({cap})->fields[{n_ops}]);\n{inner}v{v} = tl_yield_final(ctx, marker, v{v});\n{ind}}}" |
| 1041 | | − ); |
| 1042 | | − } |
| 1043 | | − _ => { |
| 1044 | | − // A `fn` operation: call the clause in the handler. |
| 1045 | | − let clause = format!("tl_dup(tl_as_block({cap})->fields[{op}])"); |
| 1046 | | − let _ = writeln!(out, "{ind}{{\n{ind} tl_value clause = {clause};"); |
| 1047 | | − let inner = format!("{ind} "); |
| 1048 | | − let call = Self::closure_call("clause", &args, &inner, out); |
| 1049 | | − let _ = writeln!(out, "{inner}v{v} = {call};\n{ind}}}"); |
| 1050 | | − } |
| 1051 | | − } |
| 1052 | | − } |
| 1053 | | − Value::Handle { |
| 1054 | | − body, |
| 1055 | | − ret, |
| 1056 | | − clauses, |
| 1057 | | − effect, |
| 1058 | | − } => { |
| 1059 | | − let body = self.atom(body)?; |
| 1060 | | − let ret = ret.as_ref().map(|r| self.atom(r)).transpose()?; |
| 1061 | | − let mut fields = self.atoms(clauses)?; |
| 1062 | | − // The capability: the clauses, then the handler's marker |
| 1063 | | − // (what `final ctl` operations unwind to). |
| 1064 | | − fields.push("tl_int((int64_t)marker)".into()); |
| 1065 | | − let catches = self.program.effects[*effect as usize] |
| 1066 | | − .ops |
| 1067 | | − .iter() |
| 1068 | | − .any(|(_, k)| *k == OpKind::FinalCtl); |
| 1069 | | − let _ = writeln!(out, "{ind}{{"); |
| 1070 | | − let inner = format!("{ind} "); |
| 1071 | | − let _ = writeln!(out, "{inner}uint64_t marker = tl_fresh_marker(ctx);"); |
| 1072 | | − // Tagged as a capability, so it is never sent to another |
| 1073 | | − // actor (its clauses and marker belong to this stack). |
| 1074 | | − let _ = writeln!( |
| 1075 | | − out, |
| 1076 | | − "{inner}v{v} = tl_from_block(tl_alloc(ctx, TL_TAG_CAP, {}, 0));", |
| 1077 | | − fields.len() |
| 1078 | | − ); |
| 1079 | | − for (i, a) in fields.iter().enumerate() { |
| 1080 | | − let _ = writeln!(out, "{inner}tl_as_block(v{v})->fields[{i}] = {a};"); |
| 1081 | | − } |
| 1082 | | − let ops = &self.program.effects[*effect as usize].ops; |
| 1083 | | − let has = |kind: OpKind| ops.iter().any(|(_, k)| *k == kind); |
| 1084 | | − if has(OpKind::Ctl) || has(OpKind::Multi) { |
| 1085 | | − // The runtime runs the body on a fiber and calls the |
| 1086 | | − // clauses (handlers.rs). |
| 1087 | | − let ret = ret.unwrap_or_else(|| "TL_UNIT".into()); |
| 1088 | | − let call = if has(OpKind::Multi) { |
| 1089 | | − if ops.len() > 64 { |
| 1090 | | − return Err(Unsupported( |
| 1091 | | − "effects with `multi ctl` operations and more than 64 operations" |
| 1092 | | − .into(), |
| 1093 | | − )); |
| 1094 | | − } |
| 1095 | | − let mask: u64 = ops |
| 1096 | | − .iter() |
| 1097 | | − .enumerate() |
| 1098 | | − .filter(|(_, (_, k))| *k == OpKind::Multi) |
| 1099 | | − .map(|(i, _)| 1 << i) |
| 1100 | | − .sum(); |
| 1101 | | − format!( |
| 1102 | | − "tl_handle_multi(ctx, {body}, v{v}, {ret}, marker, UINT64_C({mask}))" |
| 1103 | | − ) |
| 1104 | | − } else { |
| 1105 | | − format!("tl_handle_ctl(ctx, {body}, v{v}, {ret}, marker)") |
| 1106 | | − }; |
| 1107 | | − let _ = writeln!(out, "{inner}v{v} = {call};\n{ind}}}"); |
| 1108 | | − return Ok(()); |
| 1109 | | − } |
| 1110 | | − let _ = writeln!(out, "{inner}tl_value cap = tl_dup(v{v});"); |
| 1111 | | − let call = |
| 1112 | | − Self::closure_call(&body, &["v".to_owned() + &v.to_string()], &inner, out); |
| 1113 | | − let _ = writeln!(out, "{inner}v{v} = {call};"); |
| 1114 | | − let _ = writeln!(out, "{inner}if (TL_YIELDING(ctx)) {{"); |
| 1115 | | − if catches { |
| 1116 | | − let _ = writeln!( |
| 1117 | | − out, |
| 1118 | | − "{inner} tl_value payload;\n{inner} if (tl_catch_final(ctx, marker, &payload)) {{\n{inner} tl_value clause = tl_dup(tl_as_block(cap)->fields[tl_int_get(tl_as_block(payload)->fields[0])]);\n{inner} v{v} = tl_call_payload(ctx, clause, payload);\n{inner} }}" |
| 1119 | | − ); |
| 1120 | | − } |
| 1121 | | − let _ = writeln!(out, "{inner}}} else {{"); |
| 1122 | | − if let Some(r) = ret { |
| 1123 | | − let deeper = format!("{inner} "); |
| 1124 | | − let call = Self::closure_call(&r, &[format!("v{v}")], &deeper, out); |
| 1125 | | − let _ = writeln!(out, "{deeper}v{v} = {call};"); |
| 1126 | | − } else { |
| 1127 | | − let _ = writeln!(out, "{inner} /* no return clause */"); |
| 1128 | | − } |
| 1129 | | − let _ = writeln!(out, "{inner}}}\n{inner}TL_UNWIND_DROP(ctx, cap);\n{ind}}}"); |
| 1130 | | − let _ = held; |
| 1131 | | − } |
| 1132 | | − Value::Region { body, .. } => { |
| 1133 | | − let body = self.atom(body)?; |
| 1134 | | − let _ = writeln!(out, "{ind}{{\n{ind} tl_value region = tl_region_new(ctx);"); |
| 1135 | | − let inner = format!("{ind} "); |
| 1136 | | − let call = Self::closure_call(&body, &["tl_dup(region)".into()], &inner, out); |
| 1137 | | − // The region ends whether its body returns or unwinds. |
| 1138 | | − let _ = writeln!( |
| 1139 | | − out, |
| 1140 | | − "{inner}v{v} = {call};\n{inner}tl_region_exit(ctx, region);\n{ind}}}" |
| 1141 | | − ); |
| 1142 | | − } |
| 1143 | | − Value::Defer { body, cleanup } => { |
| 1144 | | − // The runtime runs the cleanup after the body, setting aside |
| 1145 | | − // and then resuming any unwinding (ADR 0016). |
| 1146 | | − let body = self.atom(body)?; |
| 1147 | | − let cleanup = self.atom(cleanup)?; |
| 1148 | | − let _ = writeln!(out, "{ind}{{\n{ind} tl_value cleanup = {cleanup};"); |
| 1149 | | − let inner = format!("{ind} "); |
| 1150 | | − let call = Self::closure_call(&body, &[], &inner, out); |
| 1151 | | − let _ = writeln!( |
| 1152 | | − out, |
| 1153 | | − "{inner}v{v} = {call};\n{inner}v{v} = tl_defer(ctx, v{v}, cleanup);\n{ind}}}" |
| 1154 | | − ); |
| 1155 | | − } |
| 1156 | | − Value::Block(_) => unreachable!("blocks are emitted by `expr`"), |
| 1157 | | − } |
| 1158 | | − Ok(()) |
| 1159 | | − } |
| 1160 | | − |
| 1161 | | − /// `v = Constructor(args)`: a heap block, or a tagged int if nullary. |
| 1162 | | − fn block( |
| 1163 | | − &mut self, |
| 1164 | | − out: &mut String, |
| 1165 | | − v: VarId, |
| 1166 | | − tag: u32, |
| 1167 | | − args: &[String], |
| 1168 | | − ind: &str, |
| 1169 | | − ) -> Result<(), Unsupported> { |
| 1170 | | − if args.is_empty() { |
| 1171 | | − let _ = writeln!(out, "{ind}v{v} = tl_int({tag});"); |
| 1172 | | − return Ok(()); |
| 1173 | | − } |
| 1174 | | − Self::check_block(tag, args.len())?; |
| 1175 | | − let _ = writeln!( |
| 1176 | | − out, |
| 1177 | | − "{ind}v{v} = tl_from_block(tl_alloc(ctx, {tag}, {}, 0));", |
| 1178 | | − args.len() |
| 1179 | | − ); |
| 1180 | | − for (i, a) in args.iter().enumerate() { |
| 1181 | | − let _ = writeln!(out, "{ind}tl_as_block(v{v})->fields[{i}] = {a};"); |
| 1182 | | − } |
| 1183 | | − Ok(()) |
| 1184 | | − } |
| 1185 | | − |
| 1186 | | − fn check_block(tag: u32, fields: usize) -> Result<(), Unsupported> { |
| 1187 | | − if fields > 254 || tag >= 0xFF00 { |
| 1188 | | − return Err(Unsupported("constructors with more than 254 fields".into())); |
| 1189 | | − } |
| 1190 | | − Ok(()) |
| 1191 | | − } |
| 1192 | | − |
| 1193 | | − /// The entry of closures of `f` capturing `n` values: unpack the |
| 1194 | | − /// closure (first argument), then tail-call `f` with captures first. |
| 1195 | | − fn closure_entry(&self, out: &mut String, f: FnId, n: usize) { |
| 1196 | | − let total = self.program.fns[f as usize].params.len(); |
| 1197 | | − let _ = writeln!( |
| 1198 | | − out, |
| 1199 | | − "TL_FN 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) {{" |
| 1200 | | − ); |
| 1201 | | − // Incoming slots: the closure, then the call's arguments. |
| 1202 | | − let incoming = 1 + total.saturating_sub(n); |
| 1203 | | − let mut slots: Vec<String> = Vec::new(); |
| 1204 | | − for i in 0..incoming { |
| 1205 | | − if i < REGS { |
| 1206 | | − slots.push(format!("a{i}")); |
| 1207 | | − } else { |
| 1208 | | − let _ = writeln!(out, " tl_value x{i} = ctx->xargs[{}];", i - REGS); |
| 1209 | | − slots.push(format!("x{i}")); |
| 1210 | | − } |
| 1211 | | − } |
| 1212 | | − for i in incoming..REGS { |
| 1213 | | − let _ = writeln!(out, " (void)a{i};"); |
| 1214 | | − } |
| 1215 | | − let mut outgoing = Vec::new(); |
| 1216 | | − for i in 0..n { |
| 1217 | | − let _ = writeln!( |
| 1218 | | − out, |
| 1219 | | − " tl_value c{i} = tl_dup(tl_as_block(a0)->fields[{i}]);" |
| 1220 | | − ); |
| 1221 | | − outgoing.push(format!("c{i}")); |
| 1222 | | − } |
| 1223 | | − let _ = writeln!(out, " tl_drop(ctx, a0);"); |
| 1224 | | − outgoing.extend(slots.into_iter().skip(1)); |
| 1225 | | − store_xargs(&outgoing, " ", out); |
| 1226 | | − let _ = writeln!( |
| 1227 | | − out, |
| 1228 | | − " TL_MUSTTAIL return f{f}(ctx, {});\n}}\n", |
| 1229 | | − register_args(&outgoing) |
| 1230 | | − ); |
| 1231 | | − } |
| 1232 | | −} |
| 1233 | | − |
| 1234 | | −/// The span of the statement `e` starts with: a `let`'s, also for the |
| 1235 | | −/// `dup`s, `drop`s and `release`s Perceus put before it. |
| 1236 | | −fn statement_span(e: &Expr) -> Option<Span> { |
| 1237 | | − match e { |
| 1238 | | − Expr::Let(_, _, _, span) => *span, |
| 1239 | | − Expr::Dup(_, rest) | Expr::Drop(_, rest) | Expr::Release { rest, .. } => { |
| 1240 | | − statement_span(rest) |
| 1241 | | − } |
| 1242 | | − _ => None, |
| 1243 | | − } |
| 1244 | | −} |
| 1245 | | − |
| 1246 | | −/// Keep every line after a `#line N` directive on line `N`: C numbers |
| 1247 | | −/// the lines after a directive `N`, `N + 1`, ..., but all the C from one |
| 1248 | | −/// source line belongs to that line. So each further line gets its own |
| 1249 | | −/// `#line N`. Lines are never split, so no directive comes between an |
| 1250 | | −/// attribute (`TL_MUSTTAIL`) and its statement. |
| 1251 | | −fn pin_lines(c: &str) -> String { |
| 1252 | | − let mut out = String::with_capacity(c.len() * 2); |
| 1253 | | − let mut pinned: Option<&str> = None; |
| 1254 | | − let mut after_directive = false; |
| 1255 | | − for line in c.lines() { |
| 1256 | | − if let Some(rest) = line.strip_prefix("#line ") { |
| 1257 | | − pinned = rest.split(' ').next(); |
| 1258 | | − after_directive = true; |
| 1259 | | − } else { |
| 1260 | | − if let Some(n) = pinned |
| 1261 | | − && !after_directive |
| 1262 | | − && !line.is_empty() |
| 1263 | | − { |
| 1264 | | − let _ = writeln!(out, "#line {n}"); |
| 1265 | | − } |
| 1266 | | − after_directive = false; |
| 1267 | | − } |
| 1268 | | − out.push_str(line); |
| 1269 | | − out.push('\n'); |
| 1270 | | − } |
| 1271 | | − out |
| 1272 | | −} |
| 1273 | | − |
| 1274 | | −/// A C string literal body: printable ASCII as is, everything else (and |
| 1275 | | −/// `"`, `\`, `?`) as three-digit octal escapes. |
| 1276 | | −fn c_escape(s: &str) -> String { |
| 1277 | | − let mut out = String::new(); |
| 1278 | | − for b in s.bytes() { |
| 1279 | | − match b { |
| 1280 | | − b'"' | b'\\' | b'?' => { |
| 1281 | | − let _ = write!(out, "\\{b:03o}"); |
| 1282 | | − } |
| 1283 | | − 0x20..=0x7e => out.push(b as char), |
| 1284 | | − _ => { |
| 1285 | | − let _ = write!(out, "\\{b:03o}"); |
| 1286 | | − } |
| 1287 | | − } |
| 1288 | | − } |
| 1289 | | − out |
| 1290 | | −} |