| @@ -61,7 +61,8 @@ pub(crate) fn emit( |
| 61 | 61 | } else { |
| 62 | 62 | crate::ranges::analyse(program, entries, reachable) |
| 63 | 63 | }; |
| 64 | | − let workers = crate::unbox::plan(program, reachable, &ranges); |
| 64 | + let hoist_statics = std::env::var_os("LOUISE_NO_STATIC_CTORS").is_none(); |
| 65 | + let workers = crate::unbox::plan(program, reachable, &ranges, hoist_statics); |
| 65 | 66 | let mut e = Emitter { |
| 66 | 67 | program, |
| 67 | 68 | sources, |
| @@ -82,9 +83,12 @@ pub(crate) fn emit( |
| 82 | 83 | cmp_defer: BTreeSet::new(), |
| 83 | 84 | raw: BTreeSet::new(), |
| 84 | 85 | worker: None, |
| 86 | + flat: BTreeMap::new(), |
| 87 | + record_result: 0, |
| 88 | + flat_temps: Vec::new(), |
| 85 | 89 | functions: BTreeMap::new(), |
| 86 | 90 | uses: Uses::default(), |
| 87 | | − hoist_statics: std::env::var_os("LOUISE_NO_STATIC_CTORS").is_none(), |
| 91 | + hoist_statics, |
| 88 | 92 | borrow_closures: std::env::var_os("LOUISE_NO_BORROW_CLOSURES").is_none(), |
| 89 | 93 | static_atoms: HashMap::new(), |
| 90 | 94 | ctx_cells: HashSet::new(), |
| @@ -294,9 +298,32 @@ fn const_int(n: i64) -> String { |
| 294 | 298 | /// `multi ctl` continuation, ADR 0017, takes the same path and dups |
| 295 | 299 | /// instead.) |
| 296 | 300 | fn unwind(held: &[VarId], ret: &str) -> String { |
| 301 | + unwind_flat(held, &BTreeMap::new(), &[], ret) |
| 302 | +} |
| 303 | + |
| 304 | +/// [`unwind`], dropping a flat variable's field locals (ADR 0069), and |
| 305 | +/// the boxes rebuilt at borrowed positions in the statement (`temps`). |
| 306 | +fn unwind_flat( |
| 307 | + held: &[VarId], |
| 308 | + flat: &BTreeMap<VarId, (u32, u32)>, |
| 309 | + temps: &[String], |
| 310 | + ret: &str, |
| 311 | +) -> String { |
| 297 | 312 | let mut s = String::from("{ "); |
| 298 | 313 | for v in held { |
| 299 | | − let _ = write!(s, "TL_UNWIND_DROP(ctx, v{v}); "); |
| 314 | + match flat.get(v) { |
| 315 | + Some((_, n)) => { |
| 316 | + for j in 0..*n { |
| 317 | + let _ = write!(s, "TL_UNWIND_DROP(ctx, v{v}f{j}); "); |
| 318 | + } |
| 319 | + } |
| 320 | + None => { |
| 321 | + let _ = write!(s, "TL_UNWIND_DROP(ctx, v{v}); "); |
| 322 | + } |
| 323 | + } |
| 324 | + } |
| 325 | + for t in temps { |
| 326 | + let _ = write!(s, "TL_UNWIND_DROP(ctx, {t}); "); |
| 300 | 327 | } |
| 301 | 328 | let _ = write!(s, "return {ret}; }}"); |
| 302 | 329 | s |
| @@ -304,11 +331,21 @@ fn unwind(held: &[VarId], ret: &str) -> String { |
| 304 | 331 | |
| 305 | 332 | /// What `unwind` returns from a function of this return shape. A |
| 306 | 333 | /// worker's dummy is never the int bail sentinel: yielding is not an |
| 307 | | −/// overflow, and the caller's sentinel check must not fire on it. |
| 308 | | −fn unwind_ret(cpr_arity: Option<u32>, worker: Option<UnboxedKind>) -> String { |
| 334 | +/// overflow, and the caller's sentinel check must not fire on it. A |
| 335 | +/// record worker's dummy is the flattened result's shape (ADR 0069). |
| 336 | +fn unwind_ret(cpr_arity: Option<u32>, worker: Option<UnboxedKind>, record_result: u32) -> String { |
| 309 | 337 | match worker { |
| 310 | 338 | Some(UnboxedKind::Float) => return "0.0".to_owned(), |
| 311 | 339 | Some(UnboxedKind::Int) => return "0".to_owned(), |
| 340 | + Some(UnboxedKind::Record) => { |
| 341 | + return match record_result { |
| 342 | + 0 | 1 => "TL_UNIT".to_owned(), |
| 343 | + n => { |
| 344 | + let units: Vec<&str> = (0..n).map(|_| "TL_UNIT").collect(); |
| 345 | + format!("(tl_pair{n}){{ {} }}", units.join(", ")) |
| 346 | + } |
| 347 | + }; |
| 348 | + } |
| 312 | 349 | None => {} |
| 313 | 350 | } |
| 314 | 351 | match cpr_arity { |
| @@ -390,6 +427,14 @@ struct Emitter<'p> { |
| 390 | 427 | /// worker's body is emitted, its raw locals (empty otherwise) and |
| 391 | 428 | /// its kind. |
| 392 | 429 | workers: BTreeMap<FnId, crate::unbox::WorkerPlan>, |
| 430 | + /// A record worker's flat variables (ADR 0069), while its body is |
| 431 | + /// emitted — (tag, field count) by variable — and its result's field |
| 432 | + /// count (empty/0 otherwise). |
| 433 | + flat: BTreeMap<VarId, (u32, u32)>, |
| 434 | + record_result: u32, |
| 435 | + /// Boxes rebuilt at borrowed positions in the current statement |
| 436 | + /// (ADR 0069): the frame owns them; dropped when it ends. |
| 437 | + flat_temps: Vec<String>, |
| 393 | 438 | /// The current function's comparison switches fused to direct |
| 394 | 439 | /// branches, by scrutinee variable ([`CmpSwitch`]). |
| 395 | 440 | cmp_switches: HashMap<VarId, CmpSwitch>, |
| @@ -719,25 +764,76 @@ fn store_xargs(slots: &[String], indent: &str, out: &mut String) { |
| 719 | 764 | } |
| 720 | 765 | } |
| 721 | 766 | |
| 767 | +/// All-owned argument/ownership pairs for [`Emitter::atoms_boxed`] |
| 768 | +/// (ADR 0069). |
| 769 | +fn owned_args(args: &[Atom]) -> Vec<(Atom, bool)> { |
| 770 | + owned_args_but_atoms(args, true) |
| 771 | +} |
| 772 | + |
| 773 | +/// Argument/ownership pairs: every position owned when `owned` (ADR |
| 774 | +/// 0069). |
| 775 | +fn owned_args_but_atoms(args: &[Atom], owned: bool) -> Vec<(Atom, bool)> { |
| 776 | + args.iter().map(|a| (a.clone(), owned)).collect() |
| 777 | +} |
| 778 | + |
| 779 | +/// Argument/ownership pairs from a callee's borrowed-parameter set (ADR |
| 780 | +/// 0069). |
| 781 | +fn owned_args_but(args: &[Atom], borrowed: &BTreeSet<usize>) -> Vec<(Atom, bool)> { |
| 782 | + args.iter() |
| 783 | + .enumerate() |
| 784 | + .map(|(i, a)| (a.clone(), !borrowed.contains(&i))) |
| 785 | + .collect() |
| 786 | +} |
| 787 | + |
| 722 | 788 | impl Emitter<'_> { |
| 723 | | − /// A worker's C symbol: the wrapper's, `$uf`/`$ui`-mangled (ADR 0045). |
| 789 | + /// A worker's C symbol: the wrapper's, `$uf`/`$ui`/`$ur`-mangled |
| 790 | + /// (ADR 0045, ADR 0069). |
| 724 | 791 | fn worker_sym(&self, id: FnId) -> String { |
| 725 | 792 | let suffix = match self.workers[&id].kind { |
| 726 | 793 | UnboxedKind::Float => "_24uf", |
| 727 | 794 | UnboxedKind::Int => "_24ui", |
| 795 | + UnboxedKind::Record => "_24ur", |
| 728 | 796 | }; |
| 729 | 797 | format!("{}{suffix}", self.syms[&id]) |
| 730 | 798 | } |
| 731 | 799 | |
| 800 | + /// A record worker's result type: the fields as a bare value (one) |
| 801 | + /// or a small struct by value (ADR 0069); a boxed result is a plain |
| 802 | + /// `tl_value`. |
| 803 | + fn record_ret(result_fields: u32) -> String { |
| 804 | + match result_fields { |
| 805 | + 0 | 1 => "tl_value".to_owned(), |
| 806 | + n => format!("tl_pair{n}"), |
| 807 | + } |
| 808 | + } |
| 809 | + |
| 732 | 810 | /// A worker's prototype: the marked parameters and the result raw |
| 733 | | − /// (called only when a plan exists). |
| 811 | + /// (called only when a plan exists). A record worker's marked |
| 812 | + /// parameters are flattened: one C parameter per field (ADR 0069). |
| 734 | 813 | fn worker_sig(&self, id: FnId) -> String { |
| 735 | 814 | let decl = &self.program.fns[id as usize]; |
| 736 | 815 | let plan = &self.workers[&id]; |
| 737 | 816 | let sig = decl.unbox_sig.as_ref().expect("a plan has a signature"); |
| 817 | + if plan.kind == UnboxedKind::Record { |
| 818 | + let params: String = decl |
| 819 | + .params |
| 820 | + .iter() |
| 821 | + .enumerate() |
| 822 | + .map(|(i, p)| match plan.flat.get(p) { |
| 823 | + Some((_, n)) => (0..*n).map(|j| format!(", tl_value a{i}f{j}")).collect(), |
| 824 | + None => format!(", tl_value a{i}"), |
| 825 | + }) |
| 826 | + .collect(); |
| 827 | + return format!( |
| 828 | + "TL_FN {} {}(tl_ctx *ctx{params})", |
| 829 | + Self::record_ret(plan.result_fields), |
| 830 | + self.worker_sym(id) |
| 831 | + ); |
| 832 | + } |
| 738 | 833 | let raw_ty = match plan.kind { |
| 739 | 834 | UnboxedKind::Float => "double", |
| 740 | 835 | UnboxedKind::Int => "int64_t", |
| 836 | + UnboxedKind::Record => unreachable!("handled above"), |
| 741 | 837 | }; |
| 742 | 838 | let params: String = decl |
| 743 | 839 | .params |
| @@ -763,32 +859,19 @@ impl Emitter<'_> { |
| 763 | 859 | /// effect's clause is the runtime's and consumes (a `send` moves a |
| 764 | 860 | /// unique message), so it keeps the owned call. In a worker the |
| 765 | 861 | /// owned call stays too: a raw argument is boxed inline at the |
| 766 | | − /// boundary, and the owned call is what consumes the box. And when |
| 767 | | − /// the call is the last use of everything it would consume (`held` |
| 768 | | − /// holds none of them past it), the owned entry consumes them: the |
| 769 | | − /// callee sees a unique value, as before ADR 0068 (the fold whose |
| 770 | | − /// accumulator is threaded through the call). |
| 771 | | − fn borrowed_call(&self, value: &Value, held: &[VarId]) -> bool { |
| 862 | + /// boundary, and the owned call is what consumes the box. |
| 863 | + fn borrowed_call(&self, value: &Value) -> bool { |
| 772 | 864 | if self.worker.is_some() { |
| 773 | 865 | return false; |
| 774 | 866 | } |
| 775 | | − let borrows = match value { |
| 867 | + match value { |
| 776 | 868 | Value::Call(..) => true, |
| 777 | 869 | Value::Perform { effect, op, .. } => { |
| 778 | 870 | let decl = &self.program.effects[*effect as usize]; |
| 779 | 871 | decl.builtin.is_none() && decl.ops[*op as usize].1 == louise_core::ir::OpKind::Fn |
| 780 | 872 | } |
| 781 | 873 | _ => false, |
| 782 | | − }; |
| 783 | | − if !borrows { |
| 784 | | − return false; |
| 785 | 874 | } |
| 786 | | − let (owned, _) = louise_perceus::uses(value, self.program); |
| 787 | | − let mut after = held.to_vec(); |
| 788 | | − for o in &owned { |
| 789 | | − take(&mut after, *o); |
| 790 | | − } |
| 791 | | − owned.iter().any(|o| after.contains(o)) |
| 792 | 875 | } |
| 793 | 876 | |
| 794 | 877 | /// `a` as a raw operand (worker mode): a raw local directly, a |
| @@ -846,12 +929,16 @@ impl Emitter<'_> { |
| 846 | 929 | let Some(plan) = self.workers.get(&id) else { |
| 847 | 930 | return Ok(None); |
| 848 | 931 | }; |
| 932 | + if plan.kind == UnboxedKind::Record { |
| 933 | + return self.emit_record_worker(id, decl); |
| 934 | + } |
| 849 | 935 | let raw = plan.raw.clone(); |
| 850 | 936 | let kind = plan.kind; |
| 851 | 937 | let sig = decl.unbox_sig.clone().expect("a plan has a signature"); |
| 852 | 938 | let (raw_ty, raw_zero, tag) = match kind { |
| 853 | 939 | UnboxedKind::Float => ("double", "0.0", "uf"), |
| 854 | 940 | UnboxedKind::Int => ("int64_t", "0", "ui"), |
| 941 | + UnboxedKind::Record => unreachable!("handled above"), |
| 855 | 942 | }; |
| 856 | 943 | let mut out = String::new(); |
| 857 | 944 | let _ = writeln!(out, "/* {}${tag} */", decl.name); |
| @@ -915,6 +1002,91 @@ impl Emitter<'_> { |
| 915 | 1002 | Ok(Some(text)) |
| 916 | 1003 | } |
| 917 | 1004 | |
| 1005 | + /// The record worker of `id` (ADR 0069): the marked parameters |
| 1006 | + /// flattened into one C parameter per field, the body on the field |
| 1007 | + /// locals, the result's fields returned by value. The wrapper keeps |
| 1008 | + /// the boxed body for the uniform path, exactly as ADR 0045. |
| 1009 | + fn emit_record_worker( |
| 1010 | + &mut self, |
| 1011 | + id: FnId, |
| 1012 | + decl: &FnDecl, |
| 1013 | + ) -> Result<Option<String>, Unsupported> { |
| 1014 | + let plan = &self.workers[&id]; |
| 1015 | + let flat = plan.flat.clone(); |
| 1016 | + let result_fields = plan.result_fields; |
| 1017 | + let mut out = String::new(); |
| 1018 | + let _ = writeln!(out, "/* {}$ur */", decl.name); |
| 1019 | + self.line = decl.span.and_then(|s| self.line_of(s)); |
| 1020 | + self.written = None; |
| 1021 | + self.sync_line(&mut out); |
| 1022 | + self.current = id; |
| 1023 | + self.worker = Some(UnboxedKind::Record); |
| 1024 | + self.flat = flat; |
| 1025 | + self.record_result = result_fields; |
| 1026 | + self.static_atoms.clear(); |
| 1027 | + self.ctx_cells = ctx_cells(&decl.body); |
| 1028 | + let _ = writeln!(out, "{} {{", self.worker_sig(id)); |
| 1029 | + let params_set: BTreeSet<VarId> = decl.params.iter().copied().collect(); |
| 1030 | + for (i, p) in decl.params.iter().enumerate() { |
| 1031 | + match self.flat.get(p) { |
| 1032 | + Some((_, n)) => { |
| 1033 | + for j in 0..*n { |
| 1034 | + let _ = writeln!(out, " tl_value v{p}f{j} = a{i}f{j};"); |
| 1035 | + } |
| 1036 | + } |
| 1037 | + None => { |
| 1038 | + let _ = writeln!(out, " tl_value v{p} = a{i};"); |
| 1039 | + } |
| 1040 | + } |
| 1041 | + } |
| 1042 | + let mut tagged_locals = Vec::new(); |
| 1043 | + for v in (0..decl.n_vars).filter(|v| !params_set.contains(v)) { |
| 1044 | + match self.flat.get(&v).copied() { |
| 1045 | + Some((_, n)) => { |
| 1046 | + let fields: Vec<String> = |
| 1047 | + (0..n).map(|j| format!("v{v}f{j} = TL_UNIT")).collect(); |
| 1048 | + tagged_locals.extend(fields); |
| 1049 | + } |
| 1050 | + None => tagged_locals.push(format!("v{v} = TL_UNIT")), |
| 1051 | + } |
| 1052 | + } |
| 1053 | + for chunk in tagged_locals.chunks(8) { |
| 1054 | + let _ = writeln!(out, " tl_value {};", chunk.join(", ")); |
| 1055 | + } |
| 1056 | + // What the frame holds on entry: the owned parameters, a flat one |
| 1057 | + // by its fields (the unwind drops them field by field). |
| 1058 | + let owned: Vec<VarId> = decl |
| 1059 | + .params |
| 1060 | + .iter() |
| 1061 | + .enumerate() |
| 1062 | + .filter(|&(i, _)| !decl.borrowed.contains(&i)) |
| 1063 | + .map(|(_, p)| *p) |
| 1064 | + .collect(); |
| 1065 | + // The worker of a recursive function keeps the preemption point: |
| 1066 | + // its own entries are the loop. |
| 1067 | + if self.cyclic.contains(&id) { |
| 1068 | + let _ = writeln!( |
| 1069 | + out, |
| 1070 | + "entry:\n if (tl_unlikely(--ctx->reductions <= 0)) {{\n tl_preempt(ctx);\n if (TL_YIELDING(ctx)) {}\n }}", |
| 1071 | + unwind_flat( |
| 1072 | + &owned, |
| 1073 | + &self.flat, |
| 1074 | + &[], |
| 1075 | + &unwind_ret(None, Some(UnboxedKind::Record), result_fields) |
| 1076 | + ) |
| 1077 | + ); |
| 1078 | + } |
| 1079 | + let func = Func { id, decl }; |
| 1080 | + self.expr(&mut out, &func, &decl.body, Dest::Return, owned, 1)?; |
| 1081 | + out.push_str("}\n\n"); |
| 1082 | + self.worker = None; |
| 1083 | + self.flat.clear(); |
| 1084 | + self.record_result = 0; |
| 1085 | + let located = self.line.is_some(); |
| 1086 | + let text = if located { pin_lines(&out) } else { out }; |
| 1087 | + Ok(Some(text)) |
| 1088 | + } |
| 1089 | + |
| 918 | 1090 | fn function(&mut self, id: FnId, decl: &FnDecl) -> Result<(), Unsupported> { |
| 919 | 1091 | if decl.params.len() > REGS + XARGS { |
| 920 | 1092 | return Err(Unsupported(format!( |
| @@ -932,6 +1104,8 @@ impl Emitter<'_> { |
| 932 | 1104 | self.static_atoms.clear(); |
| 933 | 1105 | self.ctx_cells = ctx_cells(&decl.body); |
| 934 | 1106 | self.labels = 0; |
| 1107 | + self.flat.clear(); |
| 1108 | + self.record_result = 0; |
| 935 | 1109 | self.current = id; |
| 936 | 1110 | let _ = writeln!(out, "/* {} */", decl.name); |
| 937 | 1111 | self.line = decl.span.and_then(|s| self.line_of(s)); |
| @@ -981,7 +1155,7 @@ impl Emitter<'_> { |
| 981 | 1155 | let _ = writeln!( |
| 982 | 1156 | out, |
| 983 | 1157 | "entry:\n if (tl_unlikely(--ctx->reductions <= 0)) {{\n tl_preempt(ctx);\n if (TL_YIELDING(ctx)) {}\n }}", |
| 984 | | − unwind(&owned, &unwind_ret(decl.cpr_arity, None)) |
| 1158 | + unwind(&owned, &unwind_ret(decl.cpr_arity, None, 0)) |
| 985 | 1159 | ); |
| 986 | 1160 | } |
| 987 | 1161 | let func = Func { id, decl }; |
| @@ -1271,6 +1445,14 @@ int main(void) {{ |
| 1271 | 1445 | |
| 1272 | 1446 | fn atom(&mut self, a: &Atom) -> Result<String, Unsupported> { |
| 1273 | 1447 | Ok(match a { |
| 1448 | + // A flat variable's box is rebuilt at the escape, with |
| 1449 | + // statements (`atom_boxed`): an expression position means |
| 1450 | + // the record-worker's planner missed an escape. |
| 1451 | + Atom::Var(v) if self.flat.contains_key(v) => { |
| 1452 | + panic!( |
| 1453 | + "louise: flat variable v{v} reached `atom` (record-worker planner missed an escape)" |
| 1454 | + ) |
| 1455 | + } |
| 1274 | 1456 | // A raw local escaping into a tagged position is boxed at the |
| 1275 | 1457 | // boundary (ADR 0045). |
| 1276 | 1458 | Atom::Var(v) if self.worker.is_some() && self.raw.contains(v) => match self.worker { |
| @@ -1302,6 +1484,75 @@ int main(void) {{ |
| 1302 | 1484 | atoms.iter().map(|a| self.atom(a)).collect() |
| 1303 | 1485 | } |
| 1304 | 1486 | |
| 1487 | + /// A fresh C identifier for a temporary (blocks share the counter). |
| 1488 | + fn temp(&mut self, prefix: &str) -> String { |
| 1489 | + self.labels += 1; |
| 1490 | + format!("{prefix}{}", self.labels) |
| 1491 | + } |
| 1492 | + |
| 1493 | + /// `a` as an owned value, in statement position (ADR 0069): a flat |
| 1494 | + /// variable's box is rebuilt here — `atom`'s record form, the one |
| 1495 | + /// place boxing happens — anything else is `atom`'s. `consumed` is |
| 1496 | + /// the position's ownership: the callee consumes the box (a call's |
| 1497 | + /// owned argument, a constructor's field), or borrows it — then the |
| 1498 | + /// frame owns it and drops it when the statement ends |
| 1499 | + /// (`flat_temps`; a borrowed position is why the variable's use is |
| 1500 | + /// uncounted in Core, so no `drop` exists for the box there). |
| 1501 | + fn atom_boxed( |
| 1502 | + &mut self, |
| 1503 | + out: &mut String, |
| 1504 | + ind: &str, |
| 1505 | + a: &Atom, |
| 1506 | + consumed: bool, |
| 1507 | + ) -> Result<String, Unsupported> { |
| 1508 | + match a { |
| 1509 | + Atom::Var(v) if self.flat.contains_key(v) => { |
| 1510 | + let (tag, n) = self.flat[v]; |
| 1511 | + Self::check_block(tag, n as usize)?; |
| 1512 | + let t = self.temp("bx"); |
| 1513 | + let _ = writeln!( |
| 1514 | + out, |
| 1515 | + "{ind}tl_value {t} = tl_from_block(tl_alloc(ctx, {tag}, {n}, 0));" |
| 1516 | + ); |
| 1517 | + for j in 0..n { |
| 1518 | + // A borrowed box dups the fields (the variable keeps |
| 1519 | + // them); a consumed one moves them. |
| 1520 | + let (open, close) = if consumed { ("", "") } else { ("tl_dup(", ")") }; |
| 1521 | + let _ = writeln!( |
| 1522 | + out, |
| 1523 | + "{ind}tl_as_block({t})->fields[{j}] = {open}v{v}f{j}{close};" |
| 1524 | + ); |
| 1525 | + } |
| 1526 | + if !consumed { |
| 1527 | + self.flat_temps.push(t.clone()); |
| 1528 | + } |
| 1529 | + Ok(t) |
| 1530 | + } |
| 1531 | + a => self.atom(a), |
| 1532 | + } |
| 1533 | + } |
| 1534 | + |
| 1535 | + /// [`atom_boxed`] for each of `atoms`, with each position's |
| 1536 | + /// ownership. |
| 1537 | + fn atoms_boxed( |
| 1538 | + &mut self, |
| 1539 | + out: &mut String, |
| 1540 | + ind: &str, |
| 1541 | + atoms: &[(Atom, bool)], |
| 1542 | + ) -> Result<Vec<String>, Unsupported> { |
| 1543 | + atoms |
| 1544 | + .iter() |
| 1545 | + .map(|(a, consumed)| self.atom_boxed(out, ind, a, *consumed)) |
| 1546 | + .collect() |
| 1547 | + } |
| 1548 | + |
| 1549 | + /// Drop the boxes rebuilt at borrowed positions in this statement |
| 1550 | + /// (ADR 0069), on the normal and the unwinding path alike. |
| 1551 | + fn drop_flat_temps(&mut self, out: &mut String, ind: &str) { |
| 1552 | + for t in std::mem::take(&mut self.flat_temps) { |
| 1553 | + let _ = writeln!(out, "{ind}tl_drop(ctx, {t});"); |
| 1554 | + } |
| 1555 | + } |
| 1305 | 1556 | /// A string literal's static block, named after its contents so the |
| 1306 | 1557 | /// name doesn't depend on the literals before it. |
| 1307 | 1558 | fn string_lit(&mut self, s: &str) -> String { |
| @@ -1511,7 +1762,14 @@ int main(void) {{ |
| 1511 | 1762 | Expr::Dup(v, rest) => { |
| 1512 | 1763 | // A double is not a reference: nothing to count. |
| 1513 | 1764 | // Neither is a proven-small integer (issue #191). |
| 1514 | | − if !self.raw.contains(v) && !self.ranges.small(f.id, &Atom::Var(*v)) { |
| 1765 | + if let Some((_, n)) = self.flat.get(v).copied() { |
| 1766 | + // A flat value (ADR 0069): the fields are the |
| 1767 | + // references. |
| 1768 | + for j in 0..n { |
| 1769 | + let _ = writeln!(out, "{ind}tl_dup(v{v}f{j});"); |
| 1770 | + } |
| 1771 | + held.push(*v); |
| 1772 | + } else if !self.raw.contains(v) && !self.ranges.small(f.id, &Atom::Var(*v)) { |
| 1515 | 1773 | let _ = writeln!(out, "{ind}tl_dup(v{v});"); |
| 1516 | 1774 | held.push(*v); |
| 1517 | 1775 | } |
| @@ -1524,6 +1782,14 @@ int main(void) {{ |
| 1524 | 1782 | e = rest; |
| 1525 | 1783 | continue; |
| 1526 | 1784 | } |
| 1785 | + if let Some((_, n)) = self.flat.get(v).copied() { |
| 1786 | + for j in 0..n { |
| 1787 | + let _ = writeln!(out, "{ind}tl_drop(ctx, v{v}f{j});"); |
| 1788 | + } |
| 1789 | + take(&mut held, *v); |
| 1790 | + e = rest; |
| 1791 | + continue; |
| 1792 | + } |
| 1527 | 1793 | // A fused comparison's result: never materialized, |
| 1528 | 1794 | // and a small integer's drop is a no-op anyway. |
| 1529 | 1795 | if self.cmp_skip.contains(v) || self.ranges.small(f.id, &Atom::Var(*v)) { |
| @@ -1544,7 +1810,28 @@ int main(void) {{ |
| 1544 | 1810 | keep, |
| 1545 | 1811 | rest, |
| 1546 | 1812 | } => { |
| 1547 | | − Self::release(out, *var, fields, *token, keep, &ind); |
| 1813 | + if self.flat.contains_key(var) { |
| 1814 | + // A flat value (ADR 0069): no cell exists; the |
| 1815 | + // bound fields move to their bindings, the rest |
| 1816 | + // are dropped, and the token is unit (reusing it |
| 1817 | + // allocates, exactly as a token that lost its |
| 1818 | + // cell). |
| 1819 | + for (i, a) in fields { |
| 1820 | + let _ = writeln!(out, "{ind}v{a} = v{var}f{i};"); |
| 1821 | + } |
| 1822 | + let n = self.flat[var].1; |
| 1823 | + let bound: BTreeSet<u32> = fields.iter().map(|(i, _)| *i).collect(); |
| 1824 | + for j in 0..n { |
| 1825 | + if !bound.contains(&j) { |
| 1826 | + let _ = writeln!(out, "{ind}tl_drop(ctx, v{var}f{j});"); |
| 1827 | + } |
| 1828 | + } |
| 1829 | + if let Some(t) = token { |
| 1830 | + let _ = writeln!(out, "{ind}v{t} = TL_UNIT;"); |
| 1831 | + } |
| 1832 | + } else { |
| 1833 | + Self::release(out, *var, fields, *token, keep, &ind); |
| 1834 | + } |
| 1548 | 1835 | take(&mut held, *var); |
| 1549 | 1836 | held.extend(fields.iter().map(|(_, a)| *a)); |
| 1550 | 1837 | held.extend(token); |
| @@ -1555,11 +1842,30 @@ int main(void) {{ |
| 1555 | 1842 | out, |
| 1556 | 1843 | "{ind}tl_panic_str(ctx, \"{}\");\n{ind}{}", |
| 1557 | 1844 | c_escape(msg), |
| 1558 | | − unwind(&held, &unwind_ret(f.decl.cpr_arity, self.worker)) |
| 1845 | + unwind_flat( |
| 1846 | + &held, |
| 1847 | + &self.flat, |
| 1848 | + &self.flat_temps, |
| 1849 | + &unwind_ret(f.decl.cpr_arity, self.worker, self.record_result) |
| 1850 | + ) |
| 1559 | 1851 | ); |
| 1560 | 1852 | return Ok(None); |
| 1561 | 1853 | } |
| 1562 | 1854 | Expr::Switch { on, cases, default } => { |
| 1855 | + // A switch on a flat value (ADR 0069): the |
| 1856 | + // constructor is known — emit the matching arm, no |
| 1857 | + // dispatch. |
| 1858 | + if let Atom::Var(s) = on |
| 1859 | + && let Some((tag, _)) = self.flat.get(s).copied() |
| 1860 | + { |
| 1861 | + let body = cases |
| 1862 | + .iter() |
| 1863 | + .find(|(t, _)| *t == tag) |
| 1864 | + .map(|(_, b)| b) |
| 1865 | + .or(default.as_deref()) |
| 1866 | + .expect("a single-constructor switch has its arm"); |
| 1867 | + return self.expr(out, f, body, dest, held, depth); |
| 1868 | + } |
| 1563 | 1869 | // A switch on a comparison's result: a direct |
| 1564 | 1870 | // compare-and-branch (issue #191). |
| 1565 | 1871 | if let Atom::Var(s) = on |
| @@ -1677,7 +1983,7 @@ int main(void) {{ |
| 1677 | 1983 | // A borrowed closure call (ADR 0068) consumes nothing: the frame |
| 1678 | 1984 | // keeps its references across the call — the unwinding path drops |
| 1679 | 1985 | // them — and drops them once the call returns. |
| 1680 | | − let borrowed_call = self.borrow_closures && self.borrowed_call(value, held); |
| 1986 | + let borrowed_call = self.borrow_closures && self.borrowed_call(value); |
| 1681 | 1987 | if !borrowed_call { |
| 1682 | 1988 | for o in &owned { |
| 1683 | 1989 | take(held, *o); |
| @@ -1688,7 +1994,12 @@ int main(void) {{ |
| 1688 | 1994 | let _ = writeln!( |
| 1689 | 1995 | out, |
| 1690 | 1996 | "{ind}if (TL_YIELDING(ctx)) {}", |
| 1691 | | − unwind(held, &unwind_ret(f.decl.cpr_arity, self.worker)) |
| 1997 | + unwind_flat( |
| 1998 | + held, |
| 1999 | + &self.flat, |
| 2000 | + &self.flat_temps, |
| 2001 | + &unwind_ret(f.decl.cpr_arity, self.worker, self.record_result) |
| 2002 | + ) |
| 1692 | 2003 | ); |
| 1693 | 2004 | } |
| 1694 | 2005 | if borrowed_call { |
| @@ -1701,6 +2012,7 @@ int main(void) {{ |
| 1701 | 2012 | take(held, *o); |
| 1702 | 2013 | } |
| 1703 | 2014 | } |
| 2015 | + self.drop_flat_temps(out, &ind); |
| 1704 | 2016 | // A projection is borrowed (a `dup` follows if it is |
| 1705 | 2017 | // owned); a raw double is no reference at all. |
| 1706 | 2018 | if !matches!(value, Value::Field(..)) && !self.raw.contains(&v) { |
| @@ -1724,6 +2036,10 @@ int main(void) {{ |
| 1724 | 2036 | } |
| 1725 | 2037 | match dest { |
| 1726 | 2038 | Dest::Return => { |
| 2039 | + if self.worker == Some(UnboxedKind::Record) { |
| 2040 | + self.return_record(out, a, ind)?; |
| 2041 | + return Ok(None); |
| 2042 | + } |
| 1727 | 2043 | if self.worker.is_some() { |
| 1728 | 2044 | // A boxed result read raw: the return consumed the |
| 1729 | 2045 | // box, so free it after the read (issue #279). |
| @@ -1740,18 +2056,45 @@ int main(void) {{ |
| 1740 | 2056 | } |
| 1741 | 2057 | } |
| 1742 | 2058 | } else { |
| 1743 | | − let a = self.atom(a)?; |
| 2059 | + let a = self.atom_boxed(out, ind, a, true)?; |
| 1744 | 2060 | let _ = writeln!(out, "{ind}return {a};"); |
| 1745 | 2061 | } |
| 1746 | 2062 | Ok(None) |
| 1747 | 2063 | } |
| 1748 | 2064 | Dest::Assign(v, label) => { |
| 1749 | | − // A block's value: raw or boxed as the |
| 2065 | + // A block's value: raw, flat or boxed as the |
| 1750 | 2066 | // destination's local is. |
| 2067 | + if let Some((_, n)) = self.flat.get(&v).copied() { |
| 2068 | + // The destination is flat (ADR 0069): the fields. |
| 2069 | + match a { |
| 2070 | + Atom::Var(x) if self.flat.contains_key(x) => { |
| 2071 | + debug_assert_eq!(self.flat[x].1, n, "flat assign: one shape"); |
| 2072 | + for j in 0..n { |
| 2073 | + let _ = writeln!(out, "{ind}v{v}f{j} = v{x}f{j};"); |
| 2074 | + } |
| 2075 | + } |
| 2076 | + Atom::Var(x) => { |
| 2077 | + // A boxed record: read the fields, free the |
| 2078 | + // box (the assignment consumed it). |
| 2079 | + let uf = self.temp("uf"); |
| 2080 | + let _ = writeln!( |
| 2081 | + out, |
| 2082 | + "{ind}{{\n{ind} tl_value {uf}[{n}];\n{ind} tl_unbox_fields(ctx, v{x}, {uf}, {n});" |
| 2083 | + ); |
| 2084 | + for j in 0..n { |
| 2085 | + let _ = writeln!(out, "{ind} v{v}f{j} = {uf}[{j}];"); |
| 2086 | + } |
| 2087 | + let _ = writeln!(out, "{ind}}}"); |
| 2088 | + } |
| 2089 | + _ => unreachable!("a flat block's value is a variable"), |
| 2090 | + } |
| 2091 | + let _ = writeln!(out, "{ind}goto b{label};"); |
| 2092 | + return Ok(Some(held)); |
| 2093 | + } |
| 1751 | 2094 | let s = if self.worker.is_some() && self.raw.contains(&v) { |
| 1752 | 2095 | self.raw_atom(a)? |
| 1753 | 2096 | } else { |
| 1754 | | − self.atom(a)? |
| 2097 | + self.atom_boxed(out, ind, a, true)? |
| 1755 | 2098 | }; |
| 1756 | 2099 | let _ = writeln!(out, "{ind}v{v} = {s};\n{ind}goto b{label};"); |
| 1757 | 2100 | Ok(Some(held)) |
| @@ -1759,6 +2102,49 @@ int main(void) {{ |
| 1759 | 2102 | } |
| 1760 | 2103 | } |
| 1761 | 2104 | |
| 2105 | + /// A record worker's exit (ADR 0069): the result's fields, by value. |
| 2106 | + /// A flat variable's locals are returned; a boxed record is read and |
| 2107 | + /// freed (the return consumed it — `tl_unbox_fields`). |
| 2108 | + fn return_record(&mut self, out: &mut String, a: &Atom, ind: &str) -> Result<(), Unsupported> { |
| 2109 | + let n = self.record_result; |
| 2110 | + if n == 0 { |
| 2111 | + // The result stays boxed: a flat variable escapes (the box |
| 2112 | + // is rebuilt), anything else is a plain return. |
| 2113 | + let a = self.atom_boxed(out, ind, a, true)?; |
| 2114 | + let _ = writeln!(out, "{ind}return {a};"); |
| 2115 | + return Ok(()); |
| 2116 | + } |
| 2117 | + let Atom::Var(x) = a else { |
| 2118 | + unreachable!("a flattened result is a variable"); |
| 2119 | + }; |
| 2120 | + if self.flat.contains_key(x) { |
| 2121 | + if n == 1 { |
| 2122 | + let _ = writeln!(out, "{ind}return v{x}f0;"); |
| 2123 | + } else { |
| 2124 | + let fields: Vec<String> = (0..n).map(|j| format!("v{x}f{j}")).collect(); |
| 2125 | + let _ = writeln!(out, "{ind}return (tl_pair{n}){{ {} }};", fields.join(", ")); |
| 2126 | + } |
| 2127 | + return Ok(()); |
| 2128 | + } |
| 2129 | + // A boxed record the return consumed. |
| 2130 | + let uf = self.temp("uf"); |
| 2131 | + let _ = writeln!( |
| 2132 | + out, |
| 2133 | + "{ind}{{\n{ind} tl_value {uf}[{n}];\n{ind} tl_unbox_fields(ctx, v{x}, {uf}, {n});" |
| 2134 | + ); |
| 2135 | + if n == 1 { |
| 2136 | + let _ = writeln!(out, "{ind} return {uf}[0];\n{ind}}}"); |
| 2137 | + } else { |
| 2138 | + let fields: Vec<String> = (0..n).map(|j| format!("{uf}[{j}]")).collect(); |
| 2139 | + let _ = writeln!( |
| 2140 | + out, |
| 2141 | + "{ind} return (tl_pair{n}){{ {} }};\n{ind}}}", |
| 2142 | + fields.join(", ") |
| 2143 | + ); |
| 2144 | + } |
| 2145 | + Ok(()) |
| 2146 | + } |
| 2147 | + |
| 1762 | 2148 | /// A CPR worker's exit (issue #200): return the components `atoms` as |
| 1763 | 2149 | /// the struct. It always leaves the function, so the destination (a |
| 1764 | 2150 | /// block's label) doesn't matter. |
| @@ -1815,7 +2201,7 @@ int main(void) {{ |
| 1815 | 2201 | if tail && self.program.fns[*g as usize].cpr_arity == Some(vars.len() as u32) { |
| 1816 | 2202 | // A tail call of a worker of the same shape: |
| 1817 | 2203 | // `musttail`, the signatures match. |
| 1818 | | − let slots = self.atoms(args)?; |
| 2204 | + let slots = self.atoms_boxed(out, ind, &owned_args(args))?; |
| 1819 | 2205 | store_xargs(&slots, ind, out); |
| 1820 | 2206 | self.uses.fns.insert(*g); |
| 1821 | 2207 | let _ = writeln!( |
| @@ -1828,7 +2214,7 @@ int main(void) {{ |
| 1828 | 2214 | } |
| 1829 | 2215 | let arity = vars.len(); |
| 1830 | 2216 | let tmp = format!("p{}", vars[0]); |
| 1831 | | − let slots = self.atoms(args)?; |
| 2217 | + let slots = self.atoms_boxed(out, ind, &owned_args(args))?; |
| 1832 | 2218 | store_xargs(&slots, ind, out); |
| 1833 | 2219 | self.uses.fns.insert(*g); |
| 1834 | 2220 | let _ = writeln!( |
| @@ -1841,7 +2227,12 @@ int main(void) {{ |
| 1841 | 2227 | let _ = writeln!( |
| 1842 | 2228 | out, |
| 1843 | 2229 | "{ind}if (TL_YIELDING(ctx)) {}", |
| 1844 | | − unwind(held, &unwind_ret(f.decl.cpr_arity, self.worker)) |
| 2230 | + unwind_flat( |
| 2231 | + held, |
| 2232 | + &self.flat, |
| 2233 | + &self.flat_temps, |
| 2234 | + &unwind_ret(f.decl.cpr_arity, self.worker, self.record_result) |
| 2235 | + ) |
| 1845 | 2236 | ); |
| 1846 | 2237 | } |
| 1847 | 2238 | for (i, v) in vars.iter().enumerate() { |
| @@ -2433,6 +2824,56 @@ int main(void) {{ |
| 2433 | 2824 | let _ = writeln!(out, "{ind}{{"); |
| 2434 | 2825 | let mut consumed = Vec::new(); |
| 2435 | 2826 | for (i, a) in args.iter().enumerate() { |
| 2827 | + let p = f.decl.params[i]; |
| 2828 | + if self.worker == Some(UnboxedKind::Record) { |
| 2829 | + // A flat slot (ADR 0069): a flat argument's fields, or a |
| 2830 | + // boxed record's, read and freed (the call consumed it; |
| 2831 | + // a borrowed one is read in place). |
| 2832 | + match self.flat.get(&p).copied() { |
| 2833 | + Some((_, n)) => { |
| 2834 | + match a { |
| 2835 | + Atom::Var(av) if self.flat.get(av).is_some_and(|(_, m)| *m == n) => { |
| 2836 | + for j in 0..n { |
| 2837 | + let _ = writeln!(out, "{ind} tl_value t{i}f{j} = v{av}f{j};"); |
| 2838 | + } |
| 2839 | + } |
| 2840 | + a if f.decl.borrowed.contains(&i) => { |
| 2841 | + // A flat value rebuilt for the borrowed |
| 2842 | + // slot (a shape mismatch — the types say |
| 2843 | + // it can't happen) is dropped after the |
| 2844 | + // reads. |
| 2845 | + let escape = matches!(a, Atom::Var(v) if self.flat.contains_key(v)); |
| 2846 | + let a = self.atom_boxed(out, &format!("{ind} "), a, true)?; |
| 2847 | + for j in 0..n { |
| 2848 | + let _ = writeln!( |
| 2849 | + out, |
| 2850 | + "{ind} tl_value t{i}f{j} = tl_as_block({a})->fields[{j}];" |
| 2851 | + ); |
| 2852 | + } |
| 2853 | + if escape { |
| 2854 | + let _ = writeln!(out, "{ind} tl_drop(ctx, {a});"); |
| 2855 | + } |
| 2856 | + } |
| 2857 | + a => { |
| 2858 | + let a = self.atom_boxed(out, &format!("{ind} "), a, true)?; |
| 2859 | + let uf = self.temp("uf"); |
| 2860 | + let _ = writeln!( |
| 2861 | + out, |
| 2862 | + "{ind} tl_value {uf}[{n}];\n{ind} tl_unbox_fields(ctx, {a}, {uf}, {n});" |
| 2863 | + ); |
| 2864 | + for j in 0..n { |
| 2865 | + let _ = writeln!(out, "{ind} tl_value t{i}f{j} = {uf}[{j}];"); |
| 2866 | + } |
| 2867 | + } |
| 2868 | + } |
| 2869 | + } |
| 2870 | + None => { |
| 2871 | + let a = self.atom_boxed(out, &format!("{ind} "), a, true)?; |
| 2872 | + let _ = writeln!(out, "{ind} tl_value t{i} = {a};"); |
| 2873 | + } |
| 2874 | + } |
| 2875 | + continue; |
| 2876 | + } |
| 2436 | 2877 | if self.worker.is_some() && f.decl.unbox_sig.as_ref().is_some_and(|s| s.marked(i)) { |
| 2437 | 2878 | let raw_ty = match self.worker { |
| 2438 | 2879 | Some(UnboxedKind::Int) => "int64_t", |
| @@ -2442,7 +2883,7 @@ int main(void) {{ |
| 2442 | 2883 | let _ = writeln!(out, "{ind} {raw_ty} t{i} = {a};"); |
| 2443 | 2884 | consumed.extend(drop); |
| 2444 | 2885 | } else { |
| 2445 | | − let a = self.atom(a)?; |
| 2886 | + let a = self.atom_boxed(out, &format!("{ind} "), a, true)?; |
| 2446 | 2887 | let _ = writeln!(out, "{ind} tl_value t{i} = {a};"); |
| 2447 | 2888 | } |
| 2448 | 2889 | } |
| @@ -2450,6 +2891,14 @@ int main(void) {{ |
| 2450 | 2891 | let _ = writeln!(out, "{ind} tl_drop(ctx, v{v});"); |
| 2451 | 2892 | } |
| 2452 | 2893 | for (i, p) in f.decl.params.iter().enumerate() { |
| 2894 | + if self.worker == Some(UnboxedKind::Record) |
| 2895 | + && let Some((_, n)) = self.flat.get(p).copied() |
| 2896 | + { |
| 2897 | + for j in 0..n { |
| 2898 | + let _ = writeln!(out, "{ind} v{p}f{j} = t{i}f{j};"); |
| 2899 | + } |
| 2900 | + continue; |
| 2901 | + } |
| 2453 | 2902 | let _ = writeln!(out, "{ind} v{p} = t{i};"); |
| 2454 | 2903 | } |
| 2455 | 2904 | let _ = writeln!(out, "{ind} goto entry;\n{ind}}}"); |
| @@ -2552,7 +3001,7 @@ int main(void) {{ |
| 2552 | 3001 | // The target is raw: the literal or the unboxed local. |
| 2553 | 3002 | self.raw_atom(a)? |
| 2554 | 3003 | } else { |
| 2555 | | − self.atom(a)? |
| 3004 | + self.atom_boxed(out, ind, a, true)? |
| 2556 | 3005 | }; |
| 2557 | 3006 | let _ = writeln!(out, "{ind}v{v} = {s};"); |
| 2558 | 3007 | if self.hoist_statics |
| @@ -2566,6 +3015,13 @@ int main(void) {{ |
| 2566 | 3015 | self.uses.fns.insert(*g); |
| 2567 | 3016 | let _ = writeln!(out, "{ind}v{v} = {}_k;", self.syms[g]); |
| 2568 | 3017 | } |
| 3018 | + Value::CallFn(g, args) |
| 3019 | + if self.worker == Some(UnboxedKind::Record) && *g == self.current => |
| 3020 | + { |
| 3021 | + // The record worker's own (non-tail) call: fields in, |
| 3022 | + // fields out (ADR 0069). |
| 3023 | + self.call_record_worker(out, v, *g, args, ind)?; |
| 3024 | + } |
| 2569 | 3025 | Value::CallFn(g, args) if self.worker.is_some() && *g == self.current => { |
| 2570 | 3026 | // The worker's own (non-tail) call: raw in, raw out. An |
| 2571 | 3027 | // int worker's call can bail: the sentinel propagates |
| @@ -2619,7 +3075,8 @@ int main(void) {{ |
| 2619 | 3075 | self.call_worker(out, v, *g, args, ind)?; |
| 2620 | 3076 | } |
| 2621 | 3077 | Value::CallFn(g, args) => { |
| 2622 | | − let slots = self.atoms(args)?; |
| 3078 | + let gdecl = &self.program.fns[*g as usize]; |
| 3079 | + let slots = self.atoms_boxed(out, ind, &owned_args_but(args, &gdecl.borrowed))?; |
| 2623 | 3080 | store_xargs(&slots, ind, out); |
| 2624 | 3081 | self.uses.fns.insert(*g); |
| 2625 | 3082 | let _ = writeln!( |
| @@ -2630,9 +3087,10 @@ int main(void) {{ |
| 2630 | 3087 | ); |
| 2631 | 3088 | } |
| 2632 | 3089 | Value::Call(c, args) => { |
| 2633 | | − let c = self.atom(c)?; |
| 2634 | | − let args = self.atoms(args)?; |
| 2635 | | − let call = if self.borrow_closures && self.borrowed_call(value, held) { |
| 3090 | + let borrowed = self.borrow_closures && self.borrowed_call(value); |
| 3091 | + let c = self.atom_boxed(out, ind, c, !borrowed)?; |
| 3092 | + let args = self.atoms_boxed(out, ind, &owned_args_but_atoms(args, !borrowed))?; |
| 3093 | + let call = if borrowed { |
| 2636 | 3094 | Self::closure_call_borrowed(&c, &args, ind, out) |
| 2637 | 3095 | } else { |
| 2638 | 3096 | Self::closure_call(&c, &args, ind, out) |
| @@ -2695,6 +3153,24 @@ int main(void) {{ |
| 2695 | 3153 | } |
| 2696 | 3154 | Value::CallExtern(sym, args) => self.call_extern(out, v, sym, args, ind)?, |
| 2697 | 3155 | Value::Prim(p, args) => { |
| 3156 | + // A flat value's tag is known (ADR 0069): no box read. |
| 3157 | + if let Atom::Var(b) = &args[0] |
| 3158 | + && let Some((tag, _)) = self.flat.get(b).copied() |
| 3159 | + { |
| 3160 | + let text = match p { |
| 3161 | + Prim::TagIs(t) => { |
| 3162 | + if *t == tag { |
| 3163 | + "TL_TRUE".to_owned() |
| 3164 | + } else { |
| 3165 | + "TL_FALSE".to_owned() |
| 3166 | + } |
| 3167 | + } |
| 3168 | + Prim::Tag => format!("tl_int({tag})"), |
| 3169 | + Prim::Not => unreachable!("a record is no Bool"), |
| 3170 | + }; |
| 3171 | + let _ = writeln!(out, "{ind}v{v} = {text};"); |
| 3172 | + return Ok(()); |
| 3173 | + } |
| 2698 | 3174 | let a = self.atom(&args[0])?; |
| 2699 | 3175 | let text = match p { |
| 2700 | 3176 | Prim::Not => format!("({a} == TL_TRUE) ? TL_FALSE : TL_TRUE"), |
| @@ -2704,22 +3180,44 @@ int main(void) {{ |
| 2704 | 3180 | let _ = writeln!(out, "{ind}v{v} = {text};"); |
| 2705 | 3181 | } |
| 2706 | 3182 | Value::Construct { tag, args, .. } => { |
| 2707 | | − if let Some(name) = self.static_construct(v, *tag, args) { |
| 3183 | + if let Some((_, n)) = self.flat.get(&v).copied() { |
| 3184 | + // A flat local (ADR 0069): the fields are the locals; |
| 3185 | + // no box is ever allocated. |
| 3186 | + debug_assert_eq!(n as usize, args.len()); |
| 3187 | + let args = self.atoms_boxed(out, ind, &owned_args(args))?; |
| 3188 | + for (j, a) in args.iter().enumerate() { |
| 3189 | + let _ = writeln!(out, "{ind}v{v}f{j} = {a};"); |
| 3190 | + } |
| 3191 | + } else if let Some(name) = self.static_construct(v, *tag, args) { |
| 2708 | 3192 | let _ = writeln!(out, "{ind}v{v} = (tl_value)&{name};"); |
| 2709 | 3193 | } else { |
| 2710 | | − let args = self.atoms(args)?; |
| 3194 | + let args = self.atoms_boxed(out, ind, &owned_args(args))?; |
| 2711 | 3195 | self.block(out, v, *tag, &args, ind)?; |
| 2712 | 3196 | } |
| 2713 | 3197 | } |
| 2714 | 3198 | Value::Tuple(args) => { |
| 2715 | | − if let Some(name) = self.static_construct(v, 0, args) { |
| 3199 | + if let Some((_, n)) = self.flat.get(&v).copied() { |
| 3200 | + debug_assert_eq!(n as usize, args.len()); |
| 3201 | + let args = self.atoms_boxed(out, ind, &owned_args(args))?; |
| 3202 | + for (j, a) in args.iter().enumerate() { |
| 3203 | + let _ = writeln!(out, "{ind}v{v}f{j} = {a};"); |
| 3204 | + } |
| 3205 | + } else if let Some(name) = self.static_construct(v, 0, args) { |
| 2716 | 3206 | let _ = writeln!(out, "{ind}v{v} = (tl_value)&{name};"); |
| 2717 | 3207 | } else { |
| 2718 | | − let args = self.atoms(args)?; |
| 3208 | + let args = self.atoms_boxed(out, ind, &owned_args(args))?; |
| 2719 | 3209 | self.block(out, v, 0, &args, ind)?; |
| 2720 | 3210 | } |
| 2721 | 3211 | } |
| 2722 | 3212 | Value::Field(base, i) => { |
| 3213 | + // A flat value's projection reads the field local. |
| 3214 | + if let Atom::Var(b) = base |
| 3215 | + && let Some((_, n)) = self.flat.get(b).copied() |
| 3216 | + { |
| 3217 | + assert!((*i) < n, "a projection past the record's fields"); |
| 3218 | + let _ = writeln!(out, "{ind}v{v} = v{b}f{i};"); |
| 3219 | + return Ok(()); |
| 3220 | + } |
| 2723 | 3221 | let b = self.atom(base)?; |
| 2724 | 3222 | let _ = writeln!(out, "{ind}v{v} = tl_as_block({b})->fields[{i}];"); |
| 2725 | 3223 | } |
| @@ -2728,9 +3226,29 @@ int main(void) {{ |
| 2728 | 3226 | value, |
| 2729 | 3227 | sized, |
| 2730 | 3228 | keep, |
| 2731 | | − } => self.reuse(out, v, *token, value, *sized, keep, ind)?, |
| 3229 | + } => { |
| 3230 | + if let Some((_, n)) = self.flat.get(&v).copied() { |
| 3231 | + // The result is flat (ADR 0069): no cell is reused |
| 3232 | + // (the token, possibly unit, is dropped) — the |
| 3233 | + // fields are stored into the locals. |
| 3234 | + let (tag, args) = match &**value { |
| 3235 | + Value::Construct { tag, args, .. } => (*tag, args), |
| 3236 | + Value::Tuple(args) => (0, args), |
| 3237 | + _ => unreachable!("only constructions reuse cells"), |
| 3238 | + }; |
| 3239 | + let _ = tag; |
| 3240 | + debug_assert_eq!(n as usize, args.len()); |
| 3241 | + let args = self.atoms_boxed(out, ind, &owned_args(args))?; |
| 3242 | + let _ = writeln!(out, "{ind}tl_drop(ctx, v{token});"); |
| 3243 | + for (j, a) in args.iter().enumerate() { |
| 3244 | + let _ = writeln!(out, "{ind}v{v}f{j} = {a};"); |
| 3245 | + } |
| 3246 | + } else { |
| 3247 | + self.reuse(out, v, *token, value, *sized, keep, ind)?; |
| 3248 | + } |
| 3249 | + } |
| 2732 | 3250 | Value::Closure(fid, caps) => { |
| 2733 | | − let caps = self.atoms(caps)?; |
| 3251 | + let caps = self.atoms_boxed(out, ind, &owned_args(caps))?; |
| 2734 | 3252 | if caps.len() > 254 { |
| 2735 | 3253 | return Err(Unsupported( |
| 2736 | 3254 | "closures capturing more than 254 values".into(), |
| @@ -2757,7 +3275,7 @@ int main(void) {{ |
| 2757 | 3275 | op, |
| 2758 | 3276 | args, |
| 2759 | 3277 | } => { |
| 2760 | | − let borrowed = self.borrow_closures && self.borrowed_call(value, held); |
| 3278 | + let borrowed = self.borrow_closures && self.borrowed_call(value); |
| 2761 | 3279 | self.perform(out, v, cap, *effect, *op, args, ind, borrowed)?; |
| 2762 | 3280 | } |
| 2763 | 3281 | Value::Handle { |
| @@ -2770,11 +3288,13 @@ int main(void) {{ |
| 2770 | 3288 | Value::Defer { body, cleanup } => self.defer(out, v, body, cleanup, ind)?, |
| 2771 | 3289 | // Tail recursion modulo cons (ADR 0039): `louise_rt.h`. |
| 2772 | 3290 | Value::CtxExtend { ctx, cell, hole } => { |
| 2773 | | − let (k, cell) = (self.atom(ctx)?, self.atom(cell)?); |
| 3291 | + let k = self.atom_boxed(out, ind, ctx, true)?; |
| 3292 | + let cell = self.atom_boxed(out, ind, cell, true)?; |
| 2774 | 3293 | let _ = writeln!(out, "{ind}v{v} = tl_ctx_extend(ctx, {k}, {cell}, {hole});"); |
| 2775 | 3294 | } |
| 2776 | 3295 | Value::CtxApply { ctx, value } => { |
| 2777 | | − let (k, value) = (self.atom(ctx)?, self.atom(value)?); |
| 3296 | + let k = self.atom_boxed(out, ind, ctx, true)?; |
| 3297 | + let value = self.atom_boxed(out, ind, value, true)?; |
| 2778 | 3298 | let _ = writeln!(out, "{ind}v{v} = tl_ctx_apply(ctx, {k}, {value});"); |
| 2779 | 3299 | } |
| 2780 | 3300 | Value::Block(_) => unreachable!("blocks are emitted by `expr`"), |
| @@ -2842,6 +3362,9 @@ int main(void) {{ |
| 2842 | 3362 | if sig.kind == UnboxedKind::Int { |
| 2843 | 3363 | return self.call_int_worker(out, v, g, args, &sig, ind); |
| 2844 | 3364 | } |
| 3365 | + if sig.kind == UnboxedKind::Record { |
| 3366 | + return self.call_record_worker(out, v, g, args, ind); |
| 3367 | + } |
| 2845 | 3368 | let borrowed = decl.borrowed.clone(); |
| 2846 | 3369 | let wsym = self.worker_sym(g); |
| 2847 | 3370 | let mut call = vec!["ctx".to_owned()]; |
| @@ -2888,6 +3411,112 @@ int main(void) {{ |
| 2888 | 3411 | Ok(()) |
| 2889 | 3412 | } |
| 2890 | 3413 | |
| 3414 | + /// `v = g(args)` through `g`'s record worker (ADR 0069): the flat |
| 3415 | + /// slots take the fields — a flat local's own locals, a boxed record |
| 3416 | + /// read in place (borrowed) or moved out and freed (`tl_unbox_fields`; |
| 3417 | + /// the call consumed it) — the rest tagged. The result's fields land |
| 3418 | + /// in `v`'s own field locals when `v` is flat, else the box is built |
| 3419 | + /// (or `v` is plain when the result stays boxed). |
| 3420 | + fn call_record_worker( |
| 3421 | + &mut self, |
| 3422 | + out: &mut String, |
| 3423 | + v: VarId, |
| 3424 | + g: FnId, |
| 3425 | + args: &[Atom], |
| 3426 | + ind: &str, |
| 3427 | + ) -> Result<(), Unsupported> { |
| 3428 | + let (result_fields, flat) = { |
| 3429 | + let plan = &self.workers[&g]; |
| 3430 | + (plan.result_fields, plan.flat.clone()) |
| 3431 | + }; |
| 3432 | + let gdecl = &self.program.fns[g as usize]; |
| 3433 | + let mut pre = String::new(); |
| 3434 | + let mut call = vec!["ctx".to_owned()]; |
| 3435 | + for (i, a) in args.iter().enumerate() { |
| 3436 | + let Some(pv) = gdecl.params.get(i) else { |
| 3437 | + break; |
| 3438 | + }; |
| 3439 | + let Some((_, n)) = flat.get(pv).copied() else { |
| 3440 | + // A boxed slot. |
| 3441 | + call.push(self.atom_boxed(out, ind, a, !gdecl.borrowed.contains(&i))?); |
| 3442 | + continue; |
| 3443 | + }; |
| 3444 | + match a { |
| 3445 | + // A flat local of the caller: its field locals, straight. |
| 3446 | + Atom::Var(av) if self.flat.get(av).is_some_and(|(_, m)| *m == n) => { |
| 3447 | + for j in 0..n { |
| 3448 | + call.push(format!("v{av}f{j}")); |
| 3449 | + } |
| 3450 | + } |
| 3451 | + // A borrowed argument's box is read in place. |
| 3452 | + a if gdecl.borrowed.contains(&i) |
| 3453 | + && !matches!(a, Atom::Var(v) if self.flat.contains_key(v)) => |
| 3454 | + { |
| 3455 | + let a = self.atom(a)?; |
| 3456 | + for j in 0..n { |
| 3457 | + call.push(format!("tl_as_block({a})->fields[{j}]")); |
| 3458 | + } |
| 3459 | + } |
| 3460 | + // A box the call consumes: moved out and freed. (A flat |
| 3461 | + // local of another shape — the types say no — is rebuilt |
| 3462 | + // into an owned box first, so this covers it too.) |
| 3463 | + a => { |
| 3464 | + let a = self.atom_boxed(out, ind, a, true)?; |
| 3465 | + let uf = self.temp("uf"); |
| 3466 | + let _ = writeln!( |
| 3467 | + pre, |
| 3468 | + "{ind} tl_value {uf}[{n}];\n{ind} tl_unbox_fields(ctx, {a}, {uf}, {n});" |
| 3469 | + ); |
| 3470 | + for j in 0..n { |
| 3471 | + call.push(format!("{uf}[{j}]")); |
| 3472 | + } |
| 3473 | + } |
| 3474 | + } |
| 3475 | + } |
| 3476 | + self.uses.fns.insert(g); |
| 3477 | + let wsym = self.worker_sym(g); |
| 3478 | + match (result_fields, self.flat.get(&v).copied()) { |
| 3479 | + // The caller keeps the result flat: into its field locals. |
| 3480 | + (n, Some((_, m))) if n == m && n > 0 => { |
| 3481 | + if n == 1 { |
| 3482 | + let _ = writeln!(out, "{ind}{pre}{ind}v{v}f0 = {wsym}({});", call.join(", ")); |
| 3483 | + } else { |
| 3484 | + let _ = writeln!( |
| 3485 | + out, |
| 3486 | + "{ind}{pre}{ind}tl_pair{n} r{v} = {wsym}({});", |
| 3487 | + call.join(", ") |
| 3488 | + ); |
| 3489 | + for j in 0..n { |
| 3490 | + let _ = writeln!(out, "{ind}v{v}f{j} = r{v}.f{j};"); |
| 3491 | + } |
| 3492 | + } |
| 3493 | + } |
| 3494 | + // A flattened result the caller takes boxed: build the box. |
| 3495 | + (n, None) if n > 0 => { |
| 3496 | + let _ = writeln!( |
| 3497 | + out, |
| 3498 | + "{ind}{pre}{ind}{} r{v} = {wsym}({});", |
| 3499 | + Self::record_ret(n), |
| 3500 | + call.join(", ") |
| 3501 | + ); |
| 3502 | + let _ = writeln!(out, "{ind}v{v} = tl_from_block(tl_alloc(ctx, 0, {n}, 0));"); |
| 3503 | + for j in 0..n { |
| 3504 | + let f = if n == 1 { |
| 3505 | + format!("r{v}") |
| 3506 | + } else { |
| 3507 | + format!("r{v}.f{j}") |
| 3508 | + }; |
| 3509 | + let _ = writeln!(out, "{ind}tl_as_block(v{v})->fields[{j}] = {f};"); |
| 3510 | + } |
| 3511 | + } |
| 3512 | + // A boxed result, as any call's. |
| 3513 | + _ => { |
| 3514 | + let _ = writeln!(out, "{ind}{pre}{ind}v{v} = {wsym}({});", call.join(", ")); |
| 3515 | + } |
| 3516 | + } |
| 3517 | + Ok(()) |
| 3518 | + } |
| 3519 | + |
| 2891 | 3520 | /// The int worker's boundary (ADR 0045, Revision 2): the worker runs |
| 2892 | 3521 | /// only on small-int arguments; its `TL_INT_BAIL` (or a big-integer |
| 2893 | 3522 | /// argument) recomputes the call with the boxed wrapper — which the |
| @@ -3056,7 +3685,8 @@ int main(void) {{ |
| 3056 | 3685 | // Range-proven int ops skip their checks (ADR 0046, |
| 3057 | 3686 | // piece 3), before the arguments become C. |
| 3058 | 3687 | let fast = self.ranges.unchecked(self.current, sym, args); |
| 3059 | | − let args = self.atoms(args)?; |
| 3688 | + let owned = self.program.owned.contains(sym); |
| 3689 | + let args = self.atoms_boxed(out, ind, &owned_args_but_atoms(args, owned))?; |
| 3060 | 3690 | if let Some(pool) = self.program.blocking.get(sym) { |
| 3061 | 3691 | // Run it on its blocking pool (ADR 0005). |
| 3062 | 3692 | let pool = match pool { |
| @@ -3123,7 +3753,7 @@ int main(void) {{ |
| 3123 | 3753 | Value::Tuple(args) => (0, args), |
| 3124 | 3754 | _ => unreachable!("only constructions reuse cells"), |
| 3125 | 3755 | }; |
| 3126 | | − let args = self.atoms(args)?; |
| 3756 | + let args = self.atoms_boxed(out, ind, &owned_args(args))?; |
| 3127 | 3757 | Self::check_block(tag, args.len())?; |
| 3128 | 3758 | // In place if the token is a unique cell of the same size (a |
| 3129 | 3759 | // copied `multi ctl` continuation shares its tokens). A |