| @@ -0,0 +1,1499 @@ |
| 1 | +//! `louise repl`: one bounded, transactional synthetic-module session. |
| 2 | +//! |
| 3 | +//! Expression result extraction is deliberately not wired before B1's reviewed |
| 4 | +//! `run_value_map` contract. There is no raw-`Val` or alternate display path. |
| 5 | + |
| 6 | +use std::collections::HashSet; |
| 7 | +use std::io::{self, BufRead, IsTerminal, Read, Write}; |
| 8 | +use std::path::{Path, PathBuf}; |
| 9 | +use std::process::ExitCode; |
| 10 | + |
| 11 | +use louise_db::{Analysis, Db}; |
| 12 | +use louise_diag::Diagnostic; |
| 13 | +use louise_span::{SourceDb, SourceFile}; |
| 14 | +use louise_syntax::{Fragment, FragmentKind, FragmentStatus}; |
| 15 | +use louise_types::{FnParam, Printer, Ty}; |
| 16 | + |
| 17 | +const MODULE: &str = "+repl"; |
| 18 | +const DISPLAY_PATH: &str = "<repl>"; |
| 19 | + |
| 20 | +/// Finite source and rendering budgets (ADR 0083). Execution budgets join these |
| 21 | +/// when B1's ordinary mapped runner is integrated. |
| 22 | +#[derive(Clone, Copy, Debug)] |
| 23 | +pub(crate) struct Limits { |
| 24 | + line_bytes: usize, |
| 25 | + pending_bytes: usize, |
| 26 | + load_bytes: usize, |
| 27 | + session_bytes: usize, |
| 28 | + diagnostic_bytes: usize, |
| 29 | + type_bytes: usize, |
| 30 | +} |
| 31 | + |
| 32 | +impl Default for Limits { |
| 33 | + fn default() -> Self { |
| 34 | + Limits { |
| 35 | + line_bytes: 16 << 10, |
| 36 | + pending_bytes: 64 << 10, |
| 37 | + load_bytes: 256 << 10, |
| 38 | + session_bytes: 1 << 20, |
| 39 | + diagnostic_bytes: 64 << 10, |
| 40 | + type_bytes: 64 << 10, |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +pub(crate) fn repl() -> ExitCode { |
| 46 | + let cwd = match std::env::current_dir() { |
| 47 | + Ok(cwd) => cwd, |
| 48 | + Err(err) => { |
| 49 | + eprintln!("error: repl: cannot find the current directory: {err}"); |
| 50 | + return ExitCode::FAILURE; |
| 51 | + } |
| 52 | + }; |
| 53 | + let stdin = io::stdin(); |
| 54 | + let stdout = io::stdout(); |
| 55 | + let stderr = io::stderr(); |
| 56 | + let interactive = stdin.is_terminal() && stdout.is_terminal(); |
| 57 | + let color = interactive && stderr.is_terminal(); |
| 58 | + let mut input = stdin.lock(); |
| 59 | + let mut out = stdout.lock(); |
| 60 | + let mut err = stderr.lock(); |
| 61 | + match run_io( |
| 62 | + &mut input, |
| 63 | + &mut out, |
| 64 | + &mut err, |
| 65 | + interactive, |
| 66 | + color, |
| 67 | + &cwd, |
| 68 | + Limits::default(), |
| 69 | + ) { |
| 70 | + Ok(code) => code, |
| 71 | + Err(error) => { |
| 72 | + let _ = writeln!(err, "error: repl: {error}"); |
| 73 | + ExitCode::FAILURE |
| 74 | + } |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 79 | +enum Mode { |
| 80 | + Automatic, |
| 81 | + Type, |
| 82 | +} |
| 83 | + |
| 84 | +enum Outcome { |
| 85 | + Empty, |
| 86 | + Committed, |
| 87 | + Type(String), |
| 88 | + Prepared(PreparedExpression), |
| 89 | + Rejected, |
| 90 | +} |
| 91 | + |
| 92 | +/// Core prepared for the one ordinary B1 mapped run. It contains no runtime |
| 93 | +/// state and is consumed immediately by the front end, never put back in the |
| 94 | +/// source session. |
| 95 | +struct PreparedExpression { |
| 96 | + program: louise_core::ir::Program, |
| 97 | + entry: louise_core::ir::FnId, |
| 98 | +} |
| 99 | + |
| 100 | +struct GeneratedNames { |
| 101 | + entry: String, |
| 102 | + prelude: String, |
| 103 | +} |
| 104 | + |
| 105 | +struct Session { |
| 106 | + db: Db, |
| 107 | + file: louise_span::FileId, |
| 108 | + committed: String, |
| 109 | + next_wrapper: usize, |
| 110 | + load_base: PathBuf, |
| 111 | +} |
| 112 | + |
| 113 | +impl Session { |
| 114 | + fn new(load_base: &Path) -> Session { |
| 115 | + let mut db = Db::new(); |
| 116 | + db.without_tests(); |
| 117 | + let file = db.add_module(MODULE, DISPLAY_PATH, String::new()); |
| 118 | + Session { |
| 119 | + db, |
| 120 | + file, |
| 121 | + committed: String::new(), |
| 122 | + next_wrapper: 0, |
| 123 | + load_base: load_base.to_path_buf(), |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + fn reset(&mut self) { |
| 128 | + self.committed.clear(); |
| 129 | + self.next_wrapper = 0; |
| 130 | + // Keep the identity so diagnostic bookkeeping and future snapshots can |
| 131 | + // always name the same synthetic file; all candidate artifacts are |
| 132 | + // owned by individual submissions and have already been dropped. |
| 133 | + self.db.set_text(self.file, String::new()); |
| 134 | + } |
| 135 | + |
| 136 | + fn submit( |
| 137 | + &mut self, |
| 138 | + fragment: &Fragment, |
| 139 | + mode: Mode, |
| 140 | + err: &mut dyn Write, |
| 141 | + color: bool, |
| 142 | + limits: Limits, |
| 143 | + ) -> io::Result<Outcome> { |
| 144 | + if fragment.kind() == FragmentKind::Empty { |
| 145 | + return Ok(Outcome::Empty); |
| 146 | + } |
| 147 | + if fragment.status() != FragmentStatus::Complete { |
| 148 | + return self.syntax_failure(fragment, err, limits); |
| 149 | + } |
| 150 | + match (fragment.kind(), mode) { |
| 151 | + (FragmentKind::Declaration, Mode::Automatic) => { |
| 152 | + self.commit_source(fragment.syntax().to_string(), err, color, limits) |
| 153 | + } |
| 154 | + (FragmentKind::Expression, Mode::Automatic) => { |
| 155 | + self.expression(fragment.syntax().to_string(), err, color, limits) |
| 156 | + } |
| 157 | + (FragmentKind::Expression, Mode::Type) => self.type_query(fragment, err, color, limits), |
| 158 | + // `Mode::Type` always uses `parse_expression_fragment`. |
| 159 | + (FragmentKind::Declaration, Mode::Type) | (FragmentKind::Empty, _) => self |
| 160 | + .error(err, "internal command/expression classification mismatch") |
| 161 | + .map(|()| Outcome::Rejected), |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + fn syntax_failure( |
| 166 | + &mut self, |
| 167 | + fragment: &Fragment, |
| 168 | + err: &mut dyn Write, |
| 169 | + limits: Limits, |
| 170 | + ) -> io::Result<Outcome> { |
| 171 | + let text = fragment.syntax().to_string(); |
| 172 | + let mut sources = SourceDb::default(); |
| 173 | + let file = sources.add(SourceFile::new(DISPLAY_PATH, text)); |
| 174 | + let diagnostics = fragment.diagnostics(file); |
| 175 | + // Incomplete input is normally held by `run_io`; this path is its |
| 176 | + // definite-invalid submission and the direct unit-test seam. |
| 177 | + if diagnostics.is_empty() { |
| 178 | + self.error( |
| 179 | + err, |
| 180 | + "incomplete input; continue the fragment or reset it with :reset", |
| 181 | + )?; |
| 182 | + } else { |
| 183 | + render_diagnostics(&sources, &diagnostics, false, err, limits.diagnostic_bytes)?; |
| 184 | + } |
| 185 | + Ok(Outcome::Rejected) |
| 186 | + } |
| 187 | + |
| 188 | + fn commit_source( |
| 189 | + &mut self, |
| 190 | + source: String, |
| 191 | + err: &mut dyn Write, |
| 192 | + color: bool, |
| 193 | + limits: Limits, |
| 194 | + ) -> io::Result<Outcome> { |
| 195 | + let Some(added) = source.len().checked_add(2) else { |
| 196 | + return self.rejected_limit(err, "declaration source is too large"); |
| 197 | + }; |
| 198 | + let Some(size) = self.committed.len().checked_add(added) else { |
| 199 | + return self.rejected_limit(err, "declaration source is too large"); |
| 200 | + }; |
| 201 | + if size > limits.session_bytes { |
| 202 | + return self.rejected_limit( |
| 203 | + err, |
| 204 | + "committed source exceeds the session limit; use :reset or start a new REPL", |
| 205 | + ); |
| 206 | + } |
| 207 | + let previous_len = self.committed.len(); |
| 208 | + let candidate = append_source(&self.committed, &source); |
| 209 | + self.db.set_text(self.file, candidate.clone()); |
| 210 | + let analysis = self.db.analyze(); |
| 211 | + let mut diagnostics = self.candidate_diagnostics(&analysis, previous_len); |
| 212 | + if !diagnostics.iter().any(Diagnostic::is_error) { |
| 213 | + let fip = louise_db::fip_diagnostics(&analysis); |
| 214 | + diagnostics.extend(self.diagnostics_after(fip, previous_len)); |
| 215 | + } |
| 216 | + if diagnostics.iter().any(Diagnostic::is_error) { |
| 217 | + return self.rollback(diagnostics, err, color, limits); |
| 218 | + } |
| 219 | + render_diagnostics( |
| 220 | + self.db.sources(), |
| 221 | + &diagnostics, |
| 222 | + color, |
| 223 | + err, |
| 224 | + limits.diagnostic_bytes, |
| 225 | + )?; |
| 226 | + self.committed = candidate; |
| 227 | + Ok(Outcome::Committed) |
| 228 | + } |
| 229 | + |
| 230 | + fn expression( |
| 231 | + &mut self, |
| 232 | + expression: String, |
| 233 | + err: &mut dyn Write, |
| 234 | + color: bool, |
| 235 | + limits: Limits, |
| 236 | + ) -> io::Result<Outcome> { |
| 237 | + let names = self.generated_names(); |
| 238 | + // Qualify the actual prelude method so a session `debug` or imported |
| 239 | + // `debug` cannot impersonate `Debug`. The generated zero-argument |
| 240 | + // lambda is HIR's `Boundary::Refuse("a lambda")`: function-level |
| 241 | + // `return` gets E0119 instead of bypassing `debug` with a raw String. |
| 242 | + let body = guarded_expression(&expression); |
| 243 | + let source = format!( |
| 244 | + "import std/prelude as {prelude}\nfn {entry} ::\n{{\n {prelude}.debug ({body})\n}}\n", |
| 245 | + prelude = names.prelude, |
| 246 | + entry = names.entry, |
| 247 | + ); |
| 248 | + let previous_len = self.committed.len(); |
| 249 | + let candidate = append_source(&self.committed, &source); |
| 250 | + self.db.set_text(self.file, candidate); |
| 251 | + let analysis = self.db.analyze(); |
| 252 | + let diagnostics = self.candidate_diagnostics(&analysis, previous_len); |
| 253 | + if diagnostics.iter().any(Diagnostic::is_error) { |
| 254 | + return self.rollback(diagnostics, err, color, limits); |
| 255 | + } |
| 256 | + let Some(def) = wrapper_def(&analysis, &names.entry) else { |
| 257 | + return self.internal_rollback(err, "generated expression wrapper is missing"); |
| 258 | + }; |
| 259 | + let mut program = louise_core::lower::lower(&analysis.hir, &analysis.typeck); |
| 260 | + let entry = match louise_core::runnable(&analysis.hir, &analysis.typeck, &program, def) { |
| 261 | + Ok(entry) => entry, |
| 262 | + Err(message) => { |
| 263 | + let written = self.error(err, &message); |
| 264 | + self.restore(); |
| 265 | + written?; |
| 266 | + return Ok(Outcome::Rejected); |
| 267 | + } |
| 268 | + }; |
| 269 | + // Match interpreted `run`: the same optimized Core goes to B1, whose |
| 270 | + // ordinary `run_value_map` will consume this immediately after the |
| 271 | + // source transaction has restored the committed text. |
| 272 | + louise_core::opt::run_in(&mut program, &[entry]); |
| 273 | + let rendered = render_diagnostics( |
| 274 | + self.db.sources(), |
| 275 | + &diagnostics, |
| 276 | + color, |
| 277 | + err, |
| 278 | + limits.diagnostic_bytes, |
| 279 | + ); |
| 280 | + self.restore(); |
| 281 | + rendered?; |
| 282 | + Ok(Outcome::Prepared(PreparedExpression { program, entry })) |
| 283 | + } |
| 284 | + |
| 285 | + fn type_query( |
| 286 | + &mut self, |
| 287 | + fragment: &Fragment, |
| 288 | + err: &mut dyn Write, |
| 289 | + color: bool, |
| 290 | + limits: Limits, |
| 291 | + ) -> io::Result<Outcome> { |
| 292 | + let expression = fragment.syntax().to_string(); |
| 293 | + let names = self.generated_names(); |
| 294 | + // Type queries use the same early-return boundary, but no import or |
| 295 | + // `Debug` requirement. The generated lambda is never executed here. |
| 296 | + let body = guarded_expression(&expression); |
| 297 | + let source = format!("fn {entry} ::\n{{\n ({body})\n}}\n", entry = names.entry,); |
| 298 | + let previous_len = self.committed.len(); |
| 299 | + let candidate = append_source(&self.committed, &source); |
| 300 | + self.db.set_text(self.file, candidate); |
| 301 | + let analysis = self.db.analyze(); |
| 302 | + let diagnostics = self.candidate_diagnostics(&analysis, previous_len); |
| 303 | + if diagnostics.iter().any(Diagnostic::is_error) { |
| 304 | + return self.rollback(diagnostics, err, color, limits); |
| 305 | + } |
| 306 | + let printed = match bare_item_def(fragment, &analysis) { |
| 307 | + Some(def) => render_item_type(&analysis, def, limits.type_bytes), |
| 308 | + None => render_wrapper_type(&analysis, &names.entry, limits.type_bytes), |
| 309 | + }; |
| 310 | + let printed = match printed { |
| 311 | + Ok(printed) => printed, |
| 312 | + Err(message) => return self.internal_rollback(err, &message), |
| 313 | + }; |
| 314 | + let rendered = render_diagnostics( |
| 315 | + self.db.sources(), |
| 316 | + &diagnostics, |
| 317 | + color, |
| 318 | + err, |
| 319 | + limits.diagnostic_bytes, |
| 320 | + ); |
| 321 | + self.restore(); |
| 322 | + rendered?; |
| 323 | + Ok(Outcome::Type(printed)) |
| 324 | + } |
| 325 | + |
| 326 | + fn candidate_diagnostics(&self, analysis: &Analysis, previous_len: usize) -> Vec<Diagnostic> { |
| 327 | + self.diagnostics_after(analysis.diagnostics.clone(), previous_len) |
| 328 | + } |
| 329 | + |
| 330 | + fn diagnostics_after( |
| 331 | + &self, |
| 332 | + diagnostics: Vec<Diagnostic>, |
| 333 | + previous_len: usize, |
| 334 | + ) -> Vec<Diagnostic> { |
| 335 | + diagnostics |
| 336 | + .into_iter() |
| 337 | + .filter(|diagnostic| { |
| 338 | + diagnostic.primary.span.file == self.file |
| 339 | + && usize::from(diagnostic.primary.span.range.start()) >= previous_len |
| 340 | + }) |
| 341 | + .collect() |
| 342 | + } |
| 343 | + |
| 344 | + fn rollback( |
| 345 | + &mut self, |
| 346 | + diagnostics: Vec<Diagnostic>, |
| 347 | + err: &mut dyn Write, |
| 348 | + color: bool, |
| 349 | + limits: Limits, |
| 350 | + ) -> io::Result<Outcome> { |
| 351 | + let rendered = render_diagnostics( |
| 352 | + self.db.sources(), |
| 353 | + &diagnostics, |
| 354 | + color, |
| 355 | + err, |
| 356 | + limits.diagnostic_bytes, |
| 357 | + ); |
| 358 | + self.restore(); |
| 359 | + rendered?; |
| 360 | + Ok(Outcome::Rejected) |
| 361 | + } |
| 362 | + |
| 363 | + fn internal_rollback(&mut self, err: &mut dyn Write, message: &str) -> io::Result<Outcome> { |
| 364 | + let written = self.error(err, message); |
| 365 | + self.restore(); |
| 366 | + written?; |
| 367 | + Ok(Outcome::Rejected) |
| 368 | + } |
| 369 | + |
| 370 | + fn restore(&mut self) { |
| 371 | + self.db.set_text(self.file, self.committed.clone()); |
| 372 | + } |
| 373 | + |
| 374 | + fn rejected_limit(&mut self, err: &mut dyn Write, message: &str) -> io::Result<Outcome> { |
| 375 | + self.error(err, message).map(|()| Outcome::Rejected) |
| 376 | + } |
| 377 | + |
| 378 | + fn error(&self, err: &mut dyn Write, message: &str) -> io::Result<()> { |
| 379 | + writeln!(err, "error: repl: {message}") |
| 380 | + } |
| 381 | + |
| 382 | + fn generated_names(&mut self) -> GeneratedNames { |
| 383 | + // Use resolved visible namespaces, not just function syntax: generated |
| 384 | + // entries and the prelude alias must also avoid constructors, named |
| 385 | + // imports and module aliases. The derived set is discarded after each |
| 386 | + // use and committed source remains the session's only persistent code. |
| 387 | + let analysis = self.db.analyze(); |
| 388 | + let mut used = HashSet::new(); |
| 389 | + if let Some(module) = analysis.hir.module_by_path(MODULE) { |
| 390 | + add_scope_names(&mut used, &analysis.hir.scopes[module.index()]); |
| 391 | + if let Some(prelude) = analysis.hir.prelude { |
| 392 | + add_scope_names(&mut used, &analysis.hir.exports[prelude.index()]); |
| 393 | + } |
| 394 | + } |
| 395 | + loop { |
| 396 | + let entry = format!("__louise_repl_{}", self.next_wrapper); |
| 397 | + let prelude = format!("__louise_repl_prelude_{}", self.next_wrapper); |
| 398 | + self.next_wrapper = self |
| 399 | + .next_wrapper |
| 400 | + .checked_add(1) |
| 401 | + .expect("REPL wrapper counter exhausted"); |
| 402 | + if !used.contains(&entry) && !used.contains(&prelude) { |
| 403 | + return GeneratedNames { entry, prelude }; |
| 404 | + } |
| 405 | + } |
| 406 | + } |
| 407 | + |
| 408 | + fn load( |
| 409 | + &mut self, |
| 410 | + argument: &str, |
| 411 | + err: &mut dyn Write, |
| 412 | + color: bool, |
| 413 | + limits: Limits, |
| 414 | + ) -> io::Result<Outcome> { |
| 415 | + match self.read_load(argument, limits) { |
| 416 | + Ok(source) => self.commit_source(source, err, color, limits), |
| 417 | + Err(message) => self.rejected_limit(err, &message), |
| 418 | + } |
| 419 | + } |
| 420 | + |
| 421 | + fn read_load(&self, argument: &str, limits: Limits) -> Result<String, String> { |
| 422 | + if argument.is_empty() { |
| 423 | + return Err("usage: :load FILE.lse".into()); |
| 424 | + } |
| 425 | + let supplied = Path::new(argument); |
| 426 | + if supplied |
| 427 | + .extension() |
| 428 | + .is_none_or(|extension| extension != "lse") |
| 429 | + { |
| 430 | + return Err(format!("{argument}: :load expects one .lse source file")); |
| 431 | + } |
| 432 | + let path = if supplied.is_absolute() { |
| 433 | + supplied.to_path_buf() |
| 434 | + } else { |
| 435 | + self.load_base.join(supplied) |
| 436 | + }; |
| 437 | + stable_load_bytes(&path, || read_load_snapshot(&path, limits)) |
| 438 | + } |
| 439 | +} |
| 440 | + |
| 441 | +fn add_scope_names(names: &mut HashSet<String>, scope: &louise_hir::Scope) { |
| 442 | + names.extend(scope.values.keys().cloned()); |
| 443 | + names.extend(scope.types.keys().cloned()); |
| 444 | + names.extend(scope.modules.keys().cloned()); |
| 445 | +} |
| 446 | + |
| 447 | +fn guarded_expression(expression: &str) -> String { |
| 448 | + format!("(fn {{\n{expression}\n}}) ()") |
| 449 | +} |
| 450 | + |
| 451 | +fn wrapper_def(analysis: &Analysis, name: &str) -> Option<louise_hir::DefId> { |
| 452 | + let module = analysis.hir.module_by_path(MODULE)?; |
| 453 | + analysis.hir.modules[module] |
| 454 | + .items |
| 455 | + .iter() |
| 456 | + .copied() |
| 457 | + .find(|def| analysis.hir.def(*def).name == name) |
| 458 | +} |
| 459 | + |
| 460 | +/// Resolve only a syntactically bare value item through the same synthetic |
| 461 | +/// module HIR that typechecked it. Every other expression keeps its transient |
| 462 | +/// inferred type; calls, fields and lambdas are not disguised as declarations. |
| 463 | +fn bare_item_def(fragment: &Fragment, analysis: &Analysis) -> Option<louise_hir::DefId> { |
| 464 | + let expr = fragment |
| 465 | + .syntax() |
| 466 | + .children() |
| 467 | + .find_map(<louise_syntax::ast::Expr as louise_syntax::ast::AstNode>::cast)?; |
| 468 | + let module = analysis.hir.module_by_path(MODULE)?; |
| 469 | + bare_ast_item_def(expr, module, &analysis.hir) |
| 470 | +} |
| 471 | + |
| 472 | +fn bare_ast_item_def( |
| 473 | + expr: louise_syntax::ast::Expr, |
| 474 | + module: louise_hir::ModuleId, |
| 475 | + hir: &louise_hir::Hir, |
| 476 | +) -> Option<louise_hir::DefId> { |
| 477 | + match expr { |
| 478 | + louise_syntax::ast::Expr::ParenExpr(paren) => bare_ast_item_def(paren.expr()?, module, hir), |
| 479 | + louise_syntax::ast::Expr::PathExpr(path) => { |
| 480 | + hir.lookup_value(module, &path.name_ref()?.text()) |
| 481 | + } |
| 482 | + louise_syntax::ast::Expr::FieldExpr(field) => { |
| 483 | + let louise_syntax::ast::Expr::PathExpr(base) = field.base()? else { |
| 484 | + return None; |
| 485 | + }; |
| 486 | + // The generated query lambda has no parameters/bindings, so an |
| 487 | + // item at this root cannot be shadowed by an expression local. |
| 488 | + let imported = hir.lookup_module(module, &base.name_ref()?.text())?; |
| 489 | + hir.exports[imported.index()] |
| 490 | + .values |
| 491 | + .get(&field.field()?.text()) |
| 492 | + .copied() |
| 493 | + } |
| 494 | + _ => None, |
| 495 | + } |
| 496 | +} |
| 497 | + |
| 498 | +fn render_item_type( |
| 499 | + analysis: &Analysis, |
| 500 | + def: louise_hir::DefId, |
| 501 | + limit: usize, |
| 502 | +) -> Result<String, String> { |
| 503 | + let scheme = analysis |
| 504 | + .typeck |
| 505 | + .schemes |
| 506 | + .get(&def) |
| 507 | + .ok_or_else(|| "selected value item has no declared or inferred scheme".to_owned())?; |
| 508 | + print_bounded_scheme(&analysis.hir, scheme, limit) |
| 509 | +} |
| 510 | + |
| 511 | +fn render_wrapper_type(analysis: &Analysis, name: &str, limit: usize) -> Result<String, String> { |
| 512 | + let def = wrapper_def(analysis, name) |
| 513 | + .ok_or_else(|| "generated type wrapper is missing".to_owned())?; |
| 514 | + let scheme = analysis |
| 515 | + .typeck |
| 516 | + .schemes |
| 517 | + .get(&def) |
| 518 | + .ok_or_else(|| "generated type wrapper has no inferred scheme".to_owned())?; |
| 519 | + let Ty::Fn(params, ..) = &scheme.ty else { |
| 520 | + return Err("generated type wrapper is not a function".into()); |
| 521 | + }; |
| 522 | + if !FnParam::unit_only(params) { |
| 523 | + return Err("generated type wrapper has no unit entry".into()); |
| 524 | + } |
| 525 | + let printed = print_bounded_scheme(&analysis.hir, scheme, limit)?; |
| 526 | + // This prefix is produced by Printer itself. Removing it and nothing else |
| 527 | + // preserves the inferred row, constraints, markers, equalities and the |
| 528 | + // expression's function type. |
| 529 | + printed |
| 530 | + .strip_prefix("fn() -> ") |
| 531 | + .map(str::to_owned) |
| 532 | + .ok_or_else(|| "generated type wrapper has no unit-entry scheme".into()) |
| 533 | +} |
| 534 | + |
| 535 | +fn print_bounded_scheme( |
| 536 | + hir: &louise_hir::Hir, |
| 537 | + scheme: &louise_types::Scheme, |
| 538 | + limit: usize, |
| 539 | +) -> Result<String, String> { |
| 540 | + // Printer materializes a String. Use a conservative structural preflight |
| 541 | + // before that allocation, then verify exact bytes before returning them; |
| 542 | + // no partial type ever reaches the output stream. Type-checking itself is |
| 543 | + // still bounded by source/parser limits, not presented as limited by this. |
| 544 | + if !type_output_is_bounded(hir, scheme, limit) { |
| 545 | + return Err(format!( |
| 546 | + "inferred type exceeds the REPL type-result limit of {limit} bytes or its structural bound" |
| 547 | + )); |
| 548 | + } |
| 549 | + let printed = Printer { |
| 550 | + hir, |
| 551 | + ctx: None, |
| 552 | + gen_names: &[], |
| 553 | + rigid_names: &[], |
| 554 | + } |
| 555 | + .scheme(scheme); |
| 556 | + if printed.len() > limit { |
| 557 | + return Err(format!( |
| 558 | + "inferred type exceeds the REPL type-result limit of {limit} bytes" |
| 559 | + )); |
| 560 | + } |
| 561 | + Ok(printed) |
| 562 | +} |
| 563 | + |
| 564 | +const MAX_TYPE_NODES: usize = 4096; |
| 565 | + |
| 566 | +/// A conservative upper bound on `Printer::scheme` before it builds a String. |
| 567 | +/// Per-node/per-edge allowances deliberately overcount punctuation, arrows, |
| 568 | +/// rows and separators. Equalities are walked twice because associated-type |
| 569 | +/// bindings and newly grouped constraints may duplicate their arguments. |
| 570 | +fn type_output_is_bounded( |
| 571 | + hir: &louise_hir::Hir, |
| 572 | + scheme: &louise_types::Scheme, |
| 573 | + limit: usize, |
| 574 | +) -> bool { |
| 575 | + let mut total = 0; |
| 576 | + let mut work = vec![&scheme.ty]; |
| 577 | + for constraint in scheme.all_constraints() { |
| 578 | + if !account_type_bytes( |
| 579 | + &mut total, |
| 580 | + hir.def(constraint.trait_).name.len() + 32, |
| 581 | + limit, |
| 582 | + ) { |
| 583 | + return false; |
| 584 | + } |
| 585 | + for arg in &constraint.args { |
| 586 | + if !queue_type(&mut work, arg) { |
| 587 | + return false; |
| 588 | + } |
| 589 | + } |
| 590 | + } |
| 591 | + for equality in &scheme.equalities { |
| 592 | + if !account_type_bytes(&mut total, 32, limit) { |
| 593 | + return false; |
| 594 | + } |
| 595 | + if let Ty::Proj(assoc, _) = &equality.lhs |
| 596 | + && let louise_hir::DefKind::AssocType(assoc_def) = &hir.def(*assoc).kind |
| 597 | + && !account_type_bytes(&mut total, hir.def(assoc_def.owner).name.len(), limit) |
| 598 | + { |
| 599 | + return false; |
| 600 | + } |
| 601 | + for ty in [&equality.lhs, &equality.rhs, &equality.lhs] { |
| 602 | + if !queue_type(&mut work, ty) { |
| 603 | + return false; |
| 604 | + } |
| 605 | + } |
| 606 | + for binder in &equality.binders { |
| 607 | + if !queue_type(&mut work, binder) { |
| 608 | + return false; |
| 609 | + } |
| 610 | + } |
| 611 | + } |
| 612 | + |
| 613 | + let mut visited = 0; |
| 614 | + while let Some(ty) = work.pop() { |
| 615 | + visited += 1; |
| 616 | + if visited > MAX_TYPE_NODES || !account_type_bytes(&mut total, 16, limit) { |
| 617 | + return false; |
| 618 | + } |
| 619 | + macro_rules! push { |
| 620 | + ($child:expr) => { |
| 621 | + if work.len() >= MAX_TYPE_NODES || !account_type_bytes(&mut total, 8, limit) { |
| 622 | + return false; |
| 623 | + } |
| 624 | + work.push($child); |
| 625 | + }; |
| 626 | + } |
| 627 | + match ty { |
| 628 | + Ty::Con(def, args) | Ty::Proj(def, args) => { |
| 629 | + if !account_type_bytes(&mut total, hir.def(*def).name.len(), limit) { |
| 630 | + return false; |
| 631 | + } |
| 632 | + for arg in args { |
| 633 | + push!(arg); |
| 634 | + } |
| 635 | + } |
| 636 | + Ty::App(head, args) => { |
| 637 | + push!(head); |
| 638 | + for arg in args { |
| 639 | + push!(arg); |
| 640 | + } |
| 641 | + } |
| 642 | + Ty::Tuple(types) => { |
| 643 | + for ty in types { |
| 644 | + push!(ty); |
| 645 | + } |
| 646 | + } |
| 647 | + Ty::Fn(params, result, effects, captures) => { |
| 648 | + for param in params { |
| 649 | + if let Some(label) = ¶m.label |
| 650 | + && !account_type_bytes(&mut total, label.len(), limit) |
| 651 | + { |
| 652 | + return false; |
| 653 | + } |
| 654 | + push!(¶m.ty); |
| 655 | + } |
| 656 | + push!(result); |
| 657 | + push!(effects); |
| 658 | + push!(captures); |
| 659 | + } |
| 660 | + Ty::RowExtend(label, rest) => { |
| 661 | + push!(label); |
| 662 | + push!(rest); |
| 663 | + } |
| 664 | + Ty::Rigid(_) => { |
| 665 | + // `Printer::scheme` has no stored rigid-name table here; it |
| 666 | + // prints '?', already covered by the per-node allowance. |
| 667 | + } |
| 668 | + Ty::Gen(index) => { |
| 669 | + if let Some(name) = scheme.vars.get(*index as usize) |
| 670 | + && !account_type_bytes(&mut total, name.len(), limit) |
| 671 | + { |
| 672 | + return false; |
| 673 | + } |
| 674 | + } |
| 675 | + Ty::Var(_) | Ty::Bound(_) | Ty::RowEmpty | Ty::RowEvidence | Ty::Error => {} |
| 676 | + } |
| 677 | + } |
| 678 | + true |
| 679 | +} |
| 680 | + |
| 681 | +fn queue_type<'a>(work: &mut Vec<&'a Ty>, ty: &'a Ty) -> bool { |
| 682 | + if work.len() >= MAX_TYPE_NODES { |
| 683 | + return false; |
| 684 | + } |
| 685 | + work.push(ty); |
| 686 | + true |
| 687 | +} |
| 688 | + |
| 689 | +fn account_type_bytes(total: &mut usize, added: usize, limit: usize) -> bool { |
| 690 | + let Some(next) = total.checked_add(added) else { |
| 691 | + return false; |
| 692 | + }; |
| 693 | + if next > limit { |
| 694 | + return false; |
| 695 | + } |
| 696 | + *total = next; |
| 697 | + true |
| 698 | +} |
| 699 | + |
| 700 | +fn stable_load_bytes( |
| 701 | + path: &Path, |
| 702 | + mut read: impl FnMut() -> Result<Vec<u8>, String>, |
| 703 | +) -> Result<String, String> { |
| 704 | + // Two independent, bounded snapshots avoid assuming that `modified()` is |
| 705 | + // available or has enough resolution. This is a host-side load operation, |
| 706 | + // not a persistent lock on the file or a guarantee against all racing FSes. |
| 707 | + let first = read()?; |
| 708 | + let second = read()?; |
| 709 | + if first != second { |
| 710 | + return Err(format!( |
| 711 | + "{} changed between bounded reads; nothing was loaded", |
| 712 | + path.display() |
| 713 | + )); |
| 714 | + } |
| 715 | + String::from_utf8(first) |
| 716 | + .map_err(|_| format!("{} is not valid UTF-8; nothing was loaded", path.display())) |
| 717 | +} |
| 718 | + |
| 719 | +fn read_load_snapshot(path: &Path, limits: Limits) -> Result<Vec<u8>, String> { |
| 720 | + let file = std::fs::File::open(path) |
| 721 | + .map_err(|error| format!("cannot read {}: {error}", path.display()))?; |
| 722 | + let mut bytes = Vec::new(); |
| 723 | + file.take(limits.load_bytes as u64 + 1) |
| 724 | + .read_to_end(&mut bytes) |
| 725 | + .map_err(|error| format!("cannot read {}: {error}", path.display()))?; |
| 726 | + if bytes.len() > limits.load_bytes { |
| 727 | + return Err(format!( |
| 728 | + "{} exceeds the :load limit of {} bytes; nothing was loaded", |
| 729 | + path.display(), |
| 730 | + limits.load_bytes |
| 731 | + )); |
| 732 | + } |
| 733 | + Ok(bytes) |
| 734 | +} |
| 735 | + |
| 736 | +fn append_source(committed: &str, source: &str) -> String { |
| 737 | + let mut candidate = String::with_capacity(committed.len() + source.len() + 2); |
| 738 | + candidate.push_str(committed); |
| 739 | + if !committed.is_empty() && !committed.ends_with('\n') { |
| 740 | + candidate.push('\n'); |
| 741 | + } |
| 742 | + candidate.push_str(source); |
| 743 | + if !candidate.ends_with('\n') { |
| 744 | + candidate.push('\n'); |
| 745 | + } |
| 746 | + candidate |
| 747 | +} |
| 748 | + |
| 749 | +const HELP: &str = "Louise interpreter REPL\n\ |
| 750 | + :type EXPR print an expression's inferred type, without running it\n\ |
| 751 | + :load FILE add declarations/imports from one .lse file (does not run main)\n\ |
| 752 | + :reset discard all declarations/imports in this session\n\ |
| 753 | + :help show this help\n\ |
| 754 | +Declarations and imports persist. Values, actors and runtime state do not.\n\ |
| 755 | +Expression evaluation is unavailable until the B1 value-mapping API is integrated.\n"; |
| 756 | + |
| 757 | +fn run_io( |
| 758 | + input: &mut dyn BufRead, |
| 759 | + out: &mut dyn Write, |
| 760 | + err: &mut dyn Write, |
| 761 | + interactive: bool, |
| 762 | + color: bool, |
| 763 | + cwd: &Path, |
| 764 | + limits: Limits, |
| 765 | +) -> io::Result<ExitCode> { |
| 766 | + let mut session = Session::new(cwd); |
| 767 | + let mut pending = String::new(); |
| 768 | + let mut mode = Mode::Automatic; |
| 769 | + loop { |
| 770 | + if interactive { |
| 771 | + if pending.is_empty() { |
| 772 | + write!(out, "louise> ")?; |
| 773 | + } else { |
| 774 | + write!(out, "...> ")?; |
| 775 | + } |
| 776 | + out.flush()?; |
| 777 | + } |
| 778 | + let line = match read_bounded_line(input, limits.line_bytes)? { |
| 779 | + InputLine::Eof if pending.is_empty() => return Ok(ExitCode::SUCCESS), |
| 780 | + InputLine::Eof => { |
| 781 | + writeln!(err, "error: repl: input ended in an incomplete fragment")?; |
| 782 | + return Ok(ExitCode::FAILURE); |
| 783 | + } |
| 784 | + InputLine::TooLong => { |
| 785 | + pending.clear(); |
| 786 | + writeln!( |
| 787 | + err, |
| 788 | + "error: repl: input line exceeds {} bytes; the line and pending fragment were discarded", |
| 789 | + limits.line_bytes |
| 790 | + )?; |
| 791 | + continue; |
| 792 | + } |
| 793 | + InputLine::InvalidUtf8 => { |
| 794 | + pending.clear(); |
| 795 | + writeln!( |
| 796 | + err, |
| 797 | + "error: repl: input is not valid UTF-8; the line was discarded" |
| 798 | + )?; |
| 799 | + continue; |
| 800 | + } |
| 801 | + InputLine::Text(line) => line, |
| 802 | + }; |
| 803 | + |
| 804 | + if pending.is_empty() { |
| 805 | + let command = line.trim(); |
| 806 | + let Some(command) = command.strip_prefix(':') else { |
| 807 | + pending = line; |
| 808 | + mode = Mode::Automatic; |
| 809 | + return_to_fragment(&mut session, &mut pending, mode, out, err, color, limits)?; |
| 810 | + continue; |
| 811 | + }; |
| 812 | + let (name, rest) = command |
| 813 | + .split_once(char::is_whitespace) |
| 814 | + .map_or((command, ""), |(name, rest)| (name, rest.trim())); |
| 815 | + match name { |
| 816 | + "help" if rest.is_empty() => out.write_all(HELP.as_bytes())?, |
| 817 | + "reset" if rest.is_empty() => session.reset(), |
| 818 | + "load" => { |
| 819 | + session.load(rest, err, color, limits)?; |
| 820 | + } |
| 821 | + "type" if !rest.is_empty() => { |
| 822 | + pending.push_str(rest); |
| 823 | + pending.push('\n'); |
| 824 | + mode = Mode::Type; |
| 825 | + return_to_fragment(&mut session, &mut pending, mode, out, err, color, limits)?; |
| 826 | + } |
| 827 | + "type" => writeln!(err, "error: repl: usage: :type EXPR")?, |
| 828 | + "help" | "reset" => writeln!(err, "error: repl: :{name} takes no arguments")?, |
| 829 | + _ => writeln!(err, "error: repl: unknown command :{name}; use :help")?, |
| 830 | + } |
| 831 | + continue; |
| 832 | + } |
| 833 | + |
| 834 | + if pending.len().saturating_add(line.len()) > limits.pending_bytes { |
| 835 | + pending.clear(); |
| 836 | + writeln!( |
| 837 | + err, |
| 838 | + "error: repl: pending fragment exceeds {} bytes; it was discarded", |
| 839 | + limits.pending_bytes |
| 840 | + )?; |
| 841 | + continue; |
| 842 | + } |
| 843 | + pending.push_str(&line); |
| 844 | + return_to_fragment(&mut session, &mut pending, mode, out, err, color, limits)?; |
| 845 | + } |
| 846 | +} |
| 847 | + |
| 848 | +fn return_to_fragment( |
| 849 | + session: &mut Session, |
| 850 | + pending: &mut String, |
| 851 | + mode: Mode, |
| 852 | + out: &mut dyn Write, |
| 853 | + err: &mut dyn Write, |
| 854 | + color: bool, |
| 855 | + limits: Limits, |
| 856 | +) -> io::Result<()> { |
| 857 | + let fragment = match mode { |
| 858 | + Mode::Automatic => louise_syntax::parse_fragment(pending), |
| 859 | + Mode::Type => louise_syntax::parse_expression_fragment(pending), |
| 860 | + }; |
| 861 | + if pending.len() > limits.pending_bytes { |
| 862 | + pending.clear(); |
| 863 | + writeln!( |
| 864 | + err, |
| 865 | + "error: repl: pending fragment exceeds {} bytes; it was discarded", |
| 866 | + limits.pending_bytes |
| 867 | + )?; |
| 868 | + return Ok(()); |
| 869 | + } |
| 870 | + if fragment.status() == FragmentStatus::Incomplete { |
| 871 | + return Ok(()); |
| 872 | + } |
| 873 | + pending.clear(); |
| 874 | + match session.submit(&fragment, mode, err, color, limits)? { |
| 875 | + Outcome::Empty | Outcome::Committed | Outcome::Rejected => {} |
| 876 | + Outcome::Type(printed) => writeln!(out, "{printed}")?, |
| 877 | + Outcome::Prepared(prepared) => { |
| 878 | + // Drop the prepared Core explicitly: no fallback printer, raw-Val |
| 879 | + // evaluator or second runtime API takes its place before B1. |
| 880 | + let PreparedExpression { program, entry } = prepared; |
| 881 | + drop((program, entry)); |
| 882 | + writeln!( |
| 883 | + err, |
| 884 | + "error: repl: expression evaluation is not wired until B1's run_value_map contract is integrated" |
| 885 | + )?; |
| 886 | + } |
| 887 | + } |
| 888 | + Ok(()) |
| 889 | +} |
| 890 | + |
| 891 | +/// `None`/empty at EOF versus an owned line, with newline retained for source. |
| 892 | +/// Reading beyond the cap allocates nothing: the rest is drained by buffer. |
| 893 | +enum InputLine { |
| 894 | + Eof, |
| 895 | + Text(String), |
| 896 | + TooLong, |
| 897 | + InvalidUtf8, |
| 898 | +} |
| 899 | + |
| 900 | +fn read_bounded_line(input: &mut dyn BufRead, limit: usize) -> io::Result<InputLine> { |
| 901 | + let mut bytes = Vec::new(); |
| 902 | + loop { |
| 903 | + let available = input.fill_buf()?; |
| 904 | + if available.is_empty() { |
| 905 | + if bytes.is_empty() { |
| 906 | + return Ok(InputLine::Eof); |
| 907 | + } |
| 908 | + return decode_line(bytes, false); |
| 909 | + } |
| 910 | + let newline = available.iter().position(|byte| *byte == b'\n'); |
| 911 | + let content_len = newline.unwrap_or(available.len()); |
| 912 | + let consumed = content_len + usize::from(newline.is_some()); |
| 913 | + if bytes.len().saturating_add(content_len) > limit { |
| 914 | + input.consume(consumed); |
| 915 | + if newline.is_none() { |
| 916 | + drain_line(input)?; |
| 917 | + } |
| 918 | + return Ok(InputLine::TooLong); |
| 919 | + } |
| 920 | + bytes.extend_from_slice(&available[..content_len]); |
| 921 | + input.consume(consumed); |
| 922 | + if newline.is_some() { |
| 923 | + return decode_line(bytes, true); |
| 924 | + } |
| 925 | + } |
| 926 | +} |
| 927 | + |
| 928 | +fn decode_line(bytes: Vec<u8>, newline: bool) -> io::Result<InputLine> { |
| 929 | + let Ok(mut line) = String::from_utf8(bytes) else { |
| 930 | + return Ok(InputLine::InvalidUtf8); |
| 931 | + }; |
| 932 | + if newline { |
| 933 | + line.push('\n'); |
| 934 | + } |
| 935 | + Ok(InputLine::Text(line)) |
| 936 | +} |
| 937 | + |
| 938 | +fn drain_line(input: &mut dyn BufRead) -> io::Result<()> { |
| 939 | + loop { |
| 940 | + let available = input.fill_buf()?; |
| 941 | + if available.is_empty() { |
| 942 | + return Ok(()); |
| 943 | + } |
| 944 | + let consumed = available |
| 945 | + .iter() |
| 946 | + .position(|byte| *byte == b'\n') |
| 947 | + .map_or(available.len(), |index| index + 1); |
| 948 | + let complete = available.get(consumed.saturating_sub(1)) == Some(&b'\n'); |
| 949 | + input.consume(consumed); |
| 950 | + if complete { |
| 951 | + return Ok(()); |
| 952 | + } |
| 953 | + } |
| 954 | +} |
| 955 | + |
| 956 | +/// Keep a diagnostic submission bounded even if error recovery produces many |
| 957 | +/// messages. A limit-induced write error is expected; an underlying stream |
| 958 | +/// failure is not. |
| 959 | +struct DiagnosticWriter<'a> { |
| 960 | + out: &'a mut dyn Write, |
| 961 | + remaining: usize, |
| 962 | + truncated: bool, |
| 963 | +} |
| 964 | + |
| 965 | +impl Write for DiagnosticWriter<'_> { |
| 966 | + fn write(&mut self, buffer: &[u8]) -> io::Result<usize> { |
| 967 | + if self.truncated { |
| 968 | + return Err(io::Error::other("diagnostic limit")); |
| 969 | + } |
| 970 | + if buffer.len() > self.remaining { |
| 971 | + let prefix = self.remaining; |
| 972 | + self.out.write_all(&buffer[..prefix])?; |
| 973 | + self.remaining = 0; |
| 974 | + self.truncated = true; |
| 975 | + return Err(io::Error::other("diagnostic limit")); |
| 976 | + } |
| 977 | + self.out.write_all(buffer)?; |
| 978 | + self.remaining -= buffer.len(); |
| 979 | + Ok(buffer.len()) |
| 980 | + } |
| 981 | + |
| 982 | + fn flush(&mut self) -> io::Result<()> { |
| 983 | + self.out.flush() |
| 984 | + } |
| 985 | +} |
| 986 | + |
| 987 | +fn render_diagnostics( |
| 988 | + sources: &SourceDb, |
| 989 | + diagnostics: &[Diagnostic], |
| 990 | + color: bool, |
| 991 | + out: &mut dyn Write, |
| 992 | + limit: usize, |
| 993 | +) -> io::Result<()> { |
| 994 | + if diagnostics.is_empty() { |
| 995 | + return Ok(()); |
| 996 | + } |
| 997 | + let (result, truncated) = { |
| 998 | + let mut limited = DiagnosticWriter { |
| 999 | + out, |
| 1000 | + remaining: limit, |
| 1001 | + truncated: false, |
| 1002 | + }; |
| 1003 | + let result = louise_diag::render(sources, diagnostics, color, &mut limited); |
| 1004 | + (result, limited.truncated) |
| 1005 | + }; |
| 1006 | + if !truncated { |
| 1007 | + result?; |
| 1008 | + } |
| 1009 | + if truncated { |
| 1010 | + writeln!( |
| 1011 | + out, |
| 1012 | + "error: repl: diagnostics exceeded {limit} bytes and were truncated" |
| 1013 | + )?; |
| 1014 | + } |
| 1015 | + Ok(()) |
| 1016 | +} |
| 1017 | + |
| 1018 | +#[cfg(test)] |
| 1019 | +mod tests { |
| 1020 | + use std::sync::Arc; |
| 1021 | + use std::sync::atomic::{AtomicUsize, Ordering}; |
| 1022 | + |
| 1023 | + use super::*; |
| 1024 | + |
| 1025 | + fn small_limits() -> Limits { |
| 1026 | + Limits { |
| 1027 | + line_bytes: 32, |
| 1028 | + pending_bytes: 64, |
| 1029 | + load_bytes: 64, |
| 1030 | + session_bytes: 256, |
| 1031 | + diagnostic_bytes: 256, |
| 1032 | + type_bytes: 128, |
| 1033 | + } |
| 1034 | + } |
| 1035 | + |
| 1036 | + fn submit(session: &mut Session, source: &str, mode: Mode) -> (Outcome, String) { |
| 1037 | + let fragment = match mode { |
| 1038 | + Mode::Automatic => louise_syntax::parse_fragment(source), |
| 1039 | + Mode::Type => louise_syntax::parse_expression_fragment(source), |
| 1040 | + }; |
| 1041 | + let mut err = Vec::new(); |
| 1042 | + let outcome = session |
| 1043 | + .submit(&fragment, mode, &mut err, false, Limits::default()) |
| 1044 | + .unwrap(); |
| 1045 | + (outcome, String::from_utf8(err).unwrap()) |
| 1046 | + } |
| 1047 | + |
| 1048 | + #[test] |
| 1049 | + fn declarations_persist_but_value_wrappers_do_not() { |
| 1050 | + let mut session = Session::new(Path::new(".")); |
| 1051 | + let (outcome, error) = submit( |
| 1052 | + &mut session, |
| 1053 | + "fn twice :: x: Int -> Int {\n x * 2\n}\n", |
| 1054 | + Mode::Automatic, |
| 1055 | + ); |
| 1056 | + assert!(matches!(outcome, Outcome::Committed), "{error}"); |
| 1057 | + let (outcome, error) = submit(&mut session, "twice", Mode::Type); |
| 1058 | + match outcome { |
| 1059 | + Outcome::Type(ty) => assert_eq!(ty, "fn(Int) -> Int"), |
| 1060 | + _ => panic!("type failed: {error}"), |
| 1061 | + } |
| 1062 | + let (outcome, error) = submit(&mut session, "twice 2", Mode::Automatic); |
| 1063 | + let prepared = match outcome { |
| 1064 | + Outcome::Prepared(prepared) => prepared, |
| 1065 | + _ => panic!("expression was not prepared: {error}"), |
| 1066 | + }; |
| 1067 | + let entry_name = &prepared.program.fns[prepared.entry as usize].name; |
| 1068 | + assert_eq!(entry_name, "+repl.__louise_repl_0"); |
| 1069 | + drop(prepared); |
| 1070 | + let (outcome, error) = submit(&mut session, "__louise_repl_0", Mode::Type); |
| 1071 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1072 | + assert!(error.contains("E0101"), "{error}"); |
| 1073 | + } |
| 1074 | + |
| 1075 | + #[test] |
| 1076 | + fn failed_declarations_roll_back_and_old_diagnostics_do_not_replay() { |
| 1077 | + let mut session = Session::new(Path::new(".")); |
| 1078 | + let (outcome, error) = submit( |
| 1079 | + &mut session, |
| 1080 | + "fn answer :: -> Int {\n 42\n}\n", |
| 1081 | + Mode::Automatic, |
| 1082 | + ); |
| 1083 | + assert!(matches!(outcome, Outcome::Committed), "{error}"); |
| 1084 | + let (outcome, error) = submit( |
| 1085 | + &mut session, |
| 1086 | + "fn answer :: -> Int {\n 0\n}\n", |
| 1087 | + Mode::Automatic, |
| 1088 | + ); |
| 1089 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1090 | + assert!(error.contains("E0106"), "{error}"); |
| 1091 | + let (outcome, error) = submit(&mut session, "answer", Mode::Type); |
| 1092 | + match outcome { |
| 1093 | + Outcome::Type(ty) => assert_eq!(ty, "fn() -> Int"), |
| 1094 | + _ => panic!("old declaration was lost: {error}"), |
| 1095 | + } |
| 1096 | + assert!(!error.contains("E0106"), "old error replayed: {error}"); |
| 1097 | + assert_eq!(session.committed.matches("fn answer ").count(), 1); |
| 1098 | + } |
| 1099 | + |
| 1100 | + #[test] |
| 1101 | + fn type_queries_do_not_require_runnable_or_debug() { |
| 1102 | + let mut session = Session::new(Path::new(".")); |
| 1103 | + for source in [ |
| 1104 | + "import std/io\n", |
| 1105 | + "type Hidden { Hidden }\neffect local { fn fire :: -> () }\n", |
| 1106 | + ] { |
| 1107 | + let (outcome, error) = submit(&mut session, source, Mode::Automatic); |
| 1108 | + assert!(matches!(outcome, Outcome::Committed), "{error}"); |
| 1109 | + } |
| 1110 | + for (expression, expected) in [ |
| 1111 | + ("Hidden", "Hidden"), |
| 1112 | + ("io.println \"not run\"", "() / <io>"), |
| 1113 | + ("fire ()", "() / <local>"), |
| 1114 | + ] { |
| 1115 | + let (outcome, error) = submit(&mut session, expression, Mode::Type); |
| 1116 | + match outcome { |
| 1117 | + Outcome::Type(ty) => assert_eq!(ty, expected, "{expression}"), |
| 1118 | + _ => panic!("type failed for {expression}: {error}"), |
| 1119 | + } |
| 1120 | + } |
| 1121 | + let (outcome, error) = submit(&mut session, "Hidden", Mode::Automatic); |
| 1122 | + assert!( |
| 1123 | + matches!(outcome, Outcome::Rejected), |
| 1124 | + "no-Debug expression was not rejected: {error:?}" |
| 1125 | + ); |
| 1126 | + assert!(error.contains("Debug"), "{error}"); |
| 1127 | + } |
| 1128 | + |
| 1129 | + #[test] |
| 1130 | + fn item_queries_use_canonical_schemes_without_flattening_expression_types() { |
| 1131 | + let mut session = Session::new(Path::new(".")); |
| 1132 | + let (outcome, error) = submit( |
| 1133 | + &mut session, |
| 1134 | + "import std/list\nimport std/io\nfn identity :: x { x }\n", |
| 1135 | + Mode::Automatic, |
| 1136 | + ); |
| 1137 | + assert!(matches!(outcome, Outcome::Committed), "{error}"); |
| 1138 | + for (expression, expected) in [ |
| 1139 | + ("list.range", "fn(Int, Int) -> List<Int>"), |
| 1140 | + ("identity", "fn(a) -> a"), |
| 1141 | + ("identity 1", "Int"), |
| 1142 | + ("list.sum", "fn(List<a>) -> a where Num<a>"), |
| 1143 | + ("io.println", "fn(String) -> () / <io>"), |
| 1144 | + ("io.println \"not run\"", "() / <io>"), |
| 1145 | + ] { |
| 1146 | + let (outcome, error) = submit(&mut session, expression, Mode::Type); |
| 1147 | + match outcome { |
| 1148 | + Outcome::Type(ty) => assert_eq!(ty, expected, "{expression}"), |
| 1149 | + _ => panic!("type failed for {expression}: {error}"), |
| 1150 | + } |
| 1151 | + } |
| 1152 | + } |
| 1153 | + |
| 1154 | + #[test] |
| 1155 | + fn session_debug_cannot_spoof_prelude_debug() { |
| 1156 | + let mut session = Session::new(Path::new(".")); |
| 1157 | + let (outcome, error) = submit( |
| 1158 | + &mut session, |
| 1159 | + "type Hidden { Hidden }\nfn debug :: value: a -> String { \"spoof\" }\n", |
| 1160 | + Mode::Automatic, |
| 1161 | + ); |
| 1162 | + assert!(matches!(outcome, Outcome::Committed), "{error}"); |
| 1163 | + |
| 1164 | + let (outcome, error) = submit(&mut session, "Hidden", Mode::Automatic); |
| 1165 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1166 | + assert!(error.contains("E0401"), "{error}"); |
| 1167 | + let (outcome, error) = submit(&mut session, "1", Mode::Automatic); |
| 1168 | + let Outcome::Prepared(prepared) = outcome else { |
| 1169 | + panic!("qualified literal Debug was not prepared: {error}") |
| 1170 | + }; |
| 1171 | + assert!( |
| 1172 | + prepared.program.fns[prepared.entry as usize] |
| 1173 | + .name |
| 1174 | + .ends_with(".__louise_repl_1") |
| 1175 | + ); |
| 1176 | + // POST-B1 REGRESSION: executing this exact fixture must print `1\n`, |
| 1177 | + // never `spoof\n`; the pre-B1 path deliberately has no value output. |
| 1178 | + drop(prepared); |
| 1179 | + } |
| 1180 | + |
| 1181 | + #[test] |
| 1182 | + fn generated_return_boundary_rejects_raw_results() { |
| 1183 | + let mut session = Session::new(Path::new(".")); |
| 1184 | + for source in ["return \"raw\"", "{ return \"raw\"\n 1 }"] { |
| 1185 | + let (outcome, error) = submit(&mut session, source, Mode::Automatic); |
| 1186 | + assert!(matches!(outcome, Outcome::Rejected), "{source}: {error:?}"); |
| 1187 | + assert!(error.contains("E0119"), "{source}: {error}"); |
| 1188 | + } |
| 1189 | + let (outcome, error) = submit(&mut session, "return", Mode::Type); |
| 1190 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1191 | + assert!(error.contains("E0119"), ":type return: {error}"); |
| 1192 | + |
| 1193 | + // This belongs to an explicit session definition, not to a generated |
| 1194 | + // expression lambda; the ordinary language rule remains available. |
| 1195 | + let (outcome, error) = submit( |
| 1196 | + &mut session, |
| 1197 | + "fn chosen :: -> Int {\n { return 1 }\n 0\n}\n", |
| 1198 | + Mode::Automatic, |
| 1199 | + ); |
| 1200 | + assert!(matches!(outcome, Outcome::Committed), "{error}"); |
| 1201 | + } |
| 1202 | + |
| 1203 | + #[test] |
| 1204 | + fn generated_names_skip_constructors_imports_and_prelude_aliases() { |
| 1205 | + let mut constructors = Session::new(Path::new(".")); |
| 1206 | + let (outcome, error) = submit( |
| 1207 | + &mut constructors, |
| 1208 | + "type Collision { __louise_repl_0 }\n", |
| 1209 | + Mode::Automatic, |
| 1210 | + ); |
| 1211 | + assert!(matches!(outcome, Outcome::Committed), "{error}"); |
| 1212 | + let (outcome, error) = submit(&mut constructors, "1", Mode::Automatic); |
| 1213 | + let Outcome::Prepared(prepared) = outcome else { |
| 1214 | + panic!("constructor collision was not skipped: {error}") |
| 1215 | + }; |
| 1216 | + assert!( |
| 1217 | + prepared.program.fns[prepared.entry as usize] |
| 1218 | + .name |
| 1219 | + .ends_with(".__louise_repl_1") |
| 1220 | + ); |
| 1221 | + |
| 1222 | + let mut imports = Session::new(Path::new(".")); |
| 1223 | + let (outcome, error) = submit( |
| 1224 | + &mut imports, |
| 1225 | + "import std/list.{range as __louise_repl_0, range as __louise_repl_prelude_1}\n", |
| 1226 | + Mode::Automatic, |
| 1227 | + ); |
| 1228 | + assert!(matches!(outcome, Outcome::Committed), "{error}"); |
| 1229 | + let (outcome, error) = submit(&mut imports, "1", Mode::Automatic); |
| 1230 | + let Outcome::Prepared(prepared) = outcome else { |
| 1231 | + panic!("import collisions were not skipped: {error}") |
| 1232 | + }; |
| 1233 | + assert!( |
| 1234 | + prepared.program.fns[prepared.entry as usize] |
| 1235 | + .name |
| 1236 | + .ends_with(".__louise_repl_2") |
| 1237 | + ); |
| 1238 | + } |
| 1239 | + |
| 1240 | + #[test] |
| 1241 | + fn tiny_type_limit_rolls_back_without_a_partial_type() { |
| 1242 | + let mut session = Session::new(Path::new(".")); |
| 1243 | + let fragment = louise_syntax::parse_expression_fragment("fn x { x }"); |
| 1244 | + let mut errors = Vec::new(); |
| 1245 | + let outcome = session |
| 1246 | + .submit( |
| 1247 | + &fragment, |
| 1248 | + Mode::Type, |
| 1249 | + &mut errors, |
| 1250 | + false, |
| 1251 | + Limits { |
| 1252 | + type_bytes: 8, |
| 1253 | + ..Limits::default() |
| 1254 | + }, |
| 1255 | + ) |
| 1256 | + .unwrap(); |
| 1257 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1258 | + let error = String::from_utf8(errors).unwrap(); |
| 1259 | + assert!(error.contains("type-result limit of 8 bytes"), "{error}"); |
| 1260 | + assert!(session.committed.is_empty()); |
| 1261 | + let (outcome, error) = submit(&mut session, "fn x { x }", Mode::Type); |
| 1262 | + assert!(matches!(outcome, Outcome::Type(_)), "{error}"); |
| 1263 | + } |
| 1264 | + |
| 1265 | + #[test] |
| 1266 | + fn reset_clears_names_and_wrapper_numbering() { |
| 1267 | + let mut session = Session::new(Path::new(".")); |
| 1268 | + assert!(matches!( |
| 1269 | + submit(&mut session, "fn old :: -> Int { 1 }\n", Mode::Automatic), |
| 1270 | + (Outcome::Committed, _) |
| 1271 | + )); |
| 1272 | + session.reset(); |
| 1273 | + let (outcome, error) = submit(&mut session, "old", Mode::Type); |
| 1274 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1275 | + assert!(error.contains("E0101"), "{error}"); |
| 1276 | + assert_eq!(session.next_wrapper, 1, "only the rejected type wrapper"); |
| 1277 | + let (outcome, error) = submit(&mut session, "1", Mode::Automatic); |
| 1278 | + assert!(matches!(outcome, Outcome::Prepared(_)), "{error}"); |
| 1279 | + let Outcome::Prepared(prepared) = outcome else { |
| 1280 | + unreachable!() |
| 1281 | + }; |
| 1282 | + assert!( |
| 1283 | + prepared.program.fns[prepared.entry as usize] |
| 1284 | + .name |
| 1285 | + .ends_with(".__louise_repl_1") |
| 1286 | + ); |
| 1287 | + } |
| 1288 | + |
| 1289 | + #[test] |
| 1290 | + fn load_is_bounded_utf8_atomic_and_does_not_run_main() { |
| 1291 | + let root = std::env::temp_dir().join(format!("louise-repl-load-{}", std::process::id())); |
| 1292 | + std::fs::create_dir_all(&root).unwrap(); |
| 1293 | + let valid = root.join("valid.lse"); |
| 1294 | + std::fs::write( |
| 1295 | + &valid, |
| 1296 | + "fn loaded :: -> Int { 7 }\npub fn main :: -> () { panic \"main must not run\" }\n", |
| 1297 | + ) |
| 1298 | + .unwrap(); |
| 1299 | + let mut session = Session::new(&root); |
| 1300 | + let mut errors = Vec::new(); |
| 1301 | + let outcome = session |
| 1302 | + .load("valid.lse", &mut errors, false, Limits::default()) |
| 1303 | + .unwrap(); |
| 1304 | + assert!(matches!(outcome, Outcome::Committed)); |
| 1305 | + assert!(session.committed.contains("fn loaded")); |
| 1306 | + let (outcome, error) = submit(&mut session, "loaded", Mode::Type); |
| 1307 | + assert!(matches!(outcome, Outcome::Type(_)), "{error}"); |
| 1308 | + |
| 1309 | + let invalid = root.join("invalid.lse"); |
| 1310 | + std::fs::write(&invalid, [0xff, 0xfe]).unwrap(); |
| 1311 | + let before = session.committed.clone(); |
| 1312 | + let outcome = session |
| 1313 | + .load("valid.lse", &mut errors, false, Limits::default()) |
| 1314 | + .unwrap(); |
| 1315 | + assert!( |
| 1316 | + matches!(outcome, Outcome::Rejected), |
| 1317 | + "reload must be a duplicate" |
| 1318 | + ); |
| 1319 | + assert_eq!(session.committed, before); |
| 1320 | + let outcome = session |
| 1321 | + .load("missing.lse", &mut errors, false, Limits::default()) |
| 1322 | + .unwrap(); |
| 1323 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1324 | + assert_eq!(session.committed, before); |
| 1325 | + let outcome = session |
| 1326 | + .load("invalid.lse", &mut errors, false, Limits::default()) |
| 1327 | + .unwrap(); |
| 1328 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1329 | + assert_eq!(session.committed, before); |
| 1330 | + |
| 1331 | + let large = root.join("large.lse"); |
| 1332 | + std::fs::write(&large, vec![b' '; 65]).unwrap(); |
| 1333 | + let outcome = session |
| 1334 | + .load("large.lse", &mut errors, false, small_limits()) |
| 1335 | + .unwrap(); |
| 1336 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1337 | + assert_eq!(session.committed, before); |
| 1338 | + for name in ["valid.lse", "invalid.lse", "large.lse"] { |
| 1339 | + let _ = std::fs::remove_file(root.join(name)); |
| 1340 | + } |
| 1341 | + let _ = std::fs::remove_dir(&root); |
| 1342 | + } |
| 1343 | + |
| 1344 | + #[test] |
| 1345 | + fn changing_load_contents_are_rejected_without_mtime_assumptions() { |
| 1346 | + // Same-size snapshots make this a deterministic change simulator, not |
| 1347 | + // a concurrent writer that must win a race or update an mtime field. |
| 1348 | + let mut snapshots = vec![ |
| 1349 | + b"fn one :: -> Int { 1 }\n".to_vec(), |
| 1350 | + b"fn two :: -> Int { 2 }\n".to_vec(), |
| 1351 | + ] |
| 1352 | + .into_iter(); |
| 1353 | + let error = stable_load_bytes(Path::new("changing.lse"), || { |
| 1354 | + Ok(snapshots.next().expect("two fixture snapshots")) |
| 1355 | + }) |
| 1356 | + .unwrap_err(); |
| 1357 | + assert!(error.contains("changed between bounded reads"), "{error}"); |
| 1358 | + } |
| 1359 | + |
| 1360 | + #[test] |
| 1361 | + fn line_and_submission_limits_leave_reset_usable() { |
| 1362 | + let mut out = Vec::new(); |
| 1363 | + let mut err = Vec::new(); |
| 1364 | + let mut input = io::Cursor::new(b"123456789012345678901234567890123\n:reset\n".to_vec()); |
| 1365 | + run_io( |
| 1366 | + &mut input, |
| 1367 | + &mut out, |
| 1368 | + &mut err, |
| 1369 | + false, |
| 1370 | + false, |
| 1371 | + Path::new("."), |
| 1372 | + small_limits(), |
| 1373 | + ) |
| 1374 | + .unwrap(); |
| 1375 | + assert!( |
| 1376 | + String::from_utf8(err) |
| 1377 | + .unwrap() |
| 1378 | + .contains("input line exceeds 32 bytes") |
| 1379 | + ); |
| 1380 | + |
| 1381 | + let mut session = Session::new(Path::new(".")); |
| 1382 | + let oversized = format!("fn too_big :: -> Int {{ {} }}\n", "1 + ".repeat(40) + "1"); |
| 1383 | + let mut errors = Vec::new(); |
| 1384 | + let outcome = session |
| 1385 | + .commit_source(oversized, &mut errors, false, small_limits()) |
| 1386 | + .unwrap(); |
| 1387 | + assert!(matches!(outcome, Outcome::Rejected)); |
| 1388 | + session.reset(); |
| 1389 | + assert_eq!(session.next_wrapper, 0); |
| 1390 | + assert!(session.committed.is_empty()); |
| 1391 | + } |
| 1392 | + |
| 1393 | + #[test] |
| 1394 | + fn bounded_lines_preserve_utf8_and_detect_eof() { |
| 1395 | + let mut input = io::Cursor::new("héllo\nrest".as_bytes().to_vec()); |
| 1396 | + assert!( |
| 1397 | + matches!(read_bounded_line(&mut input, 6).unwrap(), InputLine::Text(line) if line == "héllo\n") |
| 1398 | + ); |
| 1399 | + assert!( |
| 1400 | + matches!(read_bounded_line(&mut input, 4).unwrap(), InputLine::Text(line) if line == "rest") |
| 1401 | + ); |
| 1402 | + assert!(matches!( |
| 1403 | + read_bounded_line(&mut input, 4).unwrap(), |
| 1404 | + InputLine::Eof |
| 1405 | + )); |
| 1406 | + let mut too_long = io::Cursor::new(b"abcdef\nnext\n".to_vec()); |
| 1407 | + assert!(matches!( |
| 1408 | + read_bounded_line(&mut too_long, 3).unwrap(), |
| 1409 | + InputLine::TooLong |
| 1410 | + )); |
| 1411 | + assert!( |
| 1412 | + matches!(read_bounded_line(&mut too_long, 3).unwrap(), InputLine::Text(line) if line == "next\n") |
| 1413 | + ); |
| 1414 | + let mut invalid = io::Cursor::new(vec![0xff, b'\n']); |
| 1415 | + assert!(matches!( |
| 1416 | + read_bounded_line(&mut invalid, 8).unwrap(), |
| 1417 | + InputLine::InvalidUtf8 |
| 1418 | + )); |
| 1419 | + } |
| 1420 | + |
| 1421 | + #[test] |
| 1422 | + fn diagnostics_have_an_explicit_truncation_diagnostic() { |
| 1423 | + let mut sources = SourceDb::default(); |
| 1424 | + let file = sources.add(SourceFile::new(DISPLAY_PATH, "bad")); |
| 1425 | + let diagnostics: Vec<_> = (0..20) |
| 1426 | + .map(|index| { |
| 1427 | + Diagnostic::error( |
| 1428 | + "E0001", |
| 1429 | + format!("deliberately repeated test diagnostic {index}"), |
| 1430 | + louise_span::Span { |
| 1431 | + file, |
| 1432 | + range: louise_span::TextRange::new(0.into(), 1.into()), |
| 1433 | + }, |
| 1434 | + ) |
| 1435 | + }) |
| 1436 | + .collect(); |
| 1437 | + let mut out = Vec::new(); |
| 1438 | + render_diagnostics(&sources, &diagnostics, false, &mut out, 256).unwrap(); |
| 1439 | + let text = String::from_utf8(out).unwrap(); |
| 1440 | + assert!(text.contains("diagnostics exceeded 256 bytes"), "{text}"); |
| 1441 | + assert!( |
| 1442 | + text.len() < 400, |
| 1443 | + "capture retained too much: {}", |
| 1444 | + text.len() |
| 1445 | + ); |
| 1446 | + } |
| 1447 | + |
| 1448 | + #[derive(Clone, Default)] |
| 1449 | + struct FlushCounter(Arc<AtomicUsize>); |
| 1450 | + |
| 1451 | + impl Write for FlushCounter { |
| 1452 | + fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { |
| 1453 | + Ok(bytes.len()) |
| 1454 | + } |
| 1455 | + |
| 1456 | + fn flush(&mut self) -> io::Result<()> { |
| 1457 | + self.0.fetch_add(1, Ordering::SeqCst); |
| 1458 | + Ok(()) |
| 1459 | + } |
| 1460 | + } |
| 1461 | + |
| 1462 | + #[test] |
| 1463 | + fn explicit_interactivity_flushes_prompts_and_pipes_have_none() { |
| 1464 | + let flushes = FlushCounter::default(); |
| 1465 | + let mut counted = flushes.clone(); |
| 1466 | + let mut err = Vec::new(); |
| 1467 | + let mut input = io::Cursor::new(b":help\n".to_vec()); |
| 1468 | + run_io( |
| 1469 | + &mut input, |
| 1470 | + &mut counted, |
| 1471 | + &mut err, |
| 1472 | + true, |
| 1473 | + false, |
| 1474 | + Path::new("."), |
| 1475 | + small_limits(), |
| 1476 | + ) |
| 1477 | + .unwrap(); |
| 1478 | + assert!( |
| 1479 | + flushes.0.load(Ordering::SeqCst) >= 2, |
| 1480 | + "prompt before each read, including EOF" |
| 1481 | + ); |
| 1482 | + |
| 1483 | + let mut out = Vec::new(); |
| 1484 | + let mut err = Vec::new(); |
| 1485 | + let mut input = io::Cursor::new(b":help\n".to_vec()); |
| 1486 | + run_io( |
| 1487 | + &mut input, |
| 1488 | + &mut out, |
| 1489 | + &mut err, |
| 1490 | + false, |
| 1491 | + false, |
| 1492 | + Path::new("."), |
| 1493 | + small_limits(), |
| 1494 | + ) |
| 1495 | + .unwrap(); |
| 1496 | + assert!(String::from_utf8_lossy(&out).contains(":type EXPR")); |
| 1497 | + assert!(!String::from_utf8_lossy(&out).contains("louise>")); |
| 1498 | + } |
| 1499 | +} |