| @@ -3,7 +3,8 @@ |
| 3 | 3 | use std::collections::{BTreeMap, BTreeSet, HashMap}; |
| 4 | 4 | use std::fmt::Write; |
| 5 | 5 | |
| 6 | | −use tilc_core::ir::{Atom, Expr, FnDecl, FnId, Lit, OpKind, Prim, Program, Value, VarId}; |
| 6 | +use tilc_core::ir::{Atom, Expr, FnDecl, FnId, Lit, OpKind, Prim, Program, Span, Value, VarId}; |
| 7 | +use tilc_span::{FileId, SourceDb}; |
| 7 | 8 | |
| 8 | 9 | use crate::Unsupported; |
| 9 | 10 | |
| @@ -41,6 +42,30 @@ static tl_value tl_call_payload(tl_ctx *ctx, tl_value clause, tl_value payload) |
| 41 | 42 | return ((tl_fn)tl_closure_code(clause))(ctx, clause, a[0], a[1], a[2], a[3], a[4]); |
| 42 | 43 | } |
| 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 | + |
| 44 | 69 | "#; |
| 45 | 70 | |
| 46 | 71 | /// Runtime functions declared in tilrt.h (or defined inline there). |
| @@ -51,6 +76,8 @@ const PANICKING: &[&str] = &[ |
| 51 | 76 | "tl_net_connect", |
| 52 | 77 | "tl_net_read", |
| 53 | 78 | "tl_net_write", |
| 79 | + "tl_net_write_string", |
| 80 | + "tl_bytes_from_list", |
| 54 | 81 | "tl_random_int", |
| 55 | 82 | "tl_int_add", |
| 56 | 83 | "tl_int_sub", |
| @@ -75,8 +102,10 @@ const DECLARED: &[&str] = &[ |
| 75 | 102 | "tl_net_connect", |
| 76 | 103 | "tl_net_read", |
| 77 | 104 | "tl_net_write", |
| 105 | + "tl_net_write_string", |
| 78 | 106 | "tl_net_close", |
| 79 | 107 | "tl_http_parse_request", |
| 108 | + "tl_http_parse_chunk", |
| 80 | 109 | "tl_string_starts_with", |
| 81 | 110 | "tl_string_ends_with", |
| 82 | 111 | "tl_string_contains", |
| @@ -115,23 +144,40 @@ const DECLARED: &[&str] = &[ |
| 115 | 144 | "tl_eprintln", |
| 116 | 145 | ]; |
| 117 | 146 | |
| 147 | +/// The C of a whole program. With `sources`, the functions that have a |
| 148 | +/// span are emitted last, under `#line` directives pointing at their |
| 149 | +/// source; everything before them (runtime glue, constants, closure |
| 150 | +/// entries, `main`, generated functions) keeps its own C line numbers, so |
| 151 | +/// no directive has to point back into the generated file. |
| 118 | 152 | pub(crate) fn emit( |
| 119 | 153 | program: &Program, |
| 120 | 154 | entries: &[FnId], |
| 121 | 155 | reachable: &BTreeSet<FnId>, |
| 156 | + sources: Option<&SourceDb>, |
| 122 | 157 | ) -> Result<String, Unsupported> { |
| 123 | 158 | let mut e = Emitter { |
| 124 | 159 | program, |
| 160 | + sources, |
| 125 | 161 | lits: String::new(), |
| 126 | 162 | lit_ids: HashMap::new(), |
| 127 | 163 | entries: BTreeSet::new(), |
| 128 | 164 | externs: BTreeMap::new(), |
| 129 | 165 | thunks: String::new(), |
| 130 | | − body: String::new(), |
| 166 | + constants: BTreeSet::new(), |
| 167 | + constant_defs: String::new(), |
| 168 | + generated: String::new(), |
| 169 | + located: String::new(), |
| 131 | 170 | labels: 0, |
| 171 | + line: None, |
| 172 | + written: None, |
| 132 | 173 | }; |
| 133 | 174 | for f in reachable { |
| 134 | | − e.function(*f, &program.fns[*f as usize])?; |
| 175 | + e.constant(*f, &program.fns[*f as usize]); |
| 176 | + } |
| 177 | + for f in reachable { |
| 178 | + if !e.constants.contains(f) { |
| 179 | + e.function(*f, &program.fns[*f as usize])?; |
| 180 | + } |
| 135 | 181 | } |
| 136 | 182 | let mut out = String::from(PRELUDE); |
| 137 | 183 | for (sym, arity) in &e.externs { |
| @@ -141,7 +187,7 @@ pub(crate) fn emit( |
| 141 | 187 | out.push_str(&e.thunks); |
| 142 | 188 | out.push_str(&e.lits); |
| 143 | 189 | out.push('\n'); |
| 144 | | − for f in reachable { |
| 190 | + for f in reachable.difference(&e.constants) { |
| 145 | 191 | let _ = writeln!( |
| 146 | 192 | out, |
| 147 | 193 | "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);" |
| @@ -154,7 +200,7 @@ pub(crate) fn emit( |
| 154 | 200 | ); |
| 155 | 201 | } |
| 156 | 202 | out.push('\n'); |
| 157 | | − out.push_str(&e.body); |
| 203 | + out.push_str(&e.constant_defs); |
| 158 | 204 | for (f, n) in e.entries.clone() { |
| 159 | 205 | e.closure_entry(&mut out, f, n); |
| 160 | 206 | } |
| @@ -168,9 +214,26 @@ pub(crate) fn emit( |
| 168 | 214 | "an entry function with many capabilities".into(), |
| 169 | 215 | )); |
| 170 | 216 | } |
| 171 | | − let root = format!("tl_root_cap(ctx, {})", crate::PROC_OPS.len()); |
| 172 | | − let caps = register_args(&vec![root; n]); |
| 173 | | − let _ = writeln!(cases, " case {k}: return f{entry}(ctx, {caps});"); |
| 217 | + let decl = &program.fns[*entry as usize]; |
| 218 | + let _ = writeln!(cases, " case {k}: {{"); |
| 219 | + for i in 0..n { |
| 220 | + let _ = writeln!( |
| 221 | + cases, |
| 222 | + " tl_value c{i} = tl_root_cap(ctx, {});", |
| 223 | + crate::PROC_OPS.len() |
| 224 | + ); |
| 225 | + } |
| 226 | + let caps: Vec<String> = (0..n).map(|i| format!("c{i}")).collect(); |
| 227 | + let _ = writeln!( |
| 228 | + cases, |
| 229 | + " tl_value r = f{entry}(ctx, {});", |
| 230 | + register_args(&caps) |
| 231 | + ); |
| 232 | + // A borrowed capability is still the caller's. |
| 233 | + for i in &decl.borrowed { |
| 234 | + let _ = writeln!(cases, " tl_drop(ctx, c{i});"); |
| 235 | + } |
| 236 | + let _ = writeln!(cases, " return r;\n }}"); |
| 174 | 237 | } |
| 175 | 238 | let _ = write!( |
| 176 | 239 | out, |
| @@ -189,8 +252,11 @@ int main(int argc, char **argv) {{ |
| 189 | 252 | tl_report_leaks(); |
| 190 | 253 | return code; |
| 191 | 254 | }} |
| 255 | + |
| 192 | 256 | "# |
| 193 | 257 | ); |
| 258 | + out.push_str(&e.generated); |
| 259 | + out.push_str(&e.located); |
| 194 | 260 | Ok(out) |
| 195 | 261 | } |
| 196 | 262 | |
| @@ -226,8 +292,18 @@ enum Dest { |
| 226 | 292 | Assign(VarId, u32), |
| 227 | 293 | } |
| 228 | 294 | |
| 295 | +/// A line of a source file. |
| 296 | +#[derive(Clone, Copy, PartialEq, Eq)] |
| 297 | +struct Line { |
| 298 | + file: FileId, |
| 299 | + line: u32, |
| 300 | +} |
| 301 | + |
| 229 | 302 | struct Emitter<'p> { |
| 230 | 303 | program: &'p Program, |
| 304 | + /// The source files, to point `#line` directives at (none: no |
| 305 | + /// directives). |
| 306 | + sources: Option<&'p SourceDb>, |
| 231 | 307 | /// Static literal blocks. |
| 232 | 308 | lits: String, |
| 233 | 309 | lit_ids: HashMap<String, usize>, |
| @@ -237,8 +313,17 @@ struct Emitter<'p> { |
| 237 | 313 | externs: BTreeMap<String, usize>, |
| 238 | 314 | /// Thunks for `blocking` externs. |
| 239 | 315 | thunks: String, |
| 240 | | − body: String, |
| 316 | + /// Functions emitted as a static, immortal value (see `constant`). |
| 317 | + constants: BTreeSet<FnId>, |
| 318 | + constant_defs: String, |
| 319 | + /// Functions without a source location, then those with one. |
| 320 | + generated: String, |
| 321 | + located: String, |
| 241 | 322 | labels: u32, |
| 323 | + /// The source line of the code being emitted (none outside located |
| 324 | + /// functions), and the line the last `#line` directive set. |
| 325 | + line: Option<Line>, |
| 326 | + written: Option<Line>, |
| 242 | 327 | } |
| 243 | 328 | |
| 244 | 329 | /// C arguments for a call with these value slots: registers, padded. |
| @@ -267,6 +352,9 @@ impl Emitter<'_> { |
| 267 | 352 | } |
| 268 | 353 | let mut out = String::new(); |
| 269 | 354 | let _ = writeln!(out, "/* {} */", decl.name); |
| 355 | + self.line = decl.span.and_then(|s| self.line_of(s)); |
| 356 | + self.written = None; |
| 357 | + self.sync_line(&mut out); |
| 270 | 358 | let _ = writeln!( |
| 271 | 359 | out, |
| 272 | 360 | "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) {{" |
| @@ -282,6 +370,15 @@ impl Emitter<'_> { |
| 282 | 370 | for i in decl.params.len()..REGS { |
| 283 | 371 | let _ = writeln!(out, " (void)a{i};"); |
| 284 | 372 | } |
| 373 | + // The references the frame holds on entry: borrowed parameters are |
| 374 | + // the caller's. |
| 375 | + let owned: Vec<VarId> = decl |
| 376 | + .params |
| 377 | + .iter() |
| 378 | + .enumerate() |
| 379 | + .filter(|(i, _)| !decl.borrowed.contains(i)) |
| 380 | + .map(|(_, p)| *p) |
| 381 | + .collect(); |
| 285 | 382 | let locals: Vec<String> = (0..decl.n_vars) |
| 286 | 383 | .filter(|v| !params.contains(v)) |
| 287 | 384 | .map(|v| format!("v{v} = TL_UNIT")) |
| @@ -293,22 +390,101 @@ impl Emitter<'_> { |
| 293 | 390 | let _ = writeln!( |
| 294 | 391 | out, |
| 295 | 392 | "entry:\n if (tl_unlikely(--ctx->reductions <= 0)) {{\n tl_preempt(ctx);\n if (TL_YIELDING(ctx)) {}\n }}", |
| 296 | | − unwind(&decl.params) |
| 393 | + unwind(&owned) |
| 297 | 394 | ); |
| 298 | 395 | let func = Func { id, decl }; |
| 299 | | − self.expr( |
| 300 | | − &mut out, |
| 301 | | − &func, |
| 302 | | − &decl.body, |
| 303 | | − Dest::Return, |
| 304 | | − decl.params.clone(), |
| 305 | | − 1, |
| 306 | | − )?; |
| 396 | + self.expr(&mut out, &func, &decl.body, Dest::Return, owned, 1)?; |
| 307 | 397 | out.push_str("}\n\n"); |
| 308 | | − self.body.push_str(&out); |
| 398 | + if self.line.is_some() { |
| 399 | + self.located.push_str(&pin_lines(&out)); |
| 400 | + } else { |
| 401 | + self.generated.push_str(&out); |
| 402 | + } |
| 309 | 403 | Ok(()) |
| 310 | 404 | } |
| 311 | 405 | |
| 406 | + /// Where `span` starts, if `#line` directives are wanted. |
| 407 | + fn line_of(&self, span: Span) -> Option<Line> { |
| 408 | + let file = self.sources?.get(span.file); |
| 409 | + Some(Line { |
| 410 | + file: span.file, |
| 411 | + line: file.line_col(span.range.start()).line + 1, |
| 412 | + }) |
| 413 | + } |
| 414 | + |
| 415 | + /// Point the C that follows at the current source line, if it is not |
| 416 | + /// already. |
| 417 | + fn sync_line(&mut self, out: &mut String) { |
| 418 | + let (Some(line), Some(sources)) = (self.line, self.sources) else { |
| 419 | + return; |
| 420 | + }; |
| 421 | + if self.written != Some(line) { |
| 422 | + let path = sources.get(line.file).path(); |
| 423 | + let _ = writeln!(out, "#line {} \"{}\"", line.line, c_escape(path)); |
| 424 | + self.written = Some(line); |
| 425 | + } |
| 426 | + } |
| 427 | + |
| 428 | + /// Record `decl` as a constant if it has no parameters and only builds |
| 429 | + /// closures without captures and tuples of them: a trait dictionary |
| 430 | + /// without constraints, such as `Num<Int>`. It is emitted as static, |
| 431 | + /// immortal blocks (count 0, like literals), so a call to it costs no |
| 432 | + /// allocation and its result needs no counting. |
| 433 | + fn constant(&mut self, id: FnId, decl: &FnDecl) { |
| 434 | + if !decl.params.is_empty() { |
| 435 | + return; |
| 436 | + } |
| 437 | + let mut defs = String::new(); |
| 438 | + let mut entries = Vec::new(); |
| 439 | + let mut e = &decl.body; |
| 440 | + loop { |
| 441 | + match e { |
| 442 | + Expr::Let(v, value, rest, _) => { |
| 443 | + let name = format!("tl_const{id}_{v}"); |
| 444 | + match &**value { |
| 445 | + Value::Closure(f, caps) if caps.is_empty() => { |
| 446 | + entries.push(*f); |
| 447 | + let _ = writeln!( |
| 448 | + defs, |
| 449 | + "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 }};" |
| 450 | + ); |
| 451 | + } |
| 452 | + Value::Tuple(args) if !args.is_empty() && args.len() <= 254 => { |
| 453 | + let mut fields = Vec::new(); |
| 454 | + for a in args { |
| 455 | + let Atom::Var(x) = a else { return }; |
| 456 | + fields.push(format!("(tl_value)&tl_const{id}_{x}")); |
| 457 | + } |
| 458 | + let _ = writeln!( |
| 459 | + defs, |
| 460 | + "static const struct {{ tl_header h; tl_value fields[{n}]; }} __attribute__((aligned(8))) {name} = {{ {{0, 0, {n}, 0}}, {{ {} }} }};", |
| 461 | + fields.join(", "), |
| 462 | + n = args.len() |
| 463 | + ); |
| 464 | + } |
| 465 | + _ => return, |
| 466 | + } |
| 467 | + e = rest; |
| 468 | + } |
| 469 | + Expr::Return(Atom::Var(r)) => { |
| 470 | + let _ = writeln!( |
| 471 | + defs, |
| 472 | + "/* {} */\n#define tl_const{id} ((tl_value)&tl_const{id}_{r})", |
| 473 | + decl.name |
| 474 | + ); |
| 475 | + break; |
| 476 | + } |
| 477 | + _ => return, |
| 478 | + } |
| 479 | + } |
| 480 | + // Only now: a closure's entry is emitted only if it is used. |
| 481 | + for f in entries { |
| 482 | + self.entries.insert((f, 0)); |
| 483 | + } |
| 484 | + self.constants.insert(id); |
| 485 | + self.constant_defs.push_str(&defs); |
| 486 | + } |
| 487 | + |
| 312 | 488 | fn atom(&mut self, a: &Atom) -> Result<String, Unsupported> { |
| 313 | 489 | Ok(match a { |
| 314 | 490 | Atom::Var(v) => format!("v{v}"), |
| @@ -393,165 +569,248 @@ impl Emitter<'_> { |
| 393 | 569 | depth: usize, |
| 394 | 570 | ) -> Result<Option<Vec<VarId>>, Unsupported> { |
| 395 | 571 | let ind = " ".repeat(depth); |
| 396 | | − match e { |
| 397 | | − Expr::Let(v, value, rest) => { |
| 398 | | − let tail = matches!(dest, Dest::Return) |
| 399 | | − && matches!(&**rest, Expr::Return(Atom::Var(r)) if r == v); |
| 400 | | − if tail { |
| 401 | | − match &**value { |
| 402 | | − Value::Block(inner) => { |
| 403 | | − return self.expr(out, f, inner, dest, held, depth); |
| 404 | | − } |
| 405 | | − Value::CallFn(g, args) if *g == f.id => { |
| 406 | | − // Self tail call: a jump. Perceus consumed or |
| 407 | | − // dropped everything else before it. |
| 408 | | − let args = self.atoms(args)?; |
| 409 | | − let _ = writeln!(out, "{ind}{{"); |
| 410 | | − for (i, a) in args.iter().enumerate() { |
| 411 | | − let _ = writeln!(out, "{ind} tl_value t{i} = {a};"); |
| 572 | + // Statements are emitted in a loop, not by recursion: a function |
| 573 | + // can be a long sequence of them. |
| 574 | + let mut e = e; |
| 575 | + loop { |
| 576 | + if self.line.is_some() |
| 577 | + && let Some(span) = statement_span(e) |
| 578 | + { |
| 579 | + self.line = self.line_of(span); |
| 580 | + } |
| 581 | + self.sync_line(out); |
| 582 | + match e { |
| 583 | + Expr::Let(v, value, rest, _) => { |
| 584 | + let tail = matches!(dest, Dest::Return) |
| 585 | + && matches!(&**rest, Expr::Return(Atom::Var(r)) if r == v); |
| 586 | + if tail { |
| 587 | + match &**value { |
| 588 | + Value::Block(inner) => { |
| 589 | + e = inner; |
| 590 | + continue; |
| 412 | 591 | } |
| 413 | | − for (i, p) in f.decl.params.iter().enumerate() { |
| 414 | | − let _ = writeln!(out, "{ind} v{p} = t{i};"); |
| 592 | + Value::CallFn(g, args) if *g == f.id => { |
| 593 | + // Self tail call: a jump. Perceus consumed or |
| 594 | + // dropped everything else before it. |
| 595 | + let args = self.atoms(args)?; |
| 596 | + let _ = writeln!(out, "{ind}{{"); |
| 597 | + for (i, a) in args.iter().enumerate() { |
| 598 | + let _ = writeln!(out, "{ind} tl_value t{i} = {a};"); |
| 599 | + } |
| 600 | + for (i, p) in f.decl.params.iter().enumerate() { |
| 601 | + let _ = writeln!(out, "{ind} v{p} = t{i};"); |
| 602 | + } |
| 603 | + let _ = writeln!(out, "{ind} goto entry;\n{ind}}}"); |
| 604 | + return Ok(None); |
| 415 | 605 | } |
| 416 | | − let _ = writeln!(out, "{ind} goto entry;\n{ind}}}"); |
| 417 | | − return Ok(None); |
| 606 | + Value::CallFn(g, args) if !self.constants.contains(g) => { |
| 607 | + let slots = self.atoms(args)?; |
| 608 | + store_xargs(&slots, &ind, out); |
| 609 | + let _ = writeln!( |
| 610 | + out, |
| 611 | + "{ind}TL_MUSTTAIL return f{g}(ctx, {});", |
| 612 | + register_args(&slots) |
| 613 | + ); |
| 614 | + return Ok(None); |
| 615 | + } |
| 616 | + Value::Call(c, args) => { |
| 617 | + let c = self.atom(c)?; |
| 618 | + let args = self.atoms(args)?; |
| 619 | + let call = Self::closure_call(&c, &args, &ind, out); |
| 620 | + let _ = writeln!(out, "{ind}TL_MUSTTAIL return {call};"); |
| 621 | + return Ok(None); |
| 622 | + } |
| 623 | + _ => {} |
| 418 | 624 | } |
| 419 | | − Value::CallFn(g, args) => { |
| 420 | | − let slots = self.atoms(args)?; |
| 421 | | − store_xargs(&slots, &ind, out); |
| 422 | | − let _ = writeln!( |
| 423 | | − out, |
| 424 | | − "{ind}TL_MUSTTAIL return f{g}(ctx, {});", |
| 425 | | − register_args(&slots) |
| 426 | | − ); |
| 625 | + } |
| 626 | + if let Value::Block(inner) = &**value { |
| 627 | + self.labels += 1; |
| 628 | + let label = self.labels; |
| 629 | + let line = self.line; |
| 630 | + let after = |
| 631 | + self.expr(out, f, inner, Dest::Assign(*v, label), held, depth)?; |
| 632 | + self.line = line; |
| 633 | + let _ = writeln!(out, "{ind}b{label}:;"); |
| 634 | + let Some(mut after) = after else { |
| 635 | + // Every path through the block leaves the function. |
| 427 | 636 | return Ok(None); |
| 428 | | − } |
| 429 | | − Value::Call(c, args) => { |
| 430 | | − let c = self.atom(c)?; |
| 431 | | − let args = self.atoms(args)?; |
| 432 | | − let call = Self::closure_call(&c, &args, &ind, out); |
| 433 | | − let _ = writeln!(out, "{ind}TL_MUSTTAIL return {call};"); |
| 637 | + }; |
| 638 | + after.push(*v); |
| 639 | + held = after; |
| 640 | + e = rest; |
| 641 | + continue; |
| 642 | + } |
| 643 | + let (owned, _) = tilc_perceus::uses(value, &self.program.fns); |
| 644 | + for o in owned { |
| 645 | + take(&mut held, o); |
| 646 | + } |
| 647 | + self.value(out, *v, value, &ind, &held)?; |
| 648 | + if self.may_unwind(value) { |
| 649 | + let _ = writeln!(out, "{ind}if (TL_YIELDING(ctx)) {}", unwind(&held)); |
| 650 | + } |
| 651 | + // A projection is borrowed (a `dup` follows if it is owned). |
| 652 | + if !matches!(&**value, Value::Field(..)) { |
| 653 | + held.push(*v); |
| 654 | + } |
| 655 | + e = rest; |
| 656 | + } |
| 657 | + Expr::Return(a) => { |
| 658 | + if let Atom::Var(x) = a { |
| 659 | + take(&mut held, *x); |
| 660 | + } |
| 661 | + let a = self.atom(a)?; |
| 662 | + match dest { |
| 663 | + Dest::Return => { |
| 664 | + let _ = writeln!(out, "{ind}return {a};"); |
| 434 | 665 | return Ok(None); |
| 435 | 666 | } |
| 436 | | − _ => {} |
| 667 | + Dest::Assign(v, label) => { |
| 668 | + let _ = writeln!(out, "{ind}v{v} = {a};\n{ind}goto b{label};"); |
| 669 | + return Ok(Some(held)); |
| 670 | + } |
| 437 | 671 | } |
| 438 | 672 | } |
| 439 | | − if let Value::Block(inner) = &**value { |
| 440 | | − self.labels += 1; |
| 441 | | − let label = self.labels; |
| 442 | | − let after = self.expr(out, f, inner, Dest::Assign(*v, label), held, depth)?; |
| 443 | | − let _ = writeln!(out, "{ind}b{label}:;"); |
| 444 | | − let Some(mut after) = after else { |
| 445 | | − // Every path through the block leaves the function. |
| 446 | | − return Ok(None); |
| 447 | | − }; |
| 448 | | − after.push(*v); |
| 449 | | − return self.expr(out, f, rest, dest, after, depth); |
| 673 | + Expr::Dup(v, rest) => { |
| 674 | + let _ = writeln!(out, "{ind}tl_dup(v{v});"); |
| 675 | + held.push(*v); |
| 676 | + e = rest; |
| 450 | 677 | } |
| 451 | | − let (owned, _) = tilc_perceus::uses(value); |
| 452 | | − for o in owned { |
| 453 | | − take(&mut held, o); |
| 678 | + Expr::Drop(v, rest) => { |
| 679 | + let _ = writeln!(out, "{ind}tl_drop(ctx, v{v});"); |
| 680 | + take(&mut held, *v); |
| 681 | + e = rest; |
| 454 | 682 | } |
| 455 | | − self.value(out, *v, value, &ind, &held)?; |
| 456 | | − if self.may_unwind(value) { |
| 457 | | − let _ = writeln!(out, "{ind}if (TL_YIELDING(ctx)) {}", unwind(&held)); |
| 683 | + Expr::Release { |
| 684 | + var, |
| 685 | + fields, |
| 686 | + token, |
| 687 | + rest, |
| 688 | + } => { |
| 689 | + Self::release(out, *var, fields, *token, &ind); |
| 690 | + take(&mut held, *var); |
| 691 | + held.extend(fields.iter().map(|(_, a)| *a)); |
| 692 | + held.extend(token); |
| 693 | + e = rest; |
| 458 | 694 | } |
| 459 | | − held.push(*v); |
| 460 | | − self.expr(out, f, rest, dest, held, depth) |
| 461 | | − } |
| 462 | | − Expr::Return(a) => { |
| 463 | | − if let Atom::Var(x) = a { |
| 464 | | − take(&mut held, *x); |
| 695 | + Expr::Panic(msg) => { |
| 696 | + let _ = writeln!( |
| 697 | + out, |
| 698 | + "{ind}tl_panic_str(ctx, \"{}\");\n{ind}{}", |
| 699 | + c_escape(msg), |
| 700 | + unwind(&held) |
| 701 | + ); |
| 702 | + return Ok(None); |
| 465 | 703 | } |
| 466 | | − let a = self.atom(a)?; |
| 467 | | − match dest { |
| 468 | | − Dest::Return => { |
| 469 | | − let _ = writeln!(out, "{ind}return {a};"); |
| 470 | | − Ok(None) |
| 704 | + Expr::Switch { on, cases, default } => { |
| 705 | + let on = self.atom(on)?; |
| 706 | + let mut after = None; |
| 707 | + let _ = writeln!(out, "{ind}switch (tl_tag_of({on})) {{"); |
| 708 | + let line = self.line; |
| 709 | + for (tag, body) in cases { |
| 710 | + self.line = line; |
| 711 | + self.sync_line(out); |
| 712 | + let _ = writeln!(out, "{ind}case {tag}: {{"); |
| 713 | + let a = self.expr(out, f, body, dest, held.clone(), depth + 1)?; |
| 714 | + after = after.or(a); |
| 715 | + let _ = writeln!(out, "{ind}}}"); |
| 471 | 716 | } |
| 472 | | − Dest::Assign(v, label) => { |
| 473 | | − let _ = writeln!(out, "{ind}v{v} = {a};\n{ind}goto b{label};"); |
| 474 | | − Ok(Some(held)) |
| 717 | + self.line = line; |
| 718 | + self.sync_line(out); |
| 719 | + match default { |
| 720 | + Some(d) => { |
| 721 | + let _ = writeln!(out, "{ind}default: {{"); |
| 722 | + let a = self.expr(out, f, d, dest, held, depth + 1)?; |
| 723 | + after = after.or(a); |
| 724 | + let _ = writeln!(out, "{ind}}}"); |
| 725 | + } |
| 726 | + None => { |
| 727 | + let _ = writeln!(out, "{ind}default: __builtin_unreachable();"); |
| 728 | + } |
| 475 | 729 | } |
| 476 | | − } |
| 477 | | − } |
| 478 | | − Expr::Dup(v, rest) => { |
| 479 | | − let _ = writeln!(out, "{ind}tl_dup(v{v});"); |
| 480 | | − held.push(*v); |
| 481 | | − self.expr(out, f, rest, dest, held, depth) |
| 482 | | − } |
| 483 | | − Expr::Drop(v, rest) => { |
| 484 | | − let _ = writeln!(out, "{ind}tl_drop(ctx, v{v});"); |
| 485 | | − take(&mut held, *v); |
| 486 | | − self.expr(out, f, rest, dest, held, depth) |
| 487 | | − } |
| 488 | | − Expr::Panic(msg) => { |
| 489 | | − let _ = writeln!( |
| 490 | | − out, |
| 491 | | − "{ind}tl_panic_str(ctx, \"{}\");\n{ind}{}", |
| 492 | | − c_escape(msg), |
| 493 | | − unwind(&held) |
| 494 | | − ); |
| 495 | | − Ok(None) |
| 496 | | − } |
| 497 | | − Expr::Switch { on, cases, default } => { |
| 498 | | − let on = self.atom(on)?; |
| 499 | | − let mut after = None; |
| 500 | | − let _ = writeln!(out, "{ind}switch (tl_tag_of({on})) {{"); |
| 501 | | − for (tag, body) in cases { |
| 502 | | − let _ = writeln!(out, "{ind}case {tag}: {{"); |
| 503 | | − let a = self.expr(out, f, body, dest, held.clone(), depth + 1)?; |
| 504 | | − after = after.or(a); |
| 505 | 730 | let _ = writeln!(out, "{ind}}}"); |
| 731 | + return Ok(after); |
| 506 | 732 | } |
| 507 | | − match default { |
| 508 | | − Some(d) => { |
| 509 | | − let _ = writeln!(out, "{ind}default: {{"); |
| 510 | | − let a = self.expr(out, f, d, dest, held, depth + 1)?; |
| 511 | | − after = after.or(a); |
| 512 | | − let _ = writeln!(out, "{ind}}}"); |
| 733 | + Expr::SwitchLit { on, cases, default } => { |
| 734 | + if cases.is_empty() { |
| 735 | + e = default; |
| 736 | + continue; |
| 513 | 737 | } |
| 514 | | − None => { |
| 515 | | − let _ = writeln!(out, "{ind}default: __builtin_unreachable();"); |
| 738 | + let on = self.atom(on)?; |
| 739 | + let mut after = None; |
| 740 | + let line = self.line; |
| 741 | + for (i, (lit, body)) in cases.iter().enumerate() { |
| 742 | + self.line = line; |
| 743 | + self.sync_line(out); |
| 744 | + let test = match lit { |
| 745 | + Lit::Int(n) => format!("{on} == tl_int(INT64_C({n}))"), |
| 746 | + Lit::Float(x) => format!("tl_float_get({on}) == {x:e}"), |
| 747 | + Lit::String(s) => { |
| 748 | + format!("tl_str_is({on}, \"{}\", {})", c_escape(s), s.len()) |
| 749 | + } |
| 750 | + }; |
| 751 | + let kw = if i == 0 { "if" } else { "} else if" }; |
| 752 | + let _ = writeln!(out, "{ind}{kw} ({test}) {{"); |
| 753 | + let a = self.expr(out, f, body, dest, held.clone(), depth + 1)?; |
| 754 | + after = after.or(a); |
| 516 | 755 | } |
| 517 | | − } |
| 518 | | − let _ = writeln!(out, "{ind}}}"); |
| 519 | | − Ok(after) |
| 520 | | − } |
| 521 | | − Expr::SwitchLit { on, cases, default } => { |
| 522 | | − if cases.is_empty() { |
| 523 | | − return self.expr(out, f, default, dest, held, depth); |
| 524 | | − } |
| 525 | | − let on = self.atom(on)?; |
| 526 | | − let mut after = None; |
| 527 | | − for (i, (lit, body)) in cases.iter().enumerate() { |
| 528 | | − let test = match lit { |
| 529 | | − Lit::Int(n) => format!("{on} == tl_int(INT64_C({n}))"), |
| 530 | | − Lit::Float(x) => format!("tl_float_get({on}) == {x:e}"), |
| 531 | | − Lit::String(s) => { |
| 532 | | − format!("tl_str_is({on}, \"{}\", {})", c_escape(s), s.len()) |
| 533 | | − } |
| 534 | | − }; |
| 535 | | − let kw = if i == 0 { "if" } else { "} else if" }; |
| 536 | | − let _ = writeln!(out, "{ind}{kw} ({test}) {{"); |
| 537 | | − let a = self.expr(out, f, body, dest, held.clone(), depth + 1)?; |
| 756 | + self.line = line; |
| 757 | + self.sync_line(out); |
| 758 | + let _ = writeln!(out, "{ind}}} else {{"); |
| 759 | + let a = self.expr(out, f, default, dest, held, depth + 1)?; |
| 538 | 760 | after = after.or(a); |
| 761 | + let _ = writeln!(out, "{ind}}}"); |
| 762 | + return Ok(after); |
| 539 | 763 | } |
| 540 | | − let _ = writeln!(out, "{ind}}} else {{"); |
| 541 | | − let a = self.expr(out, f, default, dest, held, depth + 1)?; |
| 542 | | − after = after.or(a); |
| 543 | | − let _ = writeln!(out, "{ind}}}"); |
| 544 | | − Ok(after) |
| 545 | 764 | } |
| 546 | 765 | } |
| 547 | 766 | } |
| 548 | 767 | |
| 768 | + /// `release x [fields]` (drop specialisation), keeping a unique cell |
| 769 | + /// as `token` if there is one. |
| 770 | + fn release( |
| 771 | + out: &mut String, |
| 772 | + var: VarId, |
| 773 | + fields: &[(u32, VarId)], |
| 774 | + token: Option<VarId>, |
| 775 | + ind: &str, |
| 776 | + ) { |
| 777 | + // Unique: move the fields out and free (or keep) the cell. |
| 778 | + // Shared: the fields take references of their own. |
| 779 | + let _ = writeln!(out, "{ind}if (tl_is_unique(v{var})) {{"); |
| 780 | + for (i, _) in fields { |
| 781 | + let _ = writeln!(out, "{ind} tl_as_block(v{var})->fields[{i}] = TL_UNIT;"); |
| 782 | + } |
| 783 | + match token { |
| 784 | + Some(t) => { |
| 785 | + let _ = writeln!( |
| 786 | + out, |
| 787 | + "{ind} v{t} = tl_reuse_token(ctx, tl_as_block(v{var}));" |
| 788 | + ); |
| 789 | + } |
| 790 | + None => { |
| 791 | + let _ = writeln!( |
| 792 | + out, |
| 793 | + "{ind} tl_free_moved(ctx, tl_as_block(v{var}), {});", |
| 794 | + fields.len() |
| 795 | + ); |
| 796 | + } |
| 797 | + } |
| 798 | + let _ = writeln!(out, "{ind}}} else {{"); |
| 799 | + for (_, a) in fields { |
| 800 | + let _ = writeln!(out, "{ind} tl_dup(v{a});"); |
| 801 | + } |
| 802 | + let _ = writeln!(out, "{ind} tl_drop(ctx, v{var});"); |
| 803 | + if let Some(t) = token { |
| 804 | + let _ = writeln!(out, "{ind} v{t} = TL_UNIT;"); |
| 805 | + } |
| 806 | + let _ = writeln!(out, "{ind}}}"); |
| 807 | + } |
| 808 | + |
| 549 | 809 | /// Whether computing `value` may start or continue unwinding. |
| 550 | 810 | fn may_unwind(&self, value: &Value) -> bool { |
| 551 | 811 | match value { |
| 552 | | − Value::CallFn(..) | Value::Call(..) | Value::Handle { .. } | Value::Region { .. } => { |
| 553 | | − true |
| 554 | | − } |
| 812 | + Value::CallFn(g, _) => !self.constants.contains(g), |
| 813 | + Value::Call(..) | Value::Handle { .. } | Value::Region { .. } => true, |
| 555 | 814 | Value::Perform { effect, .. } => !self.program.effects[*effect as usize] |
| 556 | 815 | .name |
| 557 | 816 | .starts_with("std/ref."), |
| @@ -577,6 +836,9 @@ impl Emitter<'_> { |
| 577 | 836 | let a = self.atom(a)?; |
| 578 | 837 | let _ = writeln!(out, "{ind}v{v} = {a};"); |
| 579 | 838 | } |
| 839 | + Value::CallFn(g, _) if self.constants.contains(g) => { |
| 840 | + let _ = writeln!(out, "{ind}v{v} = tl_const{g};"); |
| 841 | + } |
| 580 | 842 | Value::CallFn(g, args) => { |
| 581 | 843 | let slots = self.atoms(args)?; |
| 582 | 844 | store_xargs(&slots, ind, out); |
| @@ -652,7 +914,25 @@ impl Emitter<'_> { |
| 652 | 914 | } |
| 653 | 915 | Value::Field(base, i) => { |
| 654 | 916 | let b = self.atom(base)?; |
| 655 | | − let _ = writeln!(out, "{ind}v{v} = tl_dup(tl_as_block({b})->fields[{i}]);"); |
| 917 | + let _ = writeln!(out, "{ind}v{v} = tl_as_block({b})->fields[{i}];"); |
| 918 | + } |
| 919 | + Value::Reuse { token, value } => { |
| 920 | + let (tag, args) = match &**value { |
| 921 | + Value::Construct { tag, args, .. } => (*tag, args), |
| 922 | + Value::Tuple(args) => (0, args), |
| 923 | + _ => unreachable!("only constructions reuse cells"), |
| 924 | + }; |
| 925 | + let args = self.atoms(args)?; |
| 926 | + Self::check_block(tag, args.len())?; |
| 927 | + // In place if the token is a cell of the same size. |
| 928 | + let n = args.len(); |
| 929 | + let _ = writeln!( |
| 930 | + out, |
| 931 | + "{ind}if (tl_is_ptr(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}}}" |
| 932 | + ); |
| 933 | + for (i, a) in args.iter().enumerate() { |
| 934 | + let _ = writeln!(out, "{ind}tl_as_block(v{v})->fields[{i}] = {a};"); |
| 935 | + } |
| 656 | 936 | } |
| 657 | 937 | Value::Closure(fid, caps) => { |
| 658 | 938 | let caps = self.atoms(caps)?; |
| @@ -828,9 +1108,7 @@ impl Emitter<'_> { |
| 828 | 1108 | let _ = writeln!(out, "{ind}v{v} = tl_int({tag});"); |
| 829 | 1109 | return Ok(()); |
| 830 | 1110 | } |
| 831 | | − if args.len() > 254 || tag >= 0xFF00 { |
| 832 | | − return Err(Unsupported("constructors with more than 254 fields".into())); |
| 833 | | − } |
| 1111 | + Self::check_block(tag, args.len())?; |
| 834 | 1112 | let _ = writeln!( |
| 835 | 1113 | out, |
| 836 | 1114 | "{ind}v{v} = tl_from_block(tl_alloc(ctx, {tag}, {}, 0));", |
| @@ -842,6 +1120,13 @@ impl Emitter<'_> { |
| 842 | 1120 | Ok(()) |
| 843 | 1121 | } |
| 844 | 1122 | |
| 1123 | + fn check_block(tag: u32, fields: usize) -> Result<(), Unsupported> { |
| 1124 | + if fields > 254 || tag >= 0xFF00 { |
| 1125 | + return Err(Unsupported("constructors with more than 254 fields".into())); |
| 1126 | + } |
| 1127 | + Ok(()) |
| 1128 | + } |
| 1129 | + |
| 845 | 1130 | /// The entry of closures of `f` capturing `n` values: unpack the |
| 846 | 1131 | /// closure (first argument), then tail-call `f` with captures first. |
| 847 | 1132 | fn closure_entry(&self, out: &mut String, f: FnId, n: usize) { |
| @@ -883,6 +1168,46 @@ impl Emitter<'_> { |
| 883 | 1168 | } |
| 884 | 1169 | } |
| 885 | 1170 | |
| 1171 | +/// The span of the statement `e` starts with: a `let`'s, also for the |
| 1172 | +/// `dup`s, `drop`s and `release`s Perceus put before it. |
| 1173 | +fn statement_span(e: &Expr) -> Option<Span> { |
| 1174 | + match e { |
| 1175 | + Expr::Let(_, _, _, span) => *span, |
| 1176 | + Expr::Dup(_, rest) | Expr::Drop(_, rest) | Expr::Release { rest, .. } => { |
| 1177 | + statement_span(rest) |
| 1178 | + } |
| 1179 | + _ => None, |
| 1180 | + } |
| 1181 | +} |
| 1182 | + |
| 1183 | +/// Keep every line after a `#line N` directive on line `N`: C numbers |
| 1184 | +/// the lines after a directive `N`, `N + 1`, ..., but all the C from one |
| 1185 | +/// source line belongs to that line. So each further line gets its own |
| 1186 | +/// `#line N`. Lines are never split, so no directive comes between an |
| 1187 | +/// attribute (`TL_MUSTTAIL`) and its statement. |
| 1188 | +fn pin_lines(c: &str) -> String { |
| 1189 | + let mut out = String::with_capacity(c.len() * 2); |
| 1190 | + let mut pinned: Option<&str> = None; |
| 1191 | + let mut after_directive = false; |
| 1192 | + for line in c.lines() { |
| 1193 | + if let Some(rest) = line.strip_prefix("#line ") { |
| 1194 | + pinned = rest.split(' ').next(); |
| 1195 | + after_directive = true; |
| 1196 | + } else { |
| 1197 | + if let Some(n) = pinned |
| 1198 | + && !after_directive |
| 1199 | + && !line.is_empty() |
| 1200 | + { |
| 1201 | + let _ = writeln!(out, "#line {n}"); |
| 1202 | + } |
| 1203 | + after_directive = false; |
| 1204 | + } |
| 1205 | + out.push_str(line); |
| 1206 | + out.push('\n'); |
| 1207 | + } |
| 1208 | + out |
| 1209 | +} |
| 1210 | + |
| 886 | 1211 | /// A C string literal body: printable ASCII as is, everything else (and |
| 887 | 1212 | /// `"`, `\`, `?`) as three-digit octal escapes. |
| 888 | 1213 | fn c_escape(s: &str) -> String { |