| @@ -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 | |
| @@ -143,13 +144,20 @@ const DECLARED: &[&str] = &[ |
| 143 | 144 | "tl_eprintln", |
| 144 | 145 | ]; |
| 145 | 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. |
| 146 | 152 | pub(crate) fn emit( |
| 147 | 153 | program: &Program, |
| 148 | 154 | entries: &[FnId], |
| 149 | 155 | reachable: &BTreeSet<FnId>, |
| 156 | + sources: Option<&SourceDb>, |
| 150 | 157 | ) -> Result<String, Unsupported> { |
| 151 | 158 | let mut e = Emitter { |
| 152 | 159 | program, |
| 160 | + sources, |
| 153 | 161 | lits: String::new(), |
| 154 | 162 | lit_ids: HashMap::new(), |
| 155 | 163 | entries: BTreeSet::new(), |
| @@ -157,8 +165,11 @@ pub(crate) fn emit( |
| 157 | 165 | thunks: String::new(), |
| 158 | 166 | constants: BTreeSet::new(), |
| 159 | 167 | constant_defs: String::new(), |
| 160 | | − body: String::new(), |
| 168 | + generated: String::new(), |
| 169 | + located: String::new(), |
| 161 | 170 | labels: 0, |
| 171 | + line: None, |
| 172 | + written: None, |
| 162 | 173 | }; |
| 163 | 174 | for f in reachable { |
| 164 | 175 | e.constant(*f, &program.fns[*f as usize]); |
| @@ -190,7 +201,6 @@ pub(crate) fn emit( |
| 190 | 201 | } |
| 191 | 202 | out.push('\n'); |
| 192 | 203 | out.push_str(&e.constant_defs); |
| 193 | | − out.push_str(&e.body); |
| 194 | 204 | for (f, n) in e.entries.clone() { |
| 195 | 205 | e.closure_entry(&mut out, f, n); |
| 196 | 206 | } |
| @@ -242,8 +252,11 @@ int main(int argc, char **argv) {{ |
| 242 | 252 | tl_report_leaks(); |
| 243 | 253 | return code; |
| 244 | 254 | }} |
| 255 | + |
| 245 | 256 | "# |
| 246 | 257 | ); |
| 258 | + out.push_str(&e.generated); |
| 259 | + out.push_str(&e.located); |
| 247 | 260 | Ok(out) |
| 248 | 261 | } |
| 249 | 262 | |
| @@ -279,8 +292,18 @@ enum Dest { |
| 279 | 292 | Assign(VarId, u32), |
| 280 | 293 | } |
| 281 | 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 | + |
| 282 | 302 | struct Emitter<'p> { |
| 283 | 303 | program: &'p Program, |
| 304 | + /// The source files, to point `#line` directives at (none: no |
| 305 | + /// directives). |
| 306 | + sources: Option<&'p SourceDb>, |
| 284 | 307 | /// Static literal blocks. |
| 285 | 308 | lits: String, |
| 286 | 309 | lit_ids: HashMap<String, usize>, |
| @@ -293,8 +316,14 @@ struct Emitter<'p> { |
| 293 | 316 | /// Functions emitted as a static, immortal value (see `constant`). |
| 294 | 317 | constants: BTreeSet<FnId>, |
| 295 | 318 | constant_defs: String, |
| 296 | | − body: String, |
| 319 | + /// Functions without a source location, then those with one. |
| 320 | + generated: String, |
| 321 | + located: String, |
| 297 | 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>, |
| 298 | 327 | } |
| 299 | 328 | |
| 300 | 329 | /// C arguments for a call with these value slots: registers, padded. |
| @@ -323,6 +352,9 @@ impl Emitter<'_> { |
| 323 | 352 | } |
| 324 | 353 | let mut out = String::new(); |
| 325 | 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); |
| 326 | 358 | let _ = writeln!( |
| 327 | 359 | out, |
| 328 | 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) {{" |
| @@ -363,10 +395,36 @@ impl Emitter<'_> { |
| 363 | 395 | let func = Func { id, decl }; |
| 364 | 396 | self.expr(&mut out, &func, &decl.body, Dest::Return, owned, 1)?; |
| 365 | 397 | out.push_str("}\n\n"); |
| 366 | | − 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 | + } |
| 367 | 403 | Ok(()) |
| 368 | 404 | } |
| 369 | 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 | + |
| 370 | 428 | /// Record `decl` as a constant if it has no parameters and only builds |
| 371 | 429 | /// closures without captures and tuples of them: a trait dictionary |
| 372 | 430 | /// without constraints, such as `Num<Int>`. It is emitted as static, |
| @@ -381,7 +439,7 @@ impl Emitter<'_> { |
| 381 | 439 | let mut e = &decl.body; |
| 382 | 440 | loop { |
| 383 | 441 | match e { |
| 384 | | − Expr::Let(v, value, rest) => { |
| 442 | + Expr::Let(v, value, rest, _) => { |
| 385 | 443 | let name = format!("tl_const{id}_{v}"); |
| 386 | 444 | match &**value { |
| 387 | 445 | Value::Closure(f, caps) if caps.is_empty() => { |
| @@ -515,8 +573,14 @@ impl Emitter<'_> { |
| 515 | 573 | // can be a long sequence of them. |
| 516 | 574 | let mut e = e; |
| 517 | 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); |
| 518 | 582 | match e { |
| 519 | | − Expr::Let(v, value, rest) => { |
| 583 | + Expr::Let(v, value, rest, _) => { |
| 520 | 584 | let tail = matches!(dest, Dest::Return) |
| 521 | 585 | && matches!(&**rest, Expr::Return(Atom::Var(r)) if r == v); |
| 522 | 586 | if tail { |
| @@ -562,8 +626,10 @@ impl Emitter<'_> { |
| 562 | 626 | if let Value::Block(inner) = &**value { |
| 563 | 627 | self.labels += 1; |
| 564 | 628 | let label = self.labels; |
| 629 | + let line = self.line; |
| 565 | 630 | let after = |
| 566 | 631 | self.expr(out, f, inner, Dest::Assign(*v, label), held, depth)?; |
| 632 | + self.line = line; |
| 567 | 633 | let _ = writeln!(out, "{ind}b{label}:;"); |
| 568 | 634 | let Some(mut after) = after else { |
| 569 | 635 | // Every path through the block leaves the function. |
| @@ -639,12 +705,17 @@ impl Emitter<'_> { |
| 639 | 705 | let on = self.atom(on)?; |
| 640 | 706 | let mut after = None; |
| 641 | 707 | let _ = writeln!(out, "{ind}switch (tl_tag_of({on})) {{"); |
| 708 | + let line = self.line; |
| 642 | 709 | for (tag, body) in cases { |
| 710 | + self.line = line; |
| 711 | + self.sync_line(out); |
| 643 | 712 | let _ = writeln!(out, "{ind}case {tag}: {{"); |
| 644 | 713 | let a = self.expr(out, f, body, dest, held.clone(), depth + 1)?; |
| 645 | 714 | after = after.or(a); |
| 646 | 715 | let _ = writeln!(out, "{ind}}}"); |
| 647 | 716 | } |
| 717 | + self.line = line; |
| 718 | + self.sync_line(out); |
| 648 | 719 | match default { |
| 649 | 720 | Some(d) => { |
| 650 | 721 | let _ = writeln!(out, "{ind}default: {{"); |
| @@ -666,7 +737,10 @@ impl Emitter<'_> { |
| 666 | 737 | } |
| 667 | 738 | let on = self.atom(on)?; |
| 668 | 739 | let mut after = None; |
| 740 | + let line = self.line; |
| 669 | 741 | for (i, (lit, body)) in cases.iter().enumerate() { |
| 742 | + self.line = line; |
| 743 | + self.sync_line(out); |
| 670 | 744 | let test = match lit { |
| 671 | 745 | Lit::Int(n) => format!("{on} == tl_int(INT64_C({n}))"), |
| 672 | 746 | Lit::Float(x) => format!("tl_float_get({on}) == {x:e}"), |
| @@ -679,6 +753,8 @@ impl Emitter<'_> { |
| 679 | 753 | let a = self.expr(out, f, body, dest, held.clone(), depth + 1)?; |
| 680 | 754 | after = after.or(a); |
| 681 | 755 | } |
| 756 | + self.line = line; |
| 757 | + self.sync_line(out); |
| 682 | 758 | let _ = writeln!(out, "{ind}}} else {{"); |
| 683 | 759 | let a = self.expr(out, f, default, dest, held, depth + 1)?; |
| 684 | 760 | after = after.or(a); |
| @@ -1092,6 +1168,46 @@ impl Emitter<'_> { |
| 1092 | 1168 | } |
| 1093 | 1169 | } |
| 1094 | 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 | + |
| 1095 | 1211 | /// A C string literal body: printable ASCII as is, everything else (and |
| 1096 | 1212 | /// `"`, `\`, `?`) as three-digit octal escapes. |
| 1097 | 1213 | fn c_escape(s: &str) -> String { |