| @@ -0,0 +1,625 @@ |
| 1 | +//! `louise migrate` (ADR 0061, issue #314): rewrites pre-ADR-0061 source |
| 2 | +//! in the parens-free syntax. |
| 3 | +//! |
| 4 | +//! The input is parsed with the frozen old grammar ([`crate::legacy`]); |
| 5 | +//! the translator walks the old tree and emits the new text, which the |
| 6 | +//! formatter then lays out canonically. Only these shapes change: |
| 7 | +//! |
| 8 | +//! - definitions and lambdas: `fn f(a: Int, b)` → `fn f :: a: Int b`; |
| 9 | +//! a parameter that is more than a name keeps its parentheses |
| 10 | +//! (`(Some(x) as s)`); an old `label c: T` parameter becomes |
| 11 | +//! `~label:(c: T)`. |
| 12 | +//! - effect operations (`fn op :: x: T -> U`) and handler clauses |
| 13 | +//! (`op x -> body`, no `::`). |
| 14 | +//! - calls: `f(a, b)` → `f a b`; `f()` → `f ()`; `f(label: x)` → |
| 15 | +//! `f ~label: x` (punned to `f ~label` when the value is the same name). |
| 16 | +//! An argument that is not an atom is parenthesised (`f (a + b)`, |
| 17 | +//! `f (g x)`). A call whose callee is a constructor path (the last |
| 18 | +//! segment starts uppercase, as in patterns) is construction and keeps |
| 19 | +//! its parentheses and commas, with `~` labels: `User(name: x)` → |
| 20 | +//! `User(~name: x)`, as does a record update (`User(..u, ~name: x)`) |
| 21 | +//! and any parenthesised list containing a spread. |
| 22 | +//! - constructor patterns: `User(name: n, ..)` → `User(~name: n, ..)`. |
| 23 | +//! - attributes: `@derive(Eq, Show)` → `@derive Eq Show`, |
| 24 | +//! `@extern(c, "s", blocking(io))` → `@extern c "s" (blocking io)`. |
| 25 | +//! |
| 26 | +//! Safety, like the formatter's: the old text's significant tokens and |
| 27 | +//! the output's are compared; the only allowed differences are the edits |
| 28 | +//! above — added `::`/`~`, added or removed parentheses around single |
| 29 | +//! expressions, removed list parentheses and commas. Comments must match |
| 30 | +//! in order. A comment inside a transformed list is lifted out after the |
| 31 | +//! head (`f(a, // why\n b)` is `f // why\n a b`); only a zero-argument |
| 32 | +//! call's comment has nowhere to go, and refuses the file. |
| 33 | + |
| 34 | +use louise_span::TextRange; |
| 35 | +use rowan::NodeOrToken; |
| 36 | + |
| 37 | +use crate::SyntaxKind::{self, *}; |
| 38 | +use crate::legacy::ast::AstNode as _; |
| 39 | +use crate::{SyntaxNode, SyntaxToken, format, legacy}; |
| 40 | + |
| 41 | +#[derive(Debug)] |
| 42 | +pub enum MigrateError { |
| 43 | + /// The input does not parse in the *old* syntax. |
| 44 | + SyntaxErrors(String), |
| 45 | + /// A comment sits inside a list the migration rewrites; migrate it by |
| 46 | + /// hand. |
| 47 | + CommentInList(String), |
| 48 | + /// The token check failed (a bug — please report it, with the input). |
| 49 | + Unsafe(String), |
| 50 | +} |
| 51 | + |
| 52 | +/// Migrate one source file's text. |
| 53 | +pub fn migrate(text: &str) -> Result<String, MigrateError> { |
| 54 | + let (root, errors) = legacy::parse(text); |
| 55 | + if !errors.is_empty() { |
| 56 | + return Err(MigrateError::SyntaxErrors( |
| 57 | + errors |
| 58 | + .iter() |
| 59 | + .map(|e| format!("{:?}: {}", e.range, e.message)) |
| 60 | + .collect::<Vec<_>>() |
| 61 | + .join("\n"), |
| 62 | + )); |
| 63 | + } |
| 64 | + let mut t = Translator { |
| 65 | + src: text, |
| 66 | + drops: Vec::new(), |
| 67 | + comment: None, |
| 68 | + }; |
| 69 | + let mut out = String::with_capacity(text.len()); |
| 70 | + t.emit(&root, &mut out); |
| 71 | + if let Some(range) = t.comment { |
| 72 | + return Err(MigrateError::CommentInList(format!("{range:?}"))); |
| 73 | + } |
| 74 | + let formatted = format::format(&out).map_err(|e| { |
| 75 | + MigrateError::Unsafe(format!("the migrated text does not format: {e:?}\n{out}")) |
| 76 | + })?; |
| 77 | + token_check(text, &formatted, &t.drops)?; |
| 78 | + Ok(formatted) |
| 79 | +} |
| 80 | + |
| 81 | +struct Translator<'a> { |
| 82 | + src: &'a str, |
| 83 | + /// Ranges of old tokens the migration drops: the parentheses and |
| 84 | + /// commas of transformed lists. |
| 85 | + drops: Vec<TextRange>, |
| 86 | + /// A comment that cannot be lifted out of a transformed list (a |
| 87 | + /// zero-argument call's): the file is migrated by hand. |
| 88 | + comment: Option<TextRange>, |
| 89 | +} |
| 90 | + |
| 91 | +/// The byte column of a byte offset in `src`. |
| 92 | +fn col_of(src: &str, offset: usize) -> usize { |
| 93 | + offset - src[..offset].rfind('\n').map_or(0, |i| i + 1) |
| 94 | +} |
| 95 | + |
| 96 | +impl Translator<'_> { |
| 97 | + fn emit(&mut self, node: &SyntaxNode, out: &mut String) { |
| 98 | + match node.kind() { |
| 99 | + FN_DEF | EFFECT_OP => self.def_like(node, out, true), |
| 100 | + LAMBDA_EXPR | HANDLER_CLAUSE => self.def_like(node, out, false), |
| 101 | + CALL_EXPR => self.call(node, out), |
| 102 | + ATTR => self.attr(node, out), |
| 103 | + PAT_ARG => self.pat_arg(node, out), |
| 104 | + _ => self.verbatim(node, out), |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + /// Children copied as they are, nodes recursively migrated. |
| 109 | + fn verbatim(&mut self, node: &SyntaxNode, out: &mut String) { |
| 110 | + for child in node.children_with_tokens() { |
| 111 | + match child { |
| 112 | + NodeOrToken::Node(n) => self.emit(&n, out), |
| 113 | + NodeOrToken::Token(t) => out.push_str(t.text()), |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /// Records the tokens of a transformed list that the output drops: |
| 119 | + /// its parentheses and commas (direct children only; a nested |
| 120 | + /// attribute call keeps its own parentheses). Returns the comments |
| 121 | + /// found inside, which the caller re-emits after the head (they end |
| 122 | + /// their line, so the arguments follow on the next one, at the first |
| 123 | + /// argument's source column). |
| 124 | + fn drop_list_syntax(&mut self, node: &SyntaxNode) -> Vec<SyntaxToken> { |
| 125 | + let mut comments = Vec::new(); |
| 126 | + for child in node.children_with_tokens() { |
| 127 | + match child { |
| 128 | + NodeOrToken::Token(t) if matches!(t.kind(), L_PAREN | R_PAREN | COMMA) => { |
| 129 | + self.drops.push(t.text_range()); |
| 130 | + } |
| 131 | + NodeOrToken::Token(t) if matches!(t.kind(), COMMENT | DOC_COMMENT) => { |
| 132 | + comments.push(t); |
| 133 | + } |
| 134 | + _ => {} |
| 135 | + } |
| 136 | + } |
| 137 | + comments |
| 138 | + } |
| 139 | + |
| 140 | + /// Comments lifted out of a transformed list: each ends its line |
| 141 | + /// after the head; the arguments follow on a fresh line at `arg_col`. |
| 142 | + fn lifted_comments(&mut self, comments: &[SyntaxToken], arg_col: usize, out: &mut String) { |
| 143 | + for c in comments { |
| 144 | + out.push(' '); |
| 145 | + out.push_str(c.text().trim_end()); |
| 146 | + out.push('\n'); |
| 147 | + out.push_str(&" ".repeat(arg_col)); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + /// `fn name(a, b)`, `fn(a, b)`, `op(a, b)`: the head keeps its |
| 152 | + /// tokens; the parameter list loses its parentheses and commas and |
| 153 | + /// gains `::` at a definition (ADR 0061). |
| 154 | + fn def_like(&mut self, node: &SyntaxNode, out: &mut String, definition: bool) { |
| 155 | + // A comment between the name and the parameter list (`fn f // c` |
| 156 | + // `(x)`) is emitted after the `::` it precedes. |
| 157 | + let mut head_comments: Vec<SyntaxToken> = Vec::new(); |
| 158 | + for child in node.children_with_tokens() { |
| 159 | + match child { |
| 160 | + NodeOrToken::Node(n) if n.kind() == PARAM_LIST => { |
| 161 | + let mut comments = std::mem::take(&mut head_comments); |
| 162 | + comments.extend(self.drop_list_syntax(&n)); |
| 163 | + out.push_str(if definition { " ::" } else { "" }); |
| 164 | + let params: Vec<_> = n.children().filter(|c| c.kind() == PARAM).collect(); |
| 165 | + if comments.is_empty() { |
| 166 | + for p in ¶ms { |
| 167 | + out.push(' '); |
| 168 | + self.param(p, out); |
| 169 | + } |
| 170 | + } else { |
| 171 | + let col = params |
| 172 | + .first() |
| 173 | + .map(|p| col_of(self.src, p.text_range().start().into())) |
| 174 | + .unwrap_or(0); |
| 175 | + self.lifted_comments(&comments, col, out); |
| 176 | + for (i, p) in params.iter().enumerate() { |
| 177 | + if i > 0 { |
| 178 | + out.push(' '); |
| 179 | + } |
| 180 | + self.param(p, out); |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + NodeOrToken::Node(n) => self.emit(&n, out), |
| 185 | + NodeOrToken::Token(t) |
| 186 | + if matches!(t.kind(), WHITESPACE | COMMENT | DOC_COMMENT) |
| 187 | + && next_is_param_list(&t) => |
| 188 | + { |
| 189 | + // Replaced by the parameter list's own separators; a |
| 190 | + // comment is emitted after the `::`. |
| 191 | + if t.kind() != WHITESPACE { |
| 192 | + head_comments.push(t); |
| 193 | + } |
| 194 | + } |
| 195 | + NodeOrToken::Token(t) => out.push_str(t.text()), |
| 196 | + } |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + /// `a: Int`, `label c: T` → `~label:(c: T)`, `Some(x) as s` → |
| 201 | + /// `(Some(x) as s)`: a pattern that is more than a name keeps its |
| 202 | + /// parentheses. |
| 203 | + fn param(&mut self, node: &SyntaxNode, out: &mut String) { |
| 204 | + let param = legacy::ast::Param::cast(node.clone()); |
| 205 | + let (label, pat, ty) = match ¶m { |
| 206 | + Some(p) => (p.label(), p.pat(), p.ty()), |
| 207 | + None => (None, None, None), |
| 208 | + }; |
| 209 | + match label { |
| 210 | + Some(l) => { |
| 211 | + out.push('~'); |
| 212 | + out.push_str(&l.text()); |
| 213 | + match pat { |
| 214 | + Some(p) => { |
| 215 | + // A renamed binding groups: `~label:(c: T)`. |
| 216 | + out.push_str(":("); |
| 217 | + self.emit(p.syntax(), out); |
| 218 | + if let Some(ty) = ty { |
| 219 | + out.push_str(": "); |
| 220 | + self.emit(ty.syntax(), out); |
| 221 | + } |
| 222 | + out.push(')'); |
| 223 | + } |
| 224 | + None => { |
| 225 | + if let Some(ty) = ty { |
| 226 | + out.push_str(": "); |
| 227 | + self.emit(ty.syntax(), out); |
| 228 | + } |
| 229 | + } |
| 230 | + } |
| 231 | + } |
| 232 | + None => { |
| 233 | + let bare = matches!( |
| 234 | + pat, |
| 235 | + Some(legacy::ast::Pat::BindPat(_) | legacy::ast::Pat::WildcardPat(_)) |
| 236 | + ); |
| 237 | + if !bare { |
| 238 | + out.push('('); |
| 239 | + } |
| 240 | + if let Some(p) = &pat { |
| 241 | + self.emit(p.syntax(), out); |
| 242 | + } |
| 243 | + if let Some(ty) = &ty { |
| 244 | + out.push_str(": "); |
| 245 | + self.emit(ty.syntax(), out); |
| 246 | + } |
| 247 | + if !bare { |
| 248 | + out.push(')'); |
| 249 | + } |
| 250 | + } |
| 251 | + } |
| 252 | + } |
| 253 | + |
| 254 | + /// `f(a, b)` → `f a b`; `User(name: x)` → `User(~name: x)`. |
| 255 | + fn call(&mut self, node: &SyntaxNode, out: &mut String) { |
| 256 | + let Some(call) = legacy::ast::CallExpr::cast(node.clone()) else { |
| 257 | + return self.verbatim(node, out); |
| 258 | + }; |
| 259 | + let args = call.args(); |
| 260 | + let construction = call.callee().as_ref().is_some_and(callee_is_ctor) |
| 261 | + || args |
| 262 | + .iter() |
| 263 | + .any(|a| matches!(a, legacy::ast::ArgOrSpread::Spread(_))); |
| 264 | + if construction { |
| 265 | + if let Some(callee) = call.callee() { |
| 266 | + self.emit(callee.syntax(), out); |
| 267 | + } |
| 268 | + if let Some(list) = arg_list_node(node) { |
| 269 | + self.ctor_args(&list, out); |
| 270 | + } |
| 271 | + return; |
| 272 | + } |
| 273 | + // Application: the callee, then each argument space-separated. |
| 274 | + if let Some(callee) = call.callee() { |
| 275 | + self.head(&callee, out); |
| 276 | + } |
| 277 | + let list = arg_list_node(node); |
| 278 | + let comments = list.map(|l| self.drop_list_syntax(&l)).unwrap_or_default(); |
| 279 | + if args.is_empty() { |
| 280 | + // `f()` is `f ()`: the unit argument. |
| 281 | + out.push_str(" ()"); |
| 282 | + if !comments.is_empty() { |
| 283 | + // Nowhere safe to move them; this call is migrated by hand. |
| 284 | + self.comment = comments.first().map(|t| t.text_range()); |
| 285 | + return; |
| 286 | + } |
| 287 | + } |
| 288 | + if !comments.is_empty() { |
| 289 | + let col = args |
| 290 | + .first() |
| 291 | + .map(|a| col_of(self.src, a.syntax().text_range().start().into())) |
| 292 | + .unwrap_or(0); |
| 293 | + self.lifted_comments(&comments, col, out); |
| 294 | + } |
| 295 | + for (i, arg) in args.iter().enumerate() { |
| 296 | + let legacy::ast::ArgOrSpread::Arg(arg) = arg else { |
| 297 | + continue; |
| 298 | + }; |
| 299 | + if i > 0 || comments.is_empty() { |
| 300 | + out.push(' '); |
| 301 | + } |
| 302 | + self.app_arg(arg, out); |
| 303 | + } |
| 304 | + } |
| 305 | + |
| 306 | + /// A call's callee: emitted as is when it is an atom (a path, a field |
| 307 | + /// chain, a construction, a parenthesised expression), parenthesised |
| 308 | + /// otherwise (`(f x) y`). |
| 309 | + fn head(&mut self, expr: &legacy::ast::Expr, out: &mut String) { |
| 310 | + match expr { |
| 311 | + legacy::ast::Expr::PathExpr(_) |
| 312 | + | legacy::ast::Expr::ParenExpr(_) |
| 313 | + | legacy::ast::Expr::TemplateExpr(_) => self.emit(expr.syntax(), out), |
| 314 | + legacy::ast::Expr::FieldExpr(_) if head_atom(expr) => self.emit(expr.syntax(), out), |
| 315 | + legacy::ast::Expr::CallExpr(c) if c.callee().as_ref().is_some_and(callee_is_ctor) => { |
| 316 | + self.emit(expr.syntax(), out) |
| 317 | + } |
| 318 | + _ => self.parened(expr, out), |
| 319 | + } |
| 320 | + } |
| 321 | + |
| 322 | + fn parened(&mut self, expr: &legacy::ast::Expr, out: &mut String) { |
| 323 | + out.push('('); |
| 324 | + self.emit(expr.syntax(), out); |
| 325 | + out.push(')'); |
| 326 | + } |
| 327 | + |
| 328 | + /// An application's argument: `label: x` → `~label: x` (punned when |
| 329 | + /// `x` is `label`), an atom as is, anything bigger parenthesised. |
| 330 | + fn app_arg(&mut self, arg: &legacy::ast::Arg, out: &mut String) { |
| 331 | + if let Some(label) = arg.label() { |
| 332 | + out.push('~'); |
| 333 | + out.push_str(&label.text()); |
| 334 | + let pun = matches!(arg.expr(), Some(legacy::ast::Expr::PathExpr(p)) |
| 335 | + if p.name_ref().is_some_and(|n| n.text() == label.text())); |
| 336 | + if pun { |
| 337 | + self.drop_pun(arg, &label.text()); |
| 338 | + return; |
| 339 | + } |
| 340 | + out.push_str(": "); |
| 341 | + } |
| 342 | + if let Some(value) = arg.expr() { |
| 343 | + if value_is_atom(&value) { |
| 344 | + self.emit(value.syntax(), out); |
| 345 | + } else { |
| 346 | + self.parened(&value, out); |
| 347 | + } |
| 348 | + } |
| 349 | + } |
| 350 | + |
| 351 | + /// A pun (`~name` for `name: name`) drops the old label's colon and |
| 352 | + /// the repeated value. |
| 353 | + fn drop_pun(&mut self, arg: &legacy::ast::Arg, _label: &str) { |
| 354 | + for e in arg.syntax().children_with_tokens() { |
| 355 | + match e { |
| 356 | + NodeOrToken::Node(n) if n.kind() == LABEL => { |
| 357 | + for t in n.descendants_with_tokens().filter_map(|e| e.into_token()) { |
| 358 | + if t.kind() == COLON { |
| 359 | + self.drops.push(t.text_range()); |
| 360 | + } |
| 361 | + } |
| 362 | + } |
| 363 | + NodeOrToken::Node(n) => self.drop_subtree(&n), |
| 364 | + _ => {} |
| 365 | + } |
| 366 | + } |
| 367 | + } |
| 368 | + |
| 369 | + /// Records every significant token of a subtree as dropped. |
| 370 | + fn drop_subtree(&mut self, node: &SyntaxNode) { |
| 371 | + for t in node |
| 372 | + .descendants_with_tokens() |
| 373 | + .filter_map(|e| e.into_token()) |
| 374 | + .filter(|t| !t.kind().is_trivia()) |
| 375 | + { |
| 376 | + self.drops.push(t.text_range()); |
| 377 | + } |
| 378 | + } |
| 379 | + |
| 380 | + /// `(a, ~name: b, ..rest)`: construction keeps its parentheses and |
| 381 | + /// commas; only the labels change (and a label's value is an atom: |
| 382 | + /// `~name: (f x)`). |
| 383 | + fn ctor_args(&mut self, list: &SyntaxNode, out: &mut String) { |
| 384 | + for child in list.children_with_tokens() { |
| 385 | + match child { |
| 386 | + NodeOrToken::Node(n) if n.kind() == ARG => { |
| 387 | + let Some(arg) = legacy::ast::Arg::cast(n) else { |
| 388 | + continue; |
| 389 | + }; |
| 390 | + match arg.label() { |
| 391 | + Some(label) => { |
| 392 | + out.push('~'); |
| 393 | + out.push_str(&label.text()); |
| 394 | + let pun = matches!(arg.expr(), Some(legacy::ast::Expr::PathExpr(p)) |
| 395 | + if p.name_ref().is_some_and(|n| n.text() == label.text())); |
| 396 | + if pun { |
| 397 | + self.drop_pun(&arg, &label.text()); |
| 398 | + } else { |
| 399 | + out.push_str(": "); |
| 400 | + if let Some(value) = arg.expr() { |
| 401 | + if value_is_atom(&value) { |
| 402 | + self.emit(value.syntax(), out); |
| 403 | + } else { |
| 404 | + self.parened(&value, out); |
| 405 | + } |
| 406 | + } |
| 407 | + } |
| 408 | + } |
| 409 | + None => { |
| 410 | + if let Some(value) = arg.expr() { |
| 411 | + self.emit(value.syntax(), out); |
| 412 | + } |
| 413 | + } |
| 414 | + } |
| 415 | + } |
| 416 | + NodeOrToken::Node(n) => self.emit(&n, out), |
| 417 | + NodeOrToken::Token(t) => out.push_str(t.text()), |
| 418 | + } |
| 419 | + } |
| 420 | + } |
| 421 | + |
| 422 | + /// `User(name: n)` → `User(~name: n)`, punned to `User(~name)` when |
| 423 | + /// the pattern binds the same name. |
| 424 | + fn pat_arg(&mut self, node: &SyntaxNode, out: &mut String) { |
| 425 | + let Some(arg) = legacy::ast::PatArg::cast(node.clone()) else { |
| 426 | + return self.verbatim(node, out); |
| 427 | + }; |
| 428 | + match arg.label() { |
| 429 | + Some(label) => { |
| 430 | + out.push('~'); |
| 431 | + out.push_str(&label.text()); |
| 432 | + let pun = matches!(arg.pat(), Some(legacy::ast::Pat::BindPat(b)) |
| 433 | + if b.name().is_some_and(|n| n.text() == label.text())); |
| 434 | + if pun { |
| 435 | + for e in arg.syntax().children_with_tokens() { |
| 436 | + match e { |
| 437 | + NodeOrToken::Node(n) if n.kind() == LABEL => { |
| 438 | + for t in n.descendants_with_tokens().filter_map(|e| e.into_token()) |
| 439 | + { |
| 440 | + if t.kind() == COLON { |
| 441 | + self.drops.push(t.text_range()); |
| 442 | + } |
| 443 | + } |
| 444 | + } |
| 445 | + NodeOrToken::Node(n) => self.drop_subtree(&n), |
| 446 | + _ => {} |
| 447 | + } |
| 448 | + } |
| 449 | + } else { |
| 450 | + out.push_str(": "); |
| 451 | + if let Some(pat) = arg.pat() { |
| 452 | + self.emit(pat.syntax(), out); |
| 453 | + } |
| 454 | + } |
| 455 | + } |
| 456 | + None => self.verbatim(node, out), |
| 457 | + } |
| 458 | + } |
| 459 | + |
| 460 | + /// `@name(a, b, c(d))` → `@name a b (c d)`. |
| 461 | + fn attr(&mut self, node: &SyntaxNode, out: &mut String) { |
| 462 | + let Some(attr) = legacy::ast::Attr::cast(node.clone()) else { |
| 463 | + return self.verbatim(node, out); |
| 464 | + }; |
| 465 | + let list = node.children().find(|n| n.kind() == ATTR_ARG_LIST); |
| 466 | + let comments = list |
| 467 | + .as_ref() |
| 468 | + .map(|l| self.drop_list_syntax(l)) |
| 469 | + .unwrap_or_default(); |
| 470 | + if let Some(list) = &list { |
| 471 | + // A nested call's parentheses move out of its name |
| 472 | + // (`blocking(io)` → `(blocking io)`): dropped here, re-added |
| 473 | + // around it there. |
| 474 | + for call in list.children().filter(|n| n.kind() == ATTR_ARG_CALL) { |
| 475 | + for e in call.children_with_tokens() { |
| 476 | + if let NodeOrToken::Token(t) = e |
| 477 | + && matches!(t.kind(), L_PAREN | R_PAREN) |
| 478 | + { |
| 479 | + self.drops.push(t.text_range()); |
| 480 | + } |
| 481 | + } |
| 482 | + } |
| 483 | + } |
| 484 | + out.push('@'); |
| 485 | + if let Some(name) = attr.name() { |
| 486 | + out.push_str(&name.text()); |
| 487 | + } |
| 488 | + let args = attr.args(); |
| 489 | + if !comments.is_empty() { |
| 490 | + let col = args |
| 491 | + .first() |
| 492 | + .map(|a| { |
| 493 | + col_of(self.src, match a { |
| 494 | + legacy::ast::AttrArg::Token(t) => t.text_range().start().into(), |
| 495 | + legacy::ast::AttrArg::Call { range, .. } => range.start().into(), |
| 496 | + }) |
| 497 | + }) |
| 498 | + .unwrap_or(0); |
| 499 | + self.lifted_comments(&comments, col, out); |
| 500 | + } |
| 501 | + for (i, arg) in args.iter().enumerate() { |
| 502 | + if i > 0 || comments.is_empty() { |
| 503 | + out.push(' '); |
| 504 | + } |
| 505 | + match arg { |
| 506 | + legacy::ast::AttrArg::Token(t) => out.push_str(t.text()), |
| 507 | + legacy::ast::AttrArg::Call { name, arg, .. } => { |
| 508 | + out.push('('); |
| 509 | + out.push_str(name.text()); |
| 510 | + if let Some(arg) = arg { |
| 511 | + out.push(' '); |
| 512 | + out.push_str(arg.text()); |
| 513 | + } |
| 514 | + out.push(')'); |
| 515 | + } |
| 516 | + } |
| 517 | + } |
| 518 | + } |
| 519 | +} |
| 520 | + |
| 521 | +/// The node of a call's argument list. |
| 522 | +fn arg_list_node(call: &SyntaxNode) -> Option<SyntaxNode> { |
| 523 | + call.children().find(|n| n.kind() == ARG_LIST) |
| 524 | +} |
| 525 | + |
| 526 | +/// Whether the next significant sibling of a token is a parameter list. |
| 527 | +fn next_is_param_list(t: &SyntaxToken) -> bool { |
| 528 | + std::iter::successors(t.next_sibling_or_token(), |e| e.next_sibling_or_token()) |
| 529 | + .find(|e| !e.kind().is_trivia()) |
| 530 | + .is_some_and(|e| e.kind() == PARAM_LIST) |
| 531 | +} |
| 532 | + |
| 533 | +/// A constructor path: `User`, `option.Some` — the last segment starts |
| 534 | +/// uppercase, the same rule patterns use. |
| 535 | +fn callee_is_ctor(expr: &legacy::ast::Expr) -> bool { |
| 536 | + match expr { |
| 537 | + legacy::ast::Expr::PathExpr(p) => p |
| 538 | + .name_ref() |
| 539 | + .is_some_and(|n| n.text().starts_with(char::is_uppercase)), |
| 540 | + legacy::ast::Expr::FieldExpr(f) => f |
| 541 | + .field() |
| 542 | + .is_some_and(|n| n.text().starts_with(char::is_uppercase)), |
| 543 | + _ => false, |
| 544 | + } |
| 545 | +} |
| 546 | + |
| 547 | +/// Whether a field chain's base is atom-shaped (`a.b.c`, not `f(x).y`). |
| 548 | +fn head_atom(expr: &legacy::ast::Expr) -> bool { |
| 549 | + match expr { |
| 550 | + legacy::ast::Expr::PathExpr(_) => true, |
| 551 | + legacy::ast::Expr::FieldExpr(f) => f.base().as_ref().is_some_and(head_atom), |
| 552 | + legacy::ast::Expr::CallExpr(c) => c.callee().as_ref().is_some_and(callee_is_ctor), |
| 553 | + _ => false, |
| 554 | + } |
| 555 | +} |
| 556 | + |
| 557 | +/// An argument that needs no parentheses in the new syntax (ADR 0061's |
| 558 | +/// atoms): a literal, path, list, tuple or parenthesised expression, |
| 559 | +/// lambda, tagged template, if/match/handle/region, `_`, a construction. |
| 560 | +fn value_is_atom(expr: &legacy::ast::Expr) -> bool { |
| 561 | + use legacy::ast::Expr::*; |
| 562 | + match expr { |
| 563 | + Literal(_) | InterpString(_) | TemplateExpr(_) | PathExpr(_) | ParenExpr(_) |
| 564 | + | TupleExpr(_) | ListExpr(_) | LambdaExpr(_) | IfExpr(_) | MatchExpr(_) |
| 565 | + | HandleExpr(_) | RegionExpr(_) | PlaceholderExpr(_) => true, |
| 566 | + FieldExpr(_) => head_atom(expr), |
| 567 | + CallExpr(c) => c.callee().as_ref().is_some_and(callee_is_ctor), |
| 568 | + Block(_) | BinExpr(_) | PrefixExpr(_) | ReturnExpr(_) | HtmlElement(_) => false, |
| 569 | + } |
| 570 | +} |
| 571 | + |
| 572 | +// --------------------------------------------------------------------------- |
| 573 | +// The token check |
| 574 | + |
| 575 | +/// Old and new significant tokens must be equal up to the migration's |
| 576 | +/// edits: dropped list parentheses and commas (recorded by the |
| 577 | +/// translator), added `::` and `~`, and parentheses added around single |
| 578 | +/// arguments (which never contain a top-level comma, so they cannot |
| 579 | +/// create or lose a tuple). Comments must match, in order. |
| 580 | +fn token_check(old: &str, new: &str, drops: &[TextRange]) -> Result<(), MigrateError> { |
| 581 | + let (old_root, _) = legacy::parse(old); |
| 582 | + let new_root = crate::parse(new).syntax(); |
| 583 | + let old_tokens: Vec<(SyntaxKind, String)> = format::significant_tokens_of(&old_root) |
| 584 | + .into_iter() |
| 585 | + .filter(|(_, _, range)| !drops.contains(range)) |
| 586 | + .map(|(k, t, _)| (k, t)) |
| 587 | + .collect(); |
| 588 | + let new_tokens: Vec<(SyntaxKind, String)> = format::significant_tokens_of(&new_root) |
| 589 | + .into_iter() |
| 590 | + .filter(|(k, _, _)| !matches!(k, COLON2 | TILDE)) |
| 591 | + .map(|(k, t, _)| (k, t)) |
| 592 | + .collect(); |
| 593 | + let mut old_iter = old_tokens.iter().peekable(); |
| 594 | + for token in &new_tokens { |
| 595 | + loop { |
| 596 | + match old_iter.peek() { |
| 597 | + Some(t) if *t == token => { |
| 598 | + old_iter.next(); |
| 599 | + break; |
| 600 | + } |
| 601 | + // Parentheses the migration added around an argument. |
| 602 | + _ if matches!(token.0, L_PAREN | R_PAREN) => break, |
| 603 | + _ => { |
| 604 | + return Err(MigrateError::Unsafe(format!( |
| 605 | + "token drift: expected {:?}, found {token:?}", |
| 606 | + old_iter.peek() |
| 607 | + ))); |
| 608 | + } |
| 609 | + } |
| 610 | + } |
| 611 | + } |
| 612 | + if let Some(rest) = old_iter.peek() { |
| 613 | + return Err(MigrateError::Unsafe(format!( |
| 614 | + "token drift: {rest:?} was left out of the migration" |
| 615 | + ))); |
| 616 | + } |
| 617 | + let old_comments = format::comments_of(&old_root); |
| 618 | + let new_comments = format::comments_of(&new_root); |
| 619 | + if old_comments != new_comments { |
| 620 | + return Err(MigrateError::Unsafe(format!( |
| 621 | + "comment drift: {old_comments:?} vs {new_comments:?}" |
| 622 | + ))); |
| 623 | + } |
| 624 | + Ok(()) |
| 625 | +} |