flay-rs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3291 @@
1
+ //! Ruby2Ruby 2.6.2 (`ruby2ruby.rb`, on sexp_processor 4.17.6's
2
+ //! `SexpProcessor`): the Ruby source that Flay 2.14.5's `--diff` report
3
+ //! prints for each node.
4
+ //!
5
+ //! ```ruby
6
+ //! def sexp_to_rb sexp
7
+ //! @r2r ||= Ruby2Ruby.new
8
+ //! @r2r.process sexp.deep_clone
9
+ //! end
10
+ //! ```
11
+ //!
12
+ //! Flay reuses one `Ruby2Ruby` for the whole report, but nothing it keeps
13
+ //! between `process` calls changes the output: `context` is restored by
14
+ //! `in_context`'s `ensure` even when processing raises, `@calls` is only
15
+ //! pushed and popped, and `@unsupported_checked` only skips a check that
16
+ //! never raises for Ruby2Ruby. So every call here starts from a fresh state.
17
+ //!
18
+ //! [`sexp_to_ruby`] returns what `process` returns, or the exception it
19
+ //! raises (class and message), for any sexp of a translated tree or a copy
20
+ //! of one with some elements removed (Flay's fuzzy nodes).
21
+ //!
22
+ //! Ruby's default external encoding is taken to be UTF-8 (it decides how
23
+ //! `Symbol#inspect`, `String#inspect` and `Regexp#inspect` show non-ASCII
24
+ //! characters). Non-ASCII characters in encodings other than UTF-8 are
25
+ //! treated as single bytes, and `[[:print:]]` for non-ASCII Unicode
26
+ //! characters is approximated (see [`unicode_is_print`]).
27
+
28
+ use std::borrow::Cow;
29
+ use std::collections::HashMap;
30
+
31
+ use crate::ruby_format::float_to_s;
32
+ use crate::sexp::{Encoding, Integer, RubyString, SexpId, Tree, Value, ASCII_8BIT, UTF_8};
33
+ use crate::RubyException;
34
+
35
+ type Result<T> = std::result::Result<T, RubyException>;
36
+
37
+ /// `"#{a}#{b}..."`: the pieces concatenated as Ruby concatenates strings
38
+ /// (see [`Code::push_code`]); nil pieces add nothing.
39
+ macro_rules! interpolate {
40
+ ($($piece:expr),* $(,)?) => {{
41
+ let mut code = Code::default();
42
+ $( Piece::append_to(&$piece, &mut code)?; )*
43
+ code
44
+ }};
45
+ }
46
+
47
+ /// `Ruby2Ruby::LINE_LENGTH`: the cutoff for one-liners.
48
+ const LINE_LENGTH: usize = 78;
49
+
50
+ /// `Ruby2Ruby::BINARY`: binary operation messages.
51
+ const BINARY: &[&str] = &["<=>", "==", "<", ">", "<=", ">=", "-", "+", "*", "/", "%", "<<", ">>", "**", "!=", "^", "|", "&"];
52
+
53
+ /// `Ruby2Ruby::ASSIGN_NODES`: nodes that probably need () around them.
54
+ const ASSIGN_NODES: &[&str] = &[
55
+ "dasgn", "flip2", "flip3", "lasgn", "masgn", "match3", "attrasgn", "op_asgn1", "op_asgn2", "op_asgn_and",
56
+ "op_asgn_or", "return", "if", "rescue",
57
+ ];
58
+
59
+ /// `Ruby2Ruby::HASH_VAL_NO_PAREN`: hash values printed without parens.
60
+ const HASH_VAL_NO_PAREN: &[&str] = &["call", "false", "lit", "lvar", "nil", "str", "true"];
61
+
62
+ /// `Ruby2Ruby::MUST_BE_CURLY`.
63
+ const MUST_BE_CURLY: &[&str] = &["BEGIN", "END"];
64
+
65
+ /// `SexpProcessor#unsupported` as Ruby2Ruby leaves it.
66
+ const UNSUPPORTED: &[&str] = &["alloca", "cfunc", "cref", "ifunc", "last", "memo", "newline", "opt_n", "method"];
67
+
68
+ /// The indentation `Ruby2Ruby#indent` adds (`@indent`).
69
+ const INDENT: &str = " ";
70
+
71
+ /// `Flay#sexp_to_rb`: `Ruby2Ruby.new.process(sexp.deep_clone)` for the
72
+ /// sexp whose elements are `elements`.
73
+ ///
74
+ /// `node` is the tree sexp those elements were copied from: the sexp
75
+ /// itself, or the original of a fuzzy node (`tmpl + subcode` keeps the
76
+ /// original's `comments`). Every element below the top level is a sexp of
77
+ /// `tree`. `comments` holds the `comments` of `tree`'s sexps.
78
+ ///
79
+ /// The result's encoding is the encoding Ruby gives it when it has a
80
+ /// non-ASCII byte, and UTF-8 otherwise (Ruby's encoding for an ASCII-only
81
+ /// result varies, and does not show in Flay's report).
82
+ pub fn sexp_to_ruby(tree: &Tree, comments: &Comments, node: SexpId, elements: &[Value]) -> Result<RubyString> {
83
+ let mut ruby2ruby = Ruby2Ruby { tree, comments, context: Vec::new() };
84
+ let exp = Sexp {
85
+ elements: elements.iter().map(|value| ruby2ruby.element(value)).collect(),
86
+ comments: comments.of(node),
87
+ };
88
+ // SexpProcessor#process: a sexp processed with an empty context is
89
+ // rewritten first.
90
+ let exp = ruby2ruby.rewrite(exp)?;
91
+ let code = ruby2ruby.process_sexp(&exp)?;
92
+ Ok(RubyString::new(code.bytes, code.encoding.unwrap_or(UTF_8)))
93
+ }
94
+
95
+ /// The `comments` the translator attaches (`attach_comments`) to the
96
+ /// `class`, `module`, `defn` and `defs` sexps of one file's tree.
97
+ #[derive(Clone, Debug, Default)]
98
+ pub struct Comments {
99
+ by_sexp: HashMap<SexpId, RubyString>,
100
+ }
101
+
102
+ impl Comments {
103
+ /// The comments of `tree`, the translated tree of `source`.
104
+ pub fn new(source: &[u8], tree: &Tree) -> Comments {
105
+ let definition_starts = tree.definition_starts();
106
+ let node_starts: Vec<u32> = definition_starts.iter().map(|(_, start)| *start).collect();
107
+ let texts = crate::attach_comments::leading_comments(source, &node_starts);
108
+ let by_sexp = definition_starts
109
+ .iter()
110
+ .zip(texts)
111
+ .filter_map(|((sexp, _), text)| text.map(|text| (*sexp, text)))
112
+ .collect();
113
+ Comments { by_sexp }
114
+ }
115
+
116
+ fn of(&self, sexp: SexpId) -> Option<&RubyString> {
117
+ self.by_sexp.get(&sexp)
118
+ }
119
+ }
120
+
121
+ // -------------------------------------------------------------------------
122
+ // The sexp being processed
123
+
124
+ /// A copy of a sexp that Ruby2Ruby rewrites and processes (`deep_clone`):
125
+ /// its elements and `Sexp#comments`.
126
+ #[derive(Clone, Debug)]
127
+ struct Sexp<'t> {
128
+ elements: Vec<Element<'t>>,
129
+ comments: Option<&'t RubyString>,
130
+ }
131
+
132
+ /// One element of a [`Sexp`].
133
+ #[derive(Clone, Debug)]
134
+ enum Element<'t> {
135
+ Sexp(Sexp<'t>),
136
+ Symbol(Symbol<'t>),
137
+ Nil,
138
+ /// A String Ruby2Ruby builds (`process_defs`'s method name).
139
+ Text(Code),
140
+ /// Any other value of the tree: `true`, `false`, a String, a number, a
141
+ /// Range, a Regexp or a plain Array.
142
+ Value(&'t Value),
143
+ }
144
+
145
+ /// A Symbol: its bytes and encoding.
146
+ #[derive(Clone, Debug, PartialEq)]
147
+ struct Symbol<'t> {
148
+ bytes: Cow<'t, [u8]>,
149
+ encoding: Encoding,
150
+ }
151
+
152
+ impl<'t> Symbol<'t> {
153
+ /// A Symbol written in Ruby2Ruby's source (all ASCII).
154
+ fn named(name: &'static str) -> Self {
155
+ Symbol { bytes: Cow::Borrowed(name.as_bytes()), encoding: UTF_8 }
156
+ }
157
+
158
+ fn is(&self, name: &str) -> bool {
159
+ self.bytes.as_ref() == name.as_bytes()
160
+ }
161
+
162
+ fn is_any(&self, names: &[&str]) -> bool {
163
+ names.iter().any(|name| self.is(name))
164
+ }
165
+
166
+ /// `Symbol#to_s`.
167
+ fn to_code(&self) -> Code {
168
+ Code::new(self.bytes.to_vec(), self.encoding)
169
+ }
170
+ }
171
+
172
+ impl<'t> Sexp<'t> {
173
+ fn new(elements: Vec<Element<'t>>) -> Self {
174
+ Sexp { elements, comments: None }
175
+ }
176
+
177
+ /// The element at `index`, `None` for nil or past the end (what Ruby's
178
+ /// destructuring `_, a, b = exp` gives).
179
+ fn nth(&self, index: usize) -> Option<&Element<'t>> {
180
+ match self.elements.get(index) {
181
+ None | Some(Element::Nil) => None,
182
+ Some(element) => Some(element),
183
+ }
184
+ }
185
+
186
+ /// The elements from `index` on (`_, *rest = exp`).
187
+ fn rest(&self, index: usize) -> &[Element<'t>] {
188
+ self.elements.get(index..).unwrap_or(&[])
189
+ }
190
+
191
+ fn last(&self) -> Option<&Element<'t>> {
192
+ self.elements.last().filter(|element| !matches!(element, Element::Nil))
193
+ }
194
+
195
+ /// `sexp_type`, when it is a Symbol.
196
+ fn type_symbol(&self) -> Option<&Symbol<'t>> {
197
+ match self.elements.first() {
198
+ Some(Element::Symbol(symbol)) => Some(symbol),
199
+ _ => None,
200
+ }
201
+ }
202
+
203
+ /// `sexp_type == :name`.
204
+ fn is_type(&self, name: &str) -> bool {
205
+ self.type_symbol().is_some_and(|symbol| symbol.is(name))
206
+ }
207
+
208
+ /// `self == s(:name)`.
209
+ fn is_only(&self, name: &str) -> bool {
210
+ self.elements.len() == 1 && self.is_type(name)
211
+ }
212
+
213
+ /// `find_nodes(name)`: the indexes of the sexp children of type `name`.
214
+ fn find_nodes(&self, name: &str) -> Vec<usize> {
215
+ (0..self.elements.len())
216
+ .filter(|index| matches!(&self.elements[*index], Element::Sexp(sexp) if sexp.is_type(name)))
217
+ .collect()
218
+ }
219
+ }
220
+
221
+ /// `element == s(:name)`.
222
+ fn is_only(element: Option<&Element<'_>>, name: &str) -> bool {
223
+ matches!(element, Some(Element::Sexp(sexp)) if sexp.is_only(name))
224
+ }
225
+
226
+ /// Ruby truthiness: anything but nil and false.
227
+ fn truthy(element: Option<&Element<'_>>) -> bool {
228
+ !matches!(element, None | Some(Element::Nil) | Some(Element::Value(Value::False)))
229
+ }
230
+
231
+ // -------------------------------------------------------------------------
232
+ // The processor
233
+
234
+ /// `Ruby2Ruby` (a `SexpProcessor`) while it processes one sexp.
235
+ struct Ruby2Ruby<'t> {
236
+ tree: &'t Tree,
237
+ comments: &'t Comments,
238
+ /// `context`: the types of the sexps being rewritten or processed,
239
+ /// innermost last (`None` for a type that is not a Symbol).
240
+ context: Vec<Option<Symbol<'t>>>,
241
+ }
242
+
243
+ impl<'t> Ruby2Ruby<'t> {
244
+ /// A copy of a tree value (`deep_clone`).
245
+ fn element(&self, value: &'t Value) -> Element<'t> {
246
+ match value {
247
+ Value::Nil => Element::Nil,
248
+ Value::Symbol(id) => {
249
+ let (bytes, encoding) = self.tree.symbol(*id);
250
+ Element::Symbol(Symbol { bytes: Cow::Borrowed(bytes), encoding })
251
+ }
252
+ Value::Sexp(id) => Element::Sexp(Sexp {
253
+ elements: self.tree.get(*id).elements.iter().map(|value| self.element(value)).collect(),
254
+ comments: self.comments.of(*id),
255
+ }),
256
+ other => Element::Value(other),
257
+ }
258
+ }
259
+
260
+ /// `context[index]`: 0 is the innermost.
261
+ fn context_at(&self, index: usize) -> Option<&Symbol<'t>> {
262
+ let position = self.context.len().checked_sub(index + 1)?;
263
+ self.context[position].as_ref()
264
+ }
265
+
266
+ /// `context[index] == :name`.
267
+ fn context_is(&self, index: usize, name: &str) -> bool {
268
+ self.context_at(index).is_some_and(|symbol| symbol.is(name))
269
+ }
270
+
271
+ /// `case context[index] when /_pat$/`.
272
+ fn context_is_pattern(&self, index: usize) -> bool {
273
+ self.context_at(index).is_some_and(|symbol| matches_end_of_line(&symbol.bytes, b"_pat"))
274
+ }
275
+
276
+ // ---------------------------------------------------------------------
277
+ // Rewriting
278
+
279
+ /// `SexpProcessor#rewrite`: rewrites every sub-sexp first, then applies
280
+ /// the `rewrite_*` method for the sexp's type until the type stops
281
+ /// changing.
282
+ fn rewrite(&mut self, exp: Sexp<'t>) -> Result<Sexp<'t>> {
283
+ let mut sexp_type = exp.type_symbol().cloned();
284
+ let comments = exp.comments;
285
+
286
+ self.context.push(sexp_type.clone());
287
+ let mut elements = Vec::with_capacity(exp.elements.len());
288
+ let mut failure = None;
289
+ for sub in exp.elements {
290
+ match sub {
291
+ Element::Sexp(sexp) => match self.rewrite(sexp) {
292
+ Ok(sexp) => elements.push(Element::Sexp(sexp)),
293
+ Err(error) => {
294
+ failure = Some(error);
295
+ break;
296
+ }
297
+ },
298
+ // `rewrite` of a plain Array calls `sexp_type` on it.
299
+ Element::Value(Value::Array(_)) => {
300
+ failure = Some(no_method_error("sexp_type", "an instance of Array"));
301
+ break;
302
+ }
303
+ other => elements.push(other),
304
+ }
305
+ }
306
+ self.context.pop();
307
+ if let Some(error) = failure {
308
+ return Err(error);
309
+ }
310
+
311
+ let mut exp = Sexp { elements, comments };
312
+ loop {
313
+ exp = match sexp_type.as_ref().map(|symbol| symbol.bytes.as_ref()) {
314
+ Some(b"attrasgn") => self.rewrite_attrasgn(exp)?,
315
+ Some(b"call") => rewrite_call(exp),
316
+ Some(b"ensure") => self.rewrite_ensure(exp),
317
+ Some(b"if") => rewrite_if(exp)?,
318
+ Some(b"resbody") => self.rewrite_resbody(exp)?,
319
+ Some(b"rescue") => self.rewrite_rescue(exp)?,
320
+ Some(b"svalue") => self.rewrite_svalue(exp)?,
321
+ Some(b"until") => rewrite_until(exp)?,
322
+ Some(b"while") => rewrite_while(exp)?,
323
+ _ => exp,
324
+ };
325
+ let old_type = std::mem::replace(&mut sexp_type, exp.type_symbol().cloned());
326
+ if old_type == sexp_type {
327
+ break;
328
+ }
329
+ }
330
+ exp.comments = comments;
331
+ Ok(exp)
332
+ }
333
+
334
+ /// `Ruby2Ruby#rewrite_attrasgn`: an attribute assignment that is a
335
+ /// target of a multiple assignment becomes a call.
336
+ fn rewrite_attrasgn(&self, exp: Sexp<'t>) -> Result<Sexp<'t>> {
337
+ let in_masgn_array = self.context.len() >= 2 && self.context_is(0, "array") && self.context_is(1, "masgn");
338
+ if !in_masgn_array {
339
+ return Ok(exp);
340
+ }
341
+ // s(:call, recv, msg.to_s.chomp("=").to_sym, *args)
342
+ let message = to_s_element(self.tree, exp.nth(2))?;
343
+ let name = chomp_suffix(&message.bytes, b"=");
344
+ let symbol = Symbol { bytes: Cow::Owned(name.to_vec()), encoding: message.encoding.unwrap_or(UTF_8) };
345
+ let mut elements = vec![Element::Symbol(Symbol::named("call")), exp.elements.get(1).cloned().unwrap_or(Element::Nil)];
346
+ elements.push(Element::Symbol(symbol));
347
+ elements.extend(exp.rest(3).iter().cloned());
348
+ Ok(Sexp::new(elements))
349
+ }
350
+
351
+ /// `Ruby2Ruby#rewrite_ensure`: an `ensure` outside a `begin` gets one.
352
+ fn rewrite_ensure(&self, exp: Sexp<'t>) -> Sexp<'t> {
353
+ if self.context_is(0, "begin") {
354
+ exp
355
+ } else {
356
+ Sexp::new(vec![Element::Symbol(Symbol::named("begin")), Element::Sexp(exp)])
357
+ }
358
+ }
359
+
360
+ /// `Ruby2Ruby#rewrite_resbody`: checks the exception list.
361
+ fn rewrite_resbody(&self, exp: Sexp<'t>) -> Result<Sexp<'t>> {
362
+ let args = exp.nth(1);
363
+ if !(exp.elements.len() > 2 && truthy(args)) {
364
+ return Err(runtime_error(format!("no exception list in {}", inspect_sexp(self.tree, &exp))));
365
+ }
366
+ if !type_is(args, "array")? {
367
+ return Err(runtime_error(inspect_element(self.tree, args).lossy()));
368
+ }
369
+ Ok(exp)
370
+ }
371
+
372
+ /// `Ruby2Ruby#rewrite_rescue`: a complex `rescue` outside an `ensure`
373
+ /// is wrapped in a `begin`.
374
+ fn rewrite_rescue(&self, exp: Sexp<'t>) -> Result<Sexp<'t>> {
375
+ let mut complex = exp.elements.len() > 3;
376
+ if !complex {
377
+ // exp.resbody.block
378
+ let resbody = self.find_node(&exp, "resbody")?;
379
+ complex = match resbody {
380
+ Some(resbody) => self.find_node(resbody, "block")?.is_some(),
381
+ None => return Err(no_method_error("block", "nil")),
382
+ };
383
+ }
384
+ if !complex {
385
+ // exp.resbody.size > 3
386
+ if let Some(resbody) = self.find_node(&exp, "resbody")? {
387
+ complex = resbody.elements.len() > 3;
388
+ }
389
+ }
390
+ let resbodies: Vec<&Sexp<'t>> = exp.find_nodes("resbody").into_iter().map(|index| as_sexp(&exp.elements[index])).collect();
391
+ if !complex {
392
+ complex = resbodies.iter().any(|resbody| !is_only(resbody.nth(1), "array"));
393
+ }
394
+ if !complex {
395
+ complex = resbodies.iter().any(|resbody| resbody.last().is_none());
396
+ }
397
+ if !complex {
398
+ // body and body.node_type == :block: `node_type` is not a Sexp
399
+ // method, so `method_missing` finds no child of that type.
400
+ for resbody in &resbodies {
401
+ let body = resbody.nth(2);
402
+ if truthy(body) && !matches!(body, Some(Element::Sexp(_))) {
403
+ return Err(no_method_error("node_type", receiver_text(body)));
404
+ }
405
+ }
406
+ }
407
+ let handled = self.context_is(0, "ensure");
408
+ if complex && !handled {
409
+ Ok(Sexp::new(vec![Element::Symbol(Symbol::named("begin")), Element::Sexp(exp)]))
410
+ } else {
411
+ Ok(exp)
412
+ }
413
+ }
414
+
415
+ /// `Ruby2Ruby#rewrite_svalue`.
416
+ fn rewrite_svalue(&self, exp: Sexp<'t>) -> Result<Sexp<'t>> {
417
+ let last = exp.last();
418
+ if type_is(last, "array")? {
419
+ // s(:svalue, *exp[1].sexp_body)
420
+ let body = match exp.nth(1) {
421
+ Some(Element::Sexp(array)) => array.rest(1).to_vec(),
422
+ other => return Err(no_method_error("sexp_body", receiver_text(other))),
423
+ };
424
+ let mut elements = vec![Element::Symbol(Symbol::named("svalue"))];
425
+ elements.extend(body);
426
+ Ok(Sexp::new(elements))
427
+ } else if type_is(last, "splat")? {
428
+ Ok(exp)
429
+ } else {
430
+ Err(runtime_error(format!("huh: {}", inspect_sexp(self.tree, &exp))))
431
+ }
432
+ }
433
+
434
+ /// `Sexp#find_node(name)` (what `sexp.name` calls through
435
+ /// `method_missing`): the one child of type `name`, if any.
436
+ fn find_node<'a>(&self, sexp: &'a Sexp<'t>, name: &str) -> Result<Option<&'a Sexp<'t>>> {
437
+ match sexp.find_nodes(name).as_slice() {
438
+ [] => Ok(None),
439
+ [index] => Ok(Some(as_sexp(&sexp.elements[*index]))),
440
+ _ => Err(RubyException {
441
+ class: "NoMethodError",
442
+ message: format!("multiple nodes for {name} were found in {}", inspect_sexp(self.tree, sexp)),
443
+ }),
444
+ }
445
+ }
446
+
447
+ // ---------------------------------------------------------------------
448
+ // Processing
449
+
450
+ /// `SexpProcessor#process` (after rewriting): nil for nil, otherwise
451
+ /// the `process_*` method for the sexp's type.
452
+ fn process(&mut self, exp: Option<&Element<'t>>) -> Result<Option<Code>> {
453
+ match exp {
454
+ None | Some(Element::Nil) => Ok(None),
455
+ Some(Element::Sexp(sexp)) => self.process_sexp(sexp).map(Some),
456
+ Some(other) => Err(RubyException {
457
+ class: "SexpTypeError",
458
+ message: format!(
459
+ "exp must be a Sexp, was {}:{}",
460
+ class_name(Some(other)),
461
+ inspect_element(self.tree, Some(other))
462
+ ),
463
+ }),
464
+ }
465
+ }
466
+
467
+ /// `process` for a sexp: calls the `process_*` method for its type in
468
+ /// the context of that type.
469
+ fn process_sexp(&mut self, exp: &Sexp<'t>) -> Result<Code> {
470
+ let Some(sexp_type) = exp.type_symbol().cloned() else {
471
+ let first = exp.elements.first().filter(|element| !matches!(element, Element::Nil));
472
+ return Err(runtime_error(format!("type should be a Symbol, not: {}", inspect_element(self.tree, first))));
473
+ };
474
+ self.context.push(Some(sexp_type.clone()));
475
+ let result = self.dispatch(&sexp_type, exp);
476
+ self.context.pop();
477
+ result
478
+ }
479
+
480
+ /// The `process_*` method for `sexp_type` (strict: an unknown type
481
+ /// raises).
482
+ fn dispatch(&mut self, sexp_type: &Symbol<'t>, exp: &Sexp<'t>) -> Result<Code> {
483
+ let name = sexp_type.bytes.as_ref();
484
+ if UNSUPPORTED.iter().any(|unsupported| unsupported.as_bytes() == name) {
485
+ return Err(RubyException {
486
+ class: "UnsupportedNodeError",
487
+ message: format!("'{}' is not a supported node type", String::from_utf8_lossy(name)),
488
+ });
489
+ }
490
+ match name {
491
+ b"alias" => self.process_alias(exp),
492
+ b"and" => self.process_and(exp),
493
+ b"arglist" => self.process_arglist(exp),
494
+ b"args" => self.process_args(exp),
495
+ b"array" => self.process_array(exp),
496
+ b"attrasgn" => self.process_attrasgn(exp),
497
+ b"back_ref" => self.process_back_ref(exp),
498
+ b"begin" => self.process_begin(exp),
499
+ b"block" => self.process_block(exp),
500
+ b"block_pass" => self.process_block_pass(exp),
501
+ b"break" => self.process_break(exp),
502
+ b"call" => self.process_call(exp, false),
503
+ b"safe_call" => self.process_call(exp, true),
504
+ b"case" => self.process_case(exp),
505
+ b"cdecl" => self.process_cdecl(exp),
506
+ b"class" => self.process_class(exp),
507
+ b"colon2" => self.process_colon2(exp),
508
+ b"colon3" => self.process_colon3(exp),
509
+ b"const" => self.process_const(exp),
510
+ b"cvar" | b"gvar" | b"ivar" | b"lvar" => self.process_var(exp),
511
+ b"cvasgn" | b"cvdecl" => self.process_cvasgn(exp),
512
+ b"defined" => self.process_defined(exp),
513
+ b"defn" => self.process_defn(exp),
514
+ b"defs" => self.process_defs(exp),
515
+ b"dot2" => self.process_dot(exp, ".."),
516
+ b"dot3" => self.process_dot(exp, "..."),
517
+ b"dregx" => self.process_dregx(exp),
518
+ b"dregx_once" => self.process_dregx_once(exp),
519
+ b"dstr" => self.process_dstr(exp),
520
+ b"dsym" => self.process_dsym(exp),
521
+ b"dxstr" => self.process_dxstr(exp),
522
+ b"ensure" => self.process_ensure(exp),
523
+ b"evstr" => self.process_evstr(exp),
524
+ b"false" => Ok(Code::from("false")),
525
+ b"flip2" => self.process_flip(exp, ".."),
526
+ b"flip3" => self.process_flip(exp, "..."),
527
+ b"for" => self.process_for(exp),
528
+ b"forward_args" => Ok(Code::from("...")),
529
+ b"gasgn" | b"iasgn" => self.process_iasgn(exp),
530
+ b"hash" => self.process_hash(exp),
531
+ b"in" => self.process_in(exp),
532
+ b"find_pat" => self.process_find_pat(exp),
533
+ b"array_pat" => self.process_array_pat(exp),
534
+ b"kwrest" => self.process_kwrest(exp),
535
+ b"hash_pat" => self.process_hash_pat(exp),
536
+ b"preexe" => Ok(Code::from("BEGIN")),
537
+ b"if" => self.process_if(exp),
538
+ b"lambda" => Ok(Code::from("->")),
539
+ b"iter" => self.process_iter(exp),
540
+ b"kwsplat" => self.process_kwsplat(exp),
541
+ b"lasgn" => self.process_lasgn(exp),
542
+ b"lit" => self.process_lit(exp),
543
+ b"masgn" => self.process_masgn(exp),
544
+ b"match" => self.process_match(exp),
545
+ b"match2" => self.process_match2(exp),
546
+ b"match3" => self.process_match3(exp),
547
+ b"module" => self.process_module(exp),
548
+ b"next" => self.process_next(exp),
549
+ b"nil" => Ok(Code::from("nil")),
550
+ b"not" => self.process_not(exp),
551
+ b"nth_ref" => self.process_nth_ref(exp),
552
+ b"op_asgn" => self.process_op_asgn(exp),
553
+ b"op_asgn1" => self.process_op_asgn1(exp),
554
+ b"op_asgn2" => self.process_op_asgn2(exp, "."),
555
+ b"op_asgn_and" => self.process_op_asgn_and_or(exp, "&&="),
556
+ b"op_asgn_or" => self.process_op_asgn_and_or(exp, "||="),
557
+ b"or" => self.process_or(exp),
558
+ b"postexe" => Ok(Code::from("END")),
559
+ b"redo" => Ok(Code::from("redo")),
560
+ b"resbody" => self.process_resbody(exp),
561
+ b"rescue" => self.process_rescue(exp),
562
+ b"retry" => Ok(Code::from("retry")),
563
+ b"return" => self.process_return(exp),
564
+ b"safe_attrasgn" => self.process_safe_attrasgn(exp),
565
+ b"safe_op_asgn" => self.process_safe_op_asgn(exp),
566
+ b"safe_op_asgn2" => self.process_op_asgn2(exp, "&."),
567
+ b"sclass" => self.process_sclass(exp),
568
+ b"self" => Ok(Code::from("self")),
569
+ b"splat" => self.process_splat(exp),
570
+ b"str" => process_str(exp),
571
+ b"super" => self.process_super(exp),
572
+ b"svalue" => self.process_svalue(exp),
573
+ b"to_ary" => self.process_to_ary(exp),
574
+ b"true" => Ok(Code::from("true")),
575
+ b"undef" => self.process_undef(exp),
576
+ b"until" => self.cond_loop(exp, "until"),
577
+ b"valias" => self.process_valias(exp),
578
+ b"when" => self.process_when(exp),
579
+ b"while" => self.cond_loop(exp, "while"),
580
+ b"xstr" => process_xstr(exp),
581
+ b"yield" => self.process_yield(exp),
582
+ b"zsuper" => Ok(Code::from("super")),
583
+ b"dummy" => Err(not_ported("SexpProcessor#process_dummy")),
584
+ _ => Err(RubyException {
585
+ class: "UnknownNodeError",
586
+ message: format!(
587
+ "Bug! Unknown node-type {} to Ruby2Ruby",
588
+ inspect_symbol(&sexp_type.bytes, sexp_type.encoding).lossy()
589
+ ),
590
+ }),
591
+ }
592
+ }
593
+
594
+ /// `Ruby2Ruby#process_alias`.
595
+ fn process_alias(&mut self, exp: &Sexp<'t>) -> Result<Code> {
596
+ let lhs = self.process(exp.nth(1))?;
597
+ let rhs = self.process(exp.nth(2))?;
598
+ let code = interpolate!("alias ", lhs, " ", rhs);
599
+ self.parenthesize(code)
600
+ }
601
+
602
+ /// `Ruby2Ruby#process_and`.
603
+ fn process_and(&mut self, exp: &Sexp<'t>) -> Result<Code> {
604
+ let lhs = self.process(exp.nth(1))?;
605
+ let rhs = self.process(exp.nth(2))?;
606
+ let code = interpolate!(lhs, " and ", rhs);
607
+ self.parenthesize(code)
608
+ }
609
+
610
+ /// `Ruby2Ruby#process_arglist`: the arguments joined with ", ", a
611
+ /// `rescue` modifier in parens.
612
+ fn process_arglist(&mut self, exp: &Sexp<'t>) -> Result<Code> {
613
+ let mut args = Vec::new();
614
+ for arg in exp.rest(1) {
615
+ let arg = some(arg);
616
+ let code = self.process(arg)?;
617
+ if type_is(arg, "rescue")? {
618
+ args.push(Some(interpolate!("(", code, ")")));
619
+ } else {
620
+ args.push(code);
621
+ }
622
+ }
623
+ join(&args, ", ")
624
+ }
625
+
626
+ /// `Ruby2Ruby#process_args`: a parameter list in parens.
627
+ fn process_args(&mut self, exp: &Sexp<'t>) -> Result<Code> {
628
+ let mut args = Vec::new();
629
+ let mut shadow = Vec::new();
630
+ for arg in exp.rest(1) {
631
+ match arg {
632
+ Element::Symbol(symbol) => args.push(Some(symbol.to_code())),
633
+ Element::Sexp(sexp) => match sexp.type_symbol().map(|symbol| symbol.bytes.as_ref()) {
634
+ Some(b"lasgn") | Some(b"masgn") => args.push(Some(self.process_sexp(sexp)?)),
635
+ Some(b"kwarg") => {
636
+ let name = to_s_element(self.tree, sexp.nth(1))?;
637
+ let value = self.process(sexp.nth(2))?;
638
+ args.push(Some(interpolate!(name, ": ", value)));
639
+ }
640
+ Some(b"shadow") => shadow.push(join_flat(self.tree, sexp.rest(1), ", ")?),
641
+ Some(b"forward_args") => args.push(Some(Code::from("..."))),
642
+ _ => {
643
+ let first = sexp.elements.first().filter(|element| !matches!(element, Element::Nil));
644
+ return Err(runtime_error(format!("unknown arg type {}", inspect_element(self.tree, first))));
645
+ }
646
+ },
647
+ Element::Nil => args.push(Some(Code::default())),
648
+ other => {
649
+ return Err(runtime_error(format!("unknown arg type {}", inspect_element(self.tree, Some(other)))));
650
+ }
651
+ }
652
+ }
653
+
654
+ let args = strip(&join(&args, ", ")?);
655
+ let shadow: Vec<Option<Code>> = shadow.into_iter().map(Some).collect();
656
+ let mut shadow = strip(&join(&shadow, ", ")?);
657
+ if !shadow.bytes.is_empty() {
658
+ shadow = interpolate!("; ", shadow);
659
+ }
660
+ Ok(interpolate!("(", args, shadow, ")"))
661
+ }
662
+
663
+ /// `Ruby2Ruby#process_array`.
664
+ fn process_array(&mut self, exp: &Sexp<'t>) -> Result<Code> {
665
+ let args = self.process_arglist(exp)?;
666
+ Ok(interpolate!("[", args, "]"))
667
+ }
668
+
669
+ /// `Ruby2Ruby#process_attrasgn`: `recv[args] = rhs` or
670
+ /// `recv.name = rhs`.
671
+ fn process_attrasgn(&mut self, exp: &Sexp<'t>) -> Result<Code> {
672
+ let recv = exp.nth(1);
673
+ let name = exp.nth(2);
674
+ let mut args = exp.rest(3).to_vec();
675
+ let rhs = args.pop();
676
+ let rhs = rhs.as_ref().and_then(some);
677
+ let mut array = vec![Element::Symbol(Symbol::named("array"))];
678
+ array.extend(args);
679
+ let args = Sexp::new(array);
680
+ let receiver = self.process(recv)?;
681
+
682
+ if matches!(name, Some(Element::Symbol(symbol)) if symbol.is("[]=")) {
683
+ let args = self.process_sexp(&args)?;
684
+ let rhs = self.process(rhs)?;
685
+ return Ok(interpolate!(receiver, args, " = ", rhs));
686
+ }
687
+ if args.elements.len() != 1 {
688
+ return Err(runtime_error(format!("dunno what to do: {}", inspect_sexp(self.tree, &args))));
689
+ }
690
+ let name = to_s_element(self.tree, name)?;
691
+ let name = Code { bytes: chomp_suffix(&name.bytes, b"=").to_vec(), encoding: name.encoding };
692
+ if truthy(rhs) && !is_only(rhs, "arglist") {
693
+ let rhs = self.process(rhs)?;
694
+ Ok(interpolate!(receiver, ".", name, " = ", rhs))
695
+ } else {
696
+ Err(runtime_error(format!("dunno what to do: {}", inspect_element(self.tree, rhs))))
697
+ }
698
+ }
699
+
700
+ /// `Ruby2Ruby#process_back_ref`.
701
+ fn process_back_ref(&mut self, exp: &Sexp<'t>) -> Result<Code> {
702
+ let name = to_s_element(self.tree, exp.nth(1))?;
703
+ Ok(interpolate!("$", name))
704
+ }
705
+
706
+ /// `Ruby2Ruby#process_begin`: each statement indented unless it has a
707
+ /// line starting with `rescue` or `ensure`, between `begin` and `end`.
708
+ fn process_begin(&mut self, exp: &Sexp<'t>) -> Result<Code> {
709
+ let mut code = vec![Some(Code::from("begin"))];
710
+ for sexp in exp.rest(1) {
711
+ let src = self.process(some(sexp))?;
712
+ let at_level_zero = match &src {
713
+ Some(src) => {
714
+ check_regexp_target(src)?;
715
+ has_line_starting_with(&src.bytes, b"rescue") || has_line_starting_with(&src.bytes, b"ensure")
716
+ }
717
+ None => false,
718
+ };
719
+ code.push(Some(if at_level_zero { src.unwrap_or_default() } else { indent(src.as_ref())? }));
720
+ }
721
+ code.push(Some(Code::from("end")));
722
+ join(&code, "\n")
723
+ }
724
+
725
+ /// `Ruby2Ruby#process_block`: the statements on separate lines.
726
+ fn process_block(&mut self, exp: &Sexp<'t>) -> Result<Code> {
727
+ let mut result = Vec::new();
728
+ for sexp in exp.rest(1) {
729
+ result.push(self.process(some(sexp))?);
730
+ }
731
+ if result.is_empty() {
732
+ result.push(Some(Code::from("# do nothing\n")));
733
+ }
734
+ let mut result = self.parenthesize(join(&result, "\n")?)?;
735
+ if !result.bytes.starts_with(b"(") {
736
+ result.push_str("\n");
737
+ }
738
+ Ok(result)
739
+ }
740
+
741
+ /// `Ruby2Ruby#process_block_pass`.
742
+ fn process_block_pass(&mut self, exp: &Sexp<'t>) -> Result<Code> {
743
+ if exp.elements.len() > 2 {
744
+ return Err(runtime_error(format!("huh?: {}", inspect_sexp(self.tree, exp))));
745
+ }
746
+ let code = self.process(exp.nth(1))?;
747
+ Ok(interpolate!("&", code))
748
+ }
749
+
750
+ /// `Ruby2Ruby#process_break`.
751
+ fn process_break(&mut self, exp: &Sexp<'t>) -> Result<Code> {
752
+ match self.process(exp.nth(1))? {
753
+ Some(value) => Ok(interpolate!("break ", value)),
754
+ None => Ok(Code::from("break")),
755
+ }
756
+ }
757
+
758
+ /// `Ruby2Ruby#process_call` (and `process_safe_call`).
759
+ fn process_call(&mut self, exp: &Sexp<'t>, safe_call: bool) -> Result<Code> {
760
+ let recv = exp.nth(1);
761
+ let name = exp.nth(2);
762
+ let args = exp.rest(3);
763
+
764
+ let receiver_node_type = if truthy(recv) { sexp_type(recv)? } else { None };
765
+ let mut receiver = self.process(recv)?;
766
+ if is_symbol_in(receiver_node_type, ASSIGN_NODES) {
767
+ receiver = Some(interpolate!("(", receiver, ")"));
768
+ }
769
+
770
+ self.context.push(Some(Symbol::named("arglist")));
771
+ let processed = self.process_call_args(args, name);
772
+ self.context.pop();
773
+ let mut args: Vec<Code> = processed?.into_iter().flatten().collect();
774
+
775
+ let name_is = |candidate: &str| matches!(name, Some(Element::Symbol(symbol)) if symbol.is(candidate));
776
+ let name_text = to_s_element(self.tree, name)?;
777
+ if BINARY.iter().any(|operator| name_is(operator)) {
778
+ let joined = join_codes(&args, ", ")?;
779
+ if safe_call {
780
+ Ok(interpolate!(receiver, "&.", name_text, "(", joined, ")"))
781
+ } else if args.len() > 1 {
782
+ Ok(interpolate!(receiver, ".", name_text, "(", joined, ")"))
783
+ } else {
784
+ Ok(interpolate!("(", receiver, " ", name_text, " ", joined, ")"))
785
+ }
786
+ } else if name_is("[]") {
787
+ let receiver = receiver.unwrap_or_else(|| Code::from("self"));
788
+ let joined = join_codes(&args, ", ")?;
789
+ Ok(interpolate!(receiver, "[", joined, "]"))
790
+ } else if name_is("[]=") {
791
+ let receiver = receiver.unwrap_or_else(|| Code::from("self"));
792
+ let rhs = args.pop();
793
+ let joined = join_codes(&args, ", ")?;
794
+ Ok(interpolate!(receiver, "[", joined, "] = ", rhs))
795
+ } else if name_is("!") {
796
+ Ok(interpolate!("(not ", receiver, ")"))
797
+ } else if name_is("-@") {
798
+ Ok(interpolate!("-", receiver))
799
+ } else if name_is("+@") {
800
+ Ok(interpolate!("+", receiver))
801
+ } else {
802
+ let args = if args.is_empty() { None } else { Some(interpolate!("(", join_codes(&args, ", ")?, ")")) };
803
+ let receiver = match receiver {
804
+ Some(receiver) if safe_call => Some(interpolate!(receiver, "&.")),
805
+ Some(receiver) => Some(interpolate!(receiver, ".")),
806
+ None => None,
807
+ };
808
+ Ok(interpolate!(receiver, name_text, args))
809
+ }
810
+ }
811
+
812
+ /// The `args.map.with_index` of `process_call`, in the `:arglist`
813
+ /// context: each argument processed, a trailing hash without braces, an
814
+ /// assignment in parens, nil (dropped) for an empty one.
815
+ fn process_call_args(&mut self, args: &[Element<'t>], name: Option<&Element<'t>>) -> Result<Vec<Option<Code>>> {
816
+ let binary = matches!(name, Some(Element::Symbol(symbol)) if symbol.is_any(BINARY));
817
+ let mut result = Vec::with_capacity(args.len());
818
+ for (index, arg) in args.iter().enumerate() {
819
+ let arg = some(arg);
820
+ let arg_type = sexp_type(arg)?;
821
+ let is_empty_hash = is_only(arg, "hash");
822
+ let Some(code) = self.process(arg)? else {
823
+ return Err(no_method_error("empty?", "nil"));
824
+ };
825
+ if code.bytes.is_empty() {
826
+ result.push(None);
827
+ continue;
828
+ }
829
+ let arg_is_hash = is_symbol_in(arg_type, &["hash"]);
830
+ let strip_hash = arg_is_hash
831
+ && !binary
832
+ && !is_empty_hash
833
+ && (index == args.len() - 1 || type_is(some(&args[index + 1]), "splat")?);
834
+ let wrap_arg = is_symbol_in(arg_type, ASSIGN_NODES);
835
+
836
+ let mut code = Some(code);
837
+ if strip_hash {
838
+ code = code.and_then(|code| code.slice(2, -3));
839
+ }
840
+ if wrap_arg {
841
+ code = Some(interpolate!("(", code, ")"));
842
+ }
843
+ result.push(code);
844
+ }
845
+ Ok(result)
846
+ }
847
+
848
+ /// `Ruby2Ruby#process_case`.
849
+ fn process_case(&mut self, exp: &Sexp<'t>) -> Result<Code> {
850
+ let expr = self.process(exp.nth(1))?;
851
+ let mut result = vec![Some(match expr {
852
+ Some(expr) => interpolate!("case ", expr),
853
+ None => Code::from("case"),
854
+ })];
855
+ for pt in exp.rest(2) {
856
+ let pt = some(pt);
857
+ if truthy(pt) && is_symbol_in(sexp_type(pt)?, &["when", "in"]) {
858
+ result.push(self.process(pt)?);
859
+ } else {
860
+ if !truthy(pt) {
861
+ continue;
862
+ }
863
+ let processed = self.process(pt)?;
864
+ let mut code = indent(processed.as_ref())?;
865
+ check_regexp_target(&code)?;
866
+ if has_blank_line(&code.bytes) {
867
+ code = indent(Some(&Code::from("# do nothing")))?;
868
+ }
869
+ result.push(Some(interpolate!("else\n", code)));
870
+ }
871
+ }
872
+ result.push(Some(Code::from("end")));
873
+ let result: Vec<Option<Code>> = result.into_iter().filter(Option::is_some).collect();
874
+ join(&result, "\n")
875
+ }
876
+
877
+ /// `Ruby2Ruby#process_cdecl`.
878
+ fn process_cdecl(&mut self, exp: &Sexp<'t>) -> Result<Code> {
879
+ let lhs = match exp.nth(1) {
880
+ lhs @ Some(Element::Sexp(_)) => self.process(lhs)?.unwrap_or_default(),
881
+ lhs => to_s_element(self.tree, lhs)?,
882
+ };
883
+ let rhs = exp.nth(2);
884
+ if truthy(rhs) {
885
+ let rhs = self.process(rhs)?;
886
+ Ok(interpolate!(lhs, " = ", rhs))
887
+ } else {
888
+ Ok(lhs)
889
+ }
890
+ }
891
+
892
+ /// `Ruby2Ruby#comments`: the sexp's comments ending in a newline.
893
+ fn comments(&self, exp: &Sexp<'t>) -> Option<Code> {
894
+ let comments = exp.comments?;
895
+ let mut code = Code::new(comments.bytes.clone(), comments.encoding);
896
+ if !code.bytes.ends_with(b"\n") {
897
+ code.push_str("\n");
898
+ }
899
+ Some(code)
900
+ }
901
+
902
+ /// `Ruby2Ruby#process_class`.
903
+ fn process_class(&mut self, exp: &Sexp<'t>) -> Result<Code> {
904
+ let comments = self.comments(exp);
905
+ let class = self.util_module_or_class(exp, true)?;
906
+ Ok(interpolate!(comments, "class ", class))
907
+ }
908
+
909
+ /// `Ruby2Ruby#process_colon2`.
910
+ fn process_colon2(&mut self, exp: &Sexp<'t>) -> Result<Code> {
911
+ let lhs = self.process(exp.nth(1))?;
912
+ let rhs = to_s_element(self.tree, exp.nth(2))?;
913
+ Ok(interpolate!(lhs, "::", rhs))
914
+ }
915
+
916
+ /// `Ruby2Ruby#process_colon3`.
917
+ fn process_colon3(&mut self, exp: &Sexp<'t>) -> Result<Code> {
918
+ let rhs = to_s_element(self.tree, exp.nth(1))?;
919
+ Ok(interpolate!("::", rhs))
920
+ }
921
+
922
+ /// `Ruby2Ruby#process_const`.
923
+ fn process_const(&mut self, exp: &Sexp<'t>) -> Result<Code> {
924
+ match exp.nth(1) {
925
+ name @ Some(Element::Sexp(_)) => Ok(self.process(name)?.unwrap_or_default()),
926
+ name => to_s_element(self.tree, name),
927
+ }
928
+ }
929
+
930
+ /// `Ruby2Ruby#process_cvar`, `process_gvar`, `process_ivar` and
931
+ /// `process_lvar`, through `__var`: the name, pinned (`^name`) in a
932
+ /// pattern.
933
+ fn process_var(&mut self, exp: &Sexp<'t>) -> Result<Code> {
934
+ let name = to_s_element(self.tree, exp.nth(1))?;
935
+ if self.context_is_pattern(1) || self.context_is(1, "in") {
936
+ Ok(interpolate!("^", name))
937
+ } else {
938
+ Ok(name)
939
+ }
940
+ }
941
+
942
+ /// `Ruby2Ruby#process_cvasgn` and `process_cvdecl`.
943
+ fn process_cvasgn(&mut self, exp: &Sexp<'t>) -> Result<Code> {
944
+ let lhs = to_s_element(self.tree, exp.nth(1))?;
945
+ let rhs = self.process(exp.nth(2))?;
946
+ Ok(interpolate!(lhs, " = ", rhs))
947
+ }
948
+
949
+ /// `Ruby2Ruby#process_defined`.
950
+ fn process_defined(&mut self, exp: &Sexp<'t>) -> Result<Code> {
951
+ let rhs = self.process(exp.nth(1))?;
952
+ if self.context_is(1, "if") {
953
+ Ok(interpolate!("defined?(", rhs, ")"))
954
+ } else {
955
+ Ok(interpolate!("defined? ", rhs))
956
+ }
957
+ }
958
+
959
+ /// `Ruby2Ruby#process_defn`.
960
+ fn process_defn(&mut self, exp: &Sexp<'t>) -> Result<Code> {
961
+ let name = exp.nth(1);
962
+ let mut body: Vec<Element<'t>> = exp.rest(3).to_vec();
963
+
964
+ let comm = self.comments(exp);
965
+ let mut args = self.process(exp.nth(2))?;
966
+ if args.as_ref().is_some_and(|args| args.bytes == b"()") {
967
+ args = Some(Code::default());
968
+ }
969
+
970
+ // empty it out of a default nil expression
971
+ if body.len() == 1 && is_only(some(&body[0]), "nil") {
972
+ body.clear();
973
+ }
974
+
975
+ // `case exp when s{ q(...) }`: Sexp::Matcher#=== also matches any
976
+ // sub-sexp, but the code below reads the method's own body.
977
+ if matches_anywhere(exp, &is_ivar_reader) {
978
+ let ivar = body.first().and_then(|first| match first {
979
+ Element::Sexp(sexp) => sexp.nth(1),
980
+ _ => None,
981
+ });
982
+ let ivar = to_s_element(self.tree, ivar)?.slice(1, -1);
983
+ let reader = to_s_element(self.tree, name)?;
984
+ if ivar.is_some_and(|ivar| ivar.bytes == reader.bytes) {
985
+ let name = inspect_element(self.tree, name);
986
+ return Ok(interpolate!("attr_reader ", name));
987
+ }
988
+ } else if matches_anywhere(exp, &is_ivar_writer) {
989
+ let ivar = body.first().and_then(|first| match first {
990
+ Element::Sexp(sexp) => sexp.nth(1),
991
+ _ => None,
992
+ });
993
+ let ivar = to_s_element(self.tree, ivar)?.slice(1, -1);
994
+ let reader = to_s_element(self.tree, name)?;
995
+ let reader = Code { bytes: chomp_suffix(&reader.bytes, b"=").to_vec(), encoding: reader.encoding };
996
+ if ivar.is_some_and(|ivar| ivar.bytes == reader.bytes) {
997
+ return Ok(interpolate!("attr_writer :", reader));
998
+ }
999
+ }
1000
+
1001
+ let mut processed = Vec::with_capacity(body.len());
1002
+ for sexp in &body {
1003
+ processed.push(self.process(some(sexp))?);
1004
+ }
1005
+ let simple = processed.len() <= 1;
1006
+ if processed.is_empty() {
1007
+ processed.push(Some(Code::from("# do nothing")));
1008
+ }
1009
+ let mut body = join(&processed, "\n")?;
1010
+ check_regexp_target(&body)?;
1011
+ if simple && body.bytes.starts_with(b"begin") && is_line_at_end(&body.bytes, b"end") {
1012
+ // body.lines.to_a[1..-2].join("\n")
1013
+ let lines = lines(&body.bytes);
1014
+ let inner = if lines.len() >= 2 { &lines[1..lines.len() - 1] } else { &[][..] };
1015
+ let inner: Vec<Option<Code>> =
1016
+ inner.iter().map(|line| Some(Code { bytes: line.to_vec(), encoding: body.encoding })).collect();
1017
+ body = join(&inner, "\n")?;
1018
+ }
1019
+ if !(simple && has_line_starting_with(&body.bytes, b"rescue")) {
1020
+ body = indent(Some(&body))?;
1021
+ }
1022
+
1023
+ let name = to_s_element(self.tree, name)?;
1024
+ let code = interpolate!(comm, "def ", name, args, "\n", body, "\nend");
1025
+ check_regexp_target(&code)?;
1026
+ Ok(Code { bytes: squeeze_blank_lines(&code.bytes), encoding: code.encoding })
1027
+ }
1028
+
1029
+ /// `Ruby2Ruby#process_defs`: `process_defn` with the name
1030
+ /// `receiver.name`.
1031
+ fn process_defs(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1032
+ let lhs = exp.nth(1);
1033
+ let var = is_symbol_in(sexp_type(lhs)?, &["self", "cvar", "dvar", "ivar", "gvar", "lvar"]);
1034
+ let mut lhs = self.process(lhs)?;
1035
+ if !var {
1036
+ lhs = Some(interpolate!("(", lhs, ")"));
1037
+ }
1038
+ let name = to_s_element(self.tree, exp.nth(2))?;
1039
+ let name = interpolate!(lhs, ".", name);
1040
+ let mut elements = vec![
1041
+ Element::Symbol(Symbol::named("defn")),
1042
+ Element::Text(name),
1043
+ exp.elements.get(3).cloned().unwrap_or(Element::Nil),
1044
+ ];
1045
+ elements.extend(exp.rest(4).iter().cloned());
1046
+ self.process_defn(&Sexp::new(elements))
1047
+ }
1048
+
1049
+ /// `Ruby2Ruby#process_dot2` and `process_dot3`.
1050
+ fn process_dot(&mut self, exp: &Sexp<'t>, operator: &str) -> Result<Code> {
1051
+ let lhs = self.process(exp.nth(1))?;
1052
+ let rhs = self.process(exp.nth(2))?;
1053
+ Ok(interpolate!("(", lhs, operator, rhs, ")"))
1054
+ }
1055
+
1056
+ /// `Ruby2Ruby#process_dregx`: `/.../` with the options a trailing
1057
+ /// Integer gives.
1058
+ fn process_dregx(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1059
+ let mut rest = exp.rest(2).to_vec();
1060
+ let options = match rest.last() {
1061
+ Some(Element::Value(Value::Integer(options))) => {
1062
+ let options = re_opt(options);
1063
+ rest.pop();
1064
+ Some(options)
1065
+ }
1066
+ _ => None,
1067
+ };
1068
+ let mut elements = vec![Element::Symbol(Symbol::named("dregx")), exp.elements.get(1).cloned().unwrap_or(Element::Nil)];
1069
+ elements.extend(rest);
1070
+ let body = self.util_dthing(DthingType::Dregx, &Sexp::new(elements))?;
1071
+ Ok(interpolate!("/", body, "/", options))
1072
+ }
1073
+
1074
+ /// `Ruby2Ruby#process_dregx_once`.
1075
+ fn process_dregx_once(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1076
+ let code = self.process_dregx(exp)?;
1077
+ Ok(interpolate!(code, "o"))
1078
+ }
1079
+
1080
+ /// `Ruby2Ruby#process_dstr`.
1081
+ fn process_dstr(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1082
+ let body = self.util_dthing(DthingType::Dstr, exp)?;
1083
+ Ok(interpolate!("\"", body, "\""))
1084
+ }
1085
+
1086
+ /// `Ruby2Ruby#process_dsym`.
1087
+ fn process_dsym(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1088
+ let body = self.util_dthing(DthingType::Dsym, exp)?;
1089
+ Ok(interpolate!(":\"", body, "\""))
1090
+ }
1091
+
1092
+ /// `Ruby2Ruby#process_dxstr`.
1093
+ fn process_dxstr(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1094
+ let body = self.util_dthing(DthingType::Dxstr, exp)?;
1095
+ Ok(interpolate!("`", body, "`"))
1096
+ }
1097
+
1098
+ /// `Ruby2Ruby#process_ensure`.
1099
+ fn process_ensure(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1100
+ let body = self.process(exp.nth(1))?;
1101
+ let ens = if is_only(exp.nth(2), "nil") { None } else { exp.nth(2) };
1102
+ let mut ens = self.process(ens)?.unwrap_or_else(|| Code::from("# do nothing"));
1103
+ check_regexp_target(&ens)?;
1104
+ if has_line_starting_with(&ens.bytes, b"rescue") {
1105
+ ens = interpolate!("begin\n", ens, "\nend\n");
1106
+ }
1107
+ let Some(body) = body else {
1108
+ return Err(no_method_error("sub", "nil"));
1109
+ };
1110
+ check_regexp_target(&body)?;
1111
+ let mut body = Code { bytes: remove_trailing_end(&body.bytes), encoding: body.encoding };
1112
+ if !has_line_starting_with(&body.bytes, b"rescue") {
1113
+ body = indent(Some(&body))?;
1114
+ }
1115
+ let ens = indent(Some(&ens))?;
1116
+ Ok(interpolate!(body, "\nensure\n", ens))
1117
+ }
1118
+
1119
+ /// `Ruby2Ruby#process_evstr`.
1120
+ fn process_evstr(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1121
+ let x = exp.nth(1);
1122
+ if truthy(x) {
1123
+ Ok(self.process(x)?.unwrap_or_default())
1124
+ } else {
1125
+ Ok(Code::default())
1126
+ }
1127
+ }
1128
+
1129
+ /// `Ruby2Ruby#process_flip2` and `process_flip3`.
1130
+ fn process_flip(&mut self, exp: &Sexp<'t>, operator: &str) -> Result<Code> {
1131
+ let lhs = self.process(exp.nth(1))?;
1132
+ let rhs = self.process(exp.nth(2))?;
1133
+ Ok(interpolate!(lhs, operator, rhs))
1134
+ }
1135
+
1136
+ /// `Ruby2Ruby#process_for`.
1137
+ fn process_for(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1138
+ let recv = self.process(exp.nth(1))?;
1139
+ let iter = self.process(exp.nth(2))?;
1140
+ let body = self.process(exp.nth(3))?.unwrap_or_else(|| Code::from("# do nothing"));
1141
+ let body = indent(Some(&body))?;
1142
+ Ok(interpolate!("for ", iter, " in ", recv, " do\n", body, "\nend"))
1143
+ }
1144
+
1145
+ /// `Ruby2Ruby#process_hash`.
1146
+ fn process_hash(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1147
+ let pairs = exp.rest(1);
1148
+ let mut result = Vec::new();
1149
+ for pair in pairs.chunks(2) {
1150
+ let k = some(&pair[0]);
1151
+ let v = pair.get(1).and_then(some);
1152
+ if type_is(k, "kwsplat")? {
1153
+ result.push(Some(self.process(k)?.unwrap_or_default()));
1154
+ } else if v.is_none() {
1155
+ // Shorthand hash syntax
1156
+ let value = if type_is(k, "lit")? { Some(sexp_value(k)?) } else { None };
1157
+ let symbol_value = match value {
1158
+ Some(Some(Element::Symbol(symbol))) => symbol.to_code(),
1159
+ _ => {
1160
+ return Err(runtime_error(format!(
1161
+ "Expected symbol for hash key, but got {}",
1162
+ inspect_element(self.tree, k)
1163
+ )));
1164
+ }
1165
+ };
1166
+ result.push(Some(interpolate!(symbol_value, ":")));
1167
+ } else {
1168
+ let t = sexp_type(v)?;
1169
+ let lhs = self.process(k)?;
1170
+ let mut rhs = self.process(v)?;
1171
+ if !is_symbol_in(t, HASH_VAL_NO_PAREN) {
1172
+ rhs = Some(interpolate!("(", rhs, ")"));
1173
+ }
1174
+ result.push(Some(interpolate!(lhs, " => ", rhs)));
1175
+ }
1176
+ }
1177
+ if result.is_empty() {
1178
+ Ok(Code::from("{}"))
1179
+ } else {
1180
+ let joined = join(&result, ", ")?;
1181
+ Ok(interpolate!("{ ", joined, " }"))
1182
+ }
1183
+ }
1184
+
1185
+ /// `Ruby2Ruby#process_iasgn` (and `process_gasgn`).
1186
+ fn process_iasgn(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1187
+ let lhs = to_s_element(self.tree, exp.nth(1))?;
1188
+ let rhs = exp.nth(2);
1189
+ if truthy(rhs) {
1190
+ let rhs = self.process(rhs)?;
1191
+ Ok(interpolate!(lhs, " = ", rhs))
1192
+ } else {
1193
+ Ok(lhs)
1194
+ }
1195
+ }
1196
+
1197
+ /// `Ruby2Ruby#process_in`.
1198
+ fn process_in(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1199
+ let cond = self.process(exp.nth(1))?;
1200
+ let mut body = Vec::new();
1201
+ for sexp in exp.rest(2).iter().filter(|sexp| !matches!(sexp, Element::Nil)) {
1202
+ self.context.push(Some(Symbol::named("in_body")));
1203
+ let processed = self.process(Some(sexp));
1204
+ self.context.pop();
1205
+ body.push(Some(indent(processed?.as_ref())?));
1206
+ }
1207
+ if body.is_empty() {
1208
+ body.push(Some(indent(Some(&Code::from("# do nothing")))?));
1209
+ }
1210
+ let body = chomp(&join(&body, "\n")?);
1211
+ Ok(interpolate!("in ", cond, " then\n", body))
1212
+ }
1213
+
1214
+ /// `Ruby2Ruby#process_find_pat`.
1215
+ fn process_find_pat(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1216
+ // _, a, b, *c, d = exp
1217
+ let elements = &exp.elements;
1218
+ let a = exp.nth(1);
1219
+ let b = exp.nth(2);
1220
+ let (c, d) = if elements.len() >= 4 {
1221
+ (&elements[3..elements.len() - 1], exp.nth(elements.len() - 1))
1222
+ } else {
1223
+ (&[][..], None)
1224
+ };
1225
+
1226
+ let a = self.process(a)?;
1227
+ let b = self.process_sexp_else_to_s(b)?;
1228
+ let mut middle = Vec::with_capacity(c.len());
1229
+ for sexp in c {
1230
+ middle.push(self.process(some(sexp))?);
1231
+ }
1232
+ let c = join(&middle, ", ")?;
1233
+ let d = self.process_sexp_else_to_s(d)?;
1234
+ Ok(interpolate!(a, "[", b, ", ", c, ", ", d, "]"))
1235
+ }
1236
+
1237
+ /// `x = process x if Sexp === x`, then `x.to_s`.
1238
+ fn process_sexp_else_to_s(&mut self, element: Option<&Element<'t>>) -> Result<Code> {
1239
+ match element {
1240
+ Some(Element::Sexp(_)) => Ok(self.process(element)?.unwrap_or_default()),
1241
+ other => to_s_element(self.tree, other),
1242
+ }
1243
+ }
1244
+
1245
+ /// `Ruby2Ruby#process_array_pat`.
1246
+ fn process_array_pat(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1247
+ let const_ = exp.nth(1);
1248
+ let const_ = if truthy(const_) { self.process(const_)? } else { to_s_or_nil(self.tree, const_)? };
1249
+ let mut rest = Vec::new();
1250
+ for sexp in exp.rest(2) {
1251
+ rest.push(Some(self.process_sexp_else_to_s(some(sexp))?));
1252
+ }
1253
+ let rest = join(&rest, ", ")?;
1254
+ Ok(interpolate!(const_, "[", rest, "]"))
1255
+ }
1256
+
1257
+ /// `Ruby2Ruby#process_kwrest`.
1258
+ fn process_kwrest(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1259
+ to_s_element(self.tree, exp.nth(1))
1260
+ }
1261
+
1262
+ /// `Ruby2Ruby#process_hash_pat`.
1263
+ fn process_hash_pat(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1264
+ let const_ = exp.nth(1);
1265
+ let mut rest = exp.rest(2).to_vec();
1266
+ let const_ = if truthy(const_) { Some(self.process(const_)?.unwrap_or_default()) } else { None };
1267
+
1268
+ let mut kwrest = None;
1269
+ let last = rest.last().and_then(some);
1270
+ if truthy(last) && type_is(last, "kwrest")? {
1271
+ let last = rest.pop();
1272
+ kwrest = self.process(last.as_ref().and_then(some))?;
1273
+ }
1274
+ let mut pairs = Vec::new();
1275
+ for pair in rest.chunks(2) {
1276
+ let Some(k) = self.process(some(&pair[0]))? else {
1277
+ return Err(no_method_error("delete_prefix", "nil"));
1278
+ };
1279
+ let k = Code { bytes: k.bytes.strip_prefix(b":").unwrap_or(&k.bytes).to_vec(), encoding: k.encoding };
1280
+ let v = self.process(pair.get(1).and_then(some))?;
1281
+ pairs.push(Some(strip(&interpolate!(k, ": ", v))));
1282
+ }
1283
+ if kwrest.is_some() {
1284
+ pairs.push(kwrest);
1285
+ }
1286
+
1287
+ match const_ {
1288
+ Some(const_) if pairs.is_empty() => Ok(interpolate!(const_, "[]")),
1289
+ Some(const_) => {
1290
+ let joined = join(&pairs, ", ")?;
1291
+ Ok(interpolate!(const_, "[", joined, "]"))
1292
+ }
1293
+ None if pairs.is_empty() => Ok(Code::from("{}")),
1294
+ None => {
1295
+ let joined = join(&pairs, ", ")?;
1296
+ Ok(interpolate!("{ ", joined, " }"))
1297
+ }
1298
+ }
1299
+ }
1300
+
1301
+ /// `Ruby2Ruby#process_if`: a one-liner (`t if c`, `c ? (t) : (f)`,
1302
+ /// `f unless c`) when it fits, otherwise `if`/`unless` blocks.
1303
+ fn process_if(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1304
+ let c = exp.nth(1);
1305
+ let expand = is_symbol_in(sexp_type(c)?, ASSIGN_NODES);
1306
+ let c = self.process(c)?;
1307
+ let t = self.process(exp.nth(2))?;
1308
+ let f = self.process(exp.nth(3))?;
1309
+
1310
+ let mut c = c.unwrap_or_default();
1311
+ check_regexp_target(&c)?;
1312
+ if c.bytes.contains(&b'\n') {
1313
+ c = interpolate!("(", chomp(&c), ")");
1314
+ }
1315
+
1316
+ if let Some(t) = t {
1317
+ if !expand {
1318
+ let r = match &f {
1319
+ Some(f) => {
1320
+ let r = interpolate!(c, " ? (", t, ") : (", f, ")");
1321
+ check_regexp_target(&r)?;
1322
+ if contains(&r.bytes, b"return") {
1323
+ None
1324
+ } else {
1325
+ Some(r)
1326
+ }
1327
+ }
1328
+ None => Some(interpolate!(t, " if ", c)),
1329
+ };
1330
+ if let Some(r) = r {
1331
+ check_regexp_target(&r)?;
1332
+ if INDENT.len() + r.char_count() < LINE_LENGTH && !r.bytes.contains(&b'\n') {
1333
+ return Ok(r);
1334
+ }
1335
+ }
1336
+ }
1337
+ let t = indent(Some(&t))?;
1338
+ let mut r = interpolate!("if ", c, " then\n", t, "\n");
1339
+ if let Some(f) = f {
1340
+ let f = indent(Some(&f))?;
1341
+ r = interpolate!(r, "else\n", f, "\n");
1342
+ }
1343
+ Ok(interpolate!(r, "end"))
1344
+ } else if let Some(f) = f {
1345
+ if !expand {
1346
+ let r = interpolate!(f, " unless ", c);
1347
+ check_regexp_target(&r)?;
1348
+ if INDENT.len() + r.char_count() < LINE_LENGTH && !r.bytes.contains(&b'\n') {
1349
+ return Ok(r);
1350
+ }
1351
+ }
1352
+ let f = indent(Some(&f))?;
1353
+ Ok(interpolate!("unless ", c, " then\n", f, "\nend"))
1354
+ } else {
1355
+ // empty if statement, just do it in case of side effects from condition
1356
+ let nothing = indent(Some(&Code::from("# do nothing")))?;
1357
+ Ok(interpolate!("if ", c, " then\n", nothing, "\nend"))
1358
+ }
1359
+ }
1360
+
1361
+ /// `Ruby2Ruby#process_iter`: a block in braces when it fits on one
1362
+ /// line, otherwise `do ... end` (braces for `BEGIN`/`END`).
1363
+ fn process_iter(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1364
+ let iter = exp.nth(1);
1365
+ let args = exp.nth(2);
1366
+ let body = exp.nth(3);
1367
+
1368
+ let is_lambda = type_is(iter, "lambda")?;
1369
+ let iter = self.process(iter)?.unwrap_or_default();
1370
+ let body = if truthy(body) { self.process(body)? } else { None };
1371
+
1372
+ let args_is_zero = matches!(args, Some(Element::Value(value)) if is_numeric_zero(value));
1373
+ let args = if args_is_zero {
1374
+ Code::default()
1375
+ } else {
1376
+ let processed = self.process(args)?;
1377
+ let Some(inner) = processed.and_then(|processed| processed.slice(1, -2)) else {
1378
+ return Err(no_method_error("[]", "nil"));
1379
+ };
1380
+ if is_lambda {
1381
+ interpolate!(" (", inner, ")")
1382
+ } else {
1383
+ interpolate!(" |", inner, "|")
1384
+ }
1385
+ };
1386
+
1387
+ let curly = MUST_BE_CURLY.iter().any(|name| iter.bytes == name.as_bytes());
1388
+ let (b, e) = if curly { ("{", "}") } else { ("do", "end") };
1389
+
1390
+ check_regexp_target(&iter)?;
1391
+ let iter = Code { bytes: remove_empty_parens_at_end_of_line(&iter.bytes), encoding: iter.encoding };
1392
+
1393
+ let body_text = match &body {
1394
+ Some(body) => interpolate!(" ", strip(body), " "),
1395
+ None => Code::from(" "),
1396
+ };
1397
+ let result = if is_lambda {
1398
+ interpolate!(iter, args, " {", body_text, "}")
1399
+ } else {
1400
+ interpolate!(iter, " {", args, body_text, "}")
1401
+ };
1402
+ check_regexp_target(&result)?;
1403
+ if !result.bytes.contains(&b'\n') && result.char_count() < LINE_LENGTH {
1404
+ return Ok(result);
1405
+ }
1406
+
1407
+ let mut result = if is_lambda {
1408
+ interpolate!(iter, args, " ", b)
1409
+ } else {
1410
+ interpolate!(iter, " ", b, args)
1411
+ };
1412
+ result.push_str("\n");
1413
+ if let Some(body) = body {
1414
+ let body = indent(Some(&strip(&body)))?;
1415
+ result = interpolate!(result, body, "\n");
1416
+ }
1417
+ Ok(interpolate!(result, e))
1418
+ }
1419
+
1420
+ /// `Ruby2Ruby#process_kwsplat`.
1421
+ fn process_kwsplat(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1422
+ let kw = self.process(exp.nth(1))?;
1423
+ Ok(interpolate!("**", kw))
1424
+ }
1425
+
1426
+ /// `Ruby2Ruby#process_lasgn`: `name = value`, or `value => name` in a
1427
+ /// pattern.
1428
+ fn process_lasgn(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1429
+ let name = to_s_element(self.tree, exp.nth(1))?;
1430
+ match self.process(exp.nth(2))? {
1431
+ Some(value) if self.context_is_pattern(1) => Ok(interpolate!(value, " => ", name)),
1432
+ Some(value) => Ok(interpolate!(name, " = ", value)),
1433
+ None => Ok(name),
1434
+ }
1435
+ }
1436
+
1437
+ /// `Ruby2Ruby#process_lit`: the value's `inspect`, a Range in parens.
1438
+ fn process_lit(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1439
+ let obj = exp.nth(1);
1440
+ let code = inspect_element(self.tree, obj);
1441
+ if matches!(obj, Some(Element::Value(Value::Range(_)))) {
1442
+ Ok(interpolate!("(", code, ")"))
1443
+ } else {
1444
+ Ok(code)
1445
+ }
1446
+ }
1447
+
1448
+ /// `Ruby2Ruby#process_masgn`.
1449
+ fn process_masgn(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1450
+ let mut parenthesize = true;
1451
+ let mut result = Vec::new();
1452
+ for sexp in exp.rest(1) {
1453
+ match sexp {
1454
+ Element::Sexp(inner) if inner.is_type("array") => {
1455
+ parenthesize = self.context.iter().filter(|entry| entry.as_ref().is_some_and(|symbol| symbol.is("masgn"))).count() > 1;
1456
+ let res = self.process_sexp(inner)?;
1457
+ result.push(res.slice(1, -2));
1458
+ }
1459
+ Element::Sexp(inner) => result.push(Some(self.process_sexp(inner)?)),
1460
+ Element::Symbol(symbol) => result.push(Some(symbol.to_code())),
1461
+ other => {
1462
+ let other = some(other);
1463
+ return Err(runtime_error(format!("unknown masgn: {}", inspect_element(self.tree, other))));
1464
+ }
1465
+ }
1466
+ }
1467
+ if parenthesize {
1468
+ let joined = join(&result, ", ")?;
1469
+ Ok(interpolate!("(", joined, ")"))
1470
+ } else {
1471
+ join(&result, " = ")
1472
+ }
1473
+ }
1474
+
1475
+ /// `Ruby2Ruby#process_match`.
1476
+ fn process_match(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1477
+ Ok(self.process(exp.nth(1))?.unwrap_or_default())
1478
+ }
1479
+
1480
+ /// `Ruby2Ruby#process_match2`.
1481
+ fn process_match2(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1482
+ let lhs = self.process(exp.nth(1))?;
1483
+ let rhs = self.process(exp.nth(2))?;
1484
+ Ok(interpolate!(lhs, " =~ ", rhs))
1485
+ }
1486
+
1487
+ /// `Ruby2Ruby#process_match3` (its elements are backwards).
1488
+ fn process_match3(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1489
+ let rhs = exp.nth(1);
1490
+ let lhs = exp.nth(2);
1491
+ let left_type = sexp_type(lhs)?;
1492
+ let lhs = self.process(lhs)?;
1493
+ let rhs = self.process(rhs)?;
1494
+ if is_symbol_in(left_type, ASSIGN_NODES) {
1495
+ Ok(interpolate!("(", lhs, ") =~ ", rhs))
1496
+ } else {
1497
+ Ok(interpolate!(lhs, " =~ ", rhs))
1498
+ }
1499
+ }
1500
+
1501
+ /// `Ruby2Ruby#process_module`.
1502
+ fn process_module(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1503
+ let comments = self.comments(exp);
1504
+ let module = self.util_module_or_class(exp, false)?;
1505
+ Ok(interpolate!(comments, "module ", module))
1506
+ }
1507
+
1508
+ /// `Ruby2Ruby#process_next`.
1509
+ fn process_next(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1510
+ let rhs = exp.nth(1);
1511
+ let value = if truthy(rhs) { self.process(rhs)? } else { None };
1512
+ match value {
1513
+ Some(value) => Ok(interpolate!("next ", value)),
1514
+ None => Ok(Code::from("next")),
1515
+ }
1516
+ }
1517
+
1518
+ /// `Ruby2Ruby#process_not`.
1519
+ fn process_not(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1520
+ let sexp = self.process(exp.nth(1))?;
1521
+ Ok(interpolate!("(not ", sexp, ")"))
1522
+ }
1523
+
1524
+ /// `Ruby2Ruby#process_nth_ref`.
1525
+ fn process_nth_ref(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1526
+ let n = to_s_element(self.tree, exp.nth(1))?;
1527
+ Ok(interpolate!("$", n))
1528
+ }
1529
+
1530
+ /// `Ruby2Ruby#process_op_asgn`.
1531
+ fn process_op_asgn(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1532
+ match exp.elements.len() {
1533
+ 4 => {
1534
+ let lhs = self.process(exp.nth(1))?;
1535
+ let op = to_s_element(self.tree, exp.nth(2))?;
1536
+ let rhs = self.process(exp.nth(3))?;
1537
+ Ok(interpolate!(lhs, " ", op, "= ", rhs))
1538
+ }
1539
+ 5 => {
1540
+ let lhs = self.process(exp.nth(1))?;
1541
+ let rhs = self.process(exp.nth(2))?;
1542
+ let index = to_s_element(self.tree, exp.nth(3))?;
1543
+ let op = to_s_element(self.tree, exp.nth(4))?;
1544
+ Ok(interpolate!(lhs, ".", index, " ", op, "= ", rhs))
1545
+ }
1546
+ _ => Err(RubyException {
1547
+ class: "ArgumentError",
1548
+ message: format!("Don't know how to process this length: {}", inspect_sexp(self.tree, exp)),
1549
+ }),
1550
+ }
1551
+ }
1552
+
1553
+ /// `Ruby2Ruby#process_op_asgn1`.
1554
+ fn process_op_asgn1(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1555
+ let lhs = self.process(exp.nth(1))?;
1556
+ let index = self.process(exp.nth(2))?;
1557
+ let msg = to_s_element(self.tree, exp.nth(3))?;
1558
+ let rhs = self.process(exp.nth(4))?;
1559
+ Ok(interpolate!(lhs, "[", index, "] ", msg, "= ", rhs))
1560
+ }
1561
+
1562
+ /// `Ruby2Ruby#process_op_asgn2` and `process_safe_op_asgn2` (`call`
1563
+ /// is "." or "&.").
1564
+ fn process_op_asgn2(&mut self, exp: &Sexp<'t>, call: &str) -> Result<Code> {
1565
+ let lhs = self.process(exp.nth(1))?;
1566
+ let index = to_s_element(self.tree, exp.nth(2))?.slice(0, -2);
1567
+ let msg = to_s_element(self.tree, exp.nth(3))?;
1568
+ let rhs = self.process(exp.nth(4))?;
1569
+ Ok(interpolate!(lhs, call, index, " ", msg, "= ", rhs))
1570
+ }
1571
+
1572
+ /// `Ruby2Ruby#process_op_asgn_and` and `process_op_asgn_or`: the
1573
+ /// assignment with its first `=` replaced by `operator`.
1574
+ fn process_op_asgn_and_or(&mut self, exp: &Sexp<'t>, operator: &str) -> Result<Code> {
1575
+ let Some(rhs) = self.process(exp.nth(2))? else {
1576
+ return Err(no_method_error("sub", "nil"));
1577
+ };
1578
+ check_regexp_target(&rhs)?;
1579
+ let mut bytes = rhs.bytes.clone();
1580
+ if let Some(position) = bytes.iter().position(|byte| *byte == b'=') {
1581
+ bytes.splice(position..=position, operator.bytes());
1582
+ }
1583
+ Ok(Code { bytes, encoding: rhs.encoding })
1584
+ }
1585
+
1586
+ /// `Ruby2Ruby#process_or`: `|` between pattern alternatives.
1587
+ fn process_or(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1588
+ let lhs = self.process(exp.nth(1))?;
1589
+ let rhs = self.process(exp.nth(2))?;
1590
+ if self.context_is(1, "in") {
1591
+ Ok(interpolate!("(", lhs, " | ", rhs, ")"))
1592
+ } else {
1593
+ Ok(interpolate!("(", lhs, " or ", rhs, ")"))
1594
+ }
1595
+ }
1596
+
1597
+ /// `Ruby2Ruby#process_resbody`.
1598
+ fn process_resbody(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1599
+ let args = exp.nth(1);
1600
+ let mut body = Vec::new();
1601
+ for sexp in exp.rest(2).iter().filter(|sexp| !matches!(sexp, Element::Nil)) {
1602
+ body.push(self.process(Some(sexp))?);
1603
+ }
1604
+ if body.is_empty() {
1605
+ body.push(Some(Code::from("# do nothing")));
1606
+ }
1607
+
1608
+ // name = args.lasgn true; name ||= args.iasgn true
1609
+ let Some(Element::Sexp(args)) = args else {
1610
+ return Err(no_method_error("lasgn", receiver_text(args)));
1611
+ };
1612
+ let mut args = args.clone();
1613
+ let mut name = None;
1614
+ for assignment in ["lasgn", "iasgn"] {
1615
+ if let Some(found) = self.find_node(&args, assignment)? {
1616
+ name = Some(to_s_element(self.tree, found.nth(1))?);
1617
+ let index = args.find_nodes(assignment)[0];
1618
+ args.elements.remove(index);
1619
+ break;
1620
+ }
1621
+ }
1622
+ let processed = self.process_sexp(&args)?;
1623
+ let Some(mut args) = processed.slice(1, -2) else {
1624
+ return Err(no_method_error("empty?", "nil"));
1625
+ };
1626
+ if !args.bytes.is_empty() {
1627
+ args = interpolate!(" ", args);
1628
+ }
1629
+ if let Some(name) = name {
1630
+ args = interpolate!(args, " => ", name);
1631
+ }
1632
+ let body = indent(Some(&join(&body, "\n")?))?;
1633
+ Ok(interpolate!("rescue", args, "\n", body))
1634
+ }
1635
+
1636
+ /// `Ruby2Ruby#process_rescue`: `body rescue value` when simple,
1637
+ /// otherwise the body and `rescue` clauses (and `else`) on lines.
1638
+ fn process_rescue(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1639
+ let mut rest: Vec<Element<'t>> = exp.rest(1).to_vec();
1640
+
1641
+ let mut body = None;
1642
+ if !type_is(rest.first().and_then(some), "resbody")? {
1643
+ let first = if rest.is_empty() { None } else { Some(rest.remove(0)) };
1644
+ body = self.process(first.as_ref().and_then(some))?;
1645
+ }
1646
+ let mut els = None;
1647
+ let last = rest.last().and_then(some);
1648
+ if !(truthy(last) && type_is(last, "resbody")?) {
1649
+ let last = rest.pop();
1650
+ els = self.process(last.as_ref().and_then(some))?;
1651
+ }
1652
+ let body = body.unwrap_or_else(|| Code::from("# do nothing"));
1653
+
1654
+ // simple = rest.size == 1 && rest.first.size <= 3 &&
1655
+ // !rest.first.block && !rest.first.return
1656
+ let mut simple = false;
1657
+ if rest.len() == 1 {
1658
+ match some(&rest[0]) {
1659
+ Some(Element::Sexp(first)) => {
1660
+ simple = first.elements.len() <= 3
1661
+ && self.find_node(first, "block")?.is_none()
1662
+ && self.find_node(first, "return")?.is_none();
1663
+ }
1664
+ None => return Err(no_method_error("size", "nil")),
1665
+ Some(_) => return Err(not_ported("Ruby2Ruby#process_rescue with an atom for its only rescue clause")),
1666
+ }
1667
+ }
1668
+
1669
+ let mut resbodies = Vec::with_capacity(rest.len());
1670
+ for resbody in &rest {
1671
+ let resbody = some(resbody);
1672
+ // _, rb_args, rb_body, *rb_rest = resbody
1673
+ let (rb_args, rb_body, rb_rest_empty) = match resbody {
1674
+ Some(Element::Sexp(sexp)) => (sexp.nth(1), sexp.nth(2), sexp.elements.len() <= 3),
1675
+ _ => (None, None, true),
1676
+ };
1677
+ if simple {
1678
+ simple = is_only(rb_args, "array");
1679
+ }
1680
+ if simple {
1681
+ simple = rb_rest_empty && truthy(rb_body);
1682
+ // rb_body.node_type: nil through method_missing for a sexp.
1683
+ if simple && !matches!(rb_body, Some(Element::Sexp(_))) {
1684
+ return Err(no_method_error("node_type", receiver_text(rb_body)));
1685
+ }
1686
+ }
1687
+ resbodies.push(self.process(resbody)?);
1688
+ }
1689
+
1690
+ let resbodies_joined = join(&resbodies, "\n")?;
1691
+ if let Some(els) = els {
1692
+ let body = indent(Some(&body))?;
1693
+ let els = indent(Some(&els))?;
1694
+ Ok(interpolate!(body, "\n", resbodies_joined, "\nelse\n", els))
1695
+ } else if simple {
1696
+ let first = resbodies.first().cloned().flatten().unwrap_or_default();
1697
+ check_regexp_target(&first)?;
1698
+ let resbody = Code { bytes: join_first_line_break(&first.bytes), encoding: first.encoding };
1699
+ Ok(interpolate!(body, " ", resbody))
1700
+ } else {
1701
+ let body = indent(Some(&body))?;
1702
+ Ok(interpolate!(body, "\n", resbodies_joined))
1703
+ }
1704
+ }
1705
+
1706
+ /// `Ruby2Ruby#process_return`.
1707
+ fn process_return(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1708
+ let rhs = exp.nth(1);
1709
+ if !truthy(rhs) {
1710
+ return Ok(Code::from("return"));
1711
+ }
1712
+ let rhs_type = sexp_type(rhs)?;
1713
+ let mut rhs = self.process(rhs)?;
1714
+ if is_symbol_in(rhs_type, ASSIGN_NODES) {
1715
+ rhs = Some(interpolate!("(", rhs, ")"));
1716
+ }
1717
+ Ok(interpolate!("return ", rhs))
1718
+ }
1719
+
1720
+ /// `Ruby2Ruby#process_safe_attrasgn`.
1721
+ fn process_safe_attrasgn(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1722
+ let receiver = self.process(exp.nth(1))?;
1723
+ let mut rest = exp.rest(3).to_vec();
1724
+ let rhs = rest.pop();
1725
+ let args = rest.pop();
1726
+ let rhs = rhs.as_ref().and_then(some);
1727
+ let args = args.as_ref().and_then(some);
1728
+ if truthy(args) {
1729
+ return Err(runtime_error(format!("dunno what to do: {}", inspect_element(self.tree, args))));
1730
+ }
1731
+ let name = to_s_element(self.tree, exp.nth(2))?;
1732
+ check_regexp_target(&name)?;
1733
+ let name = Code { bytes: remove_equals_at_end_of_line(&name.bytes), encoding: name.encoding };
1734
+ if truthy(rhs) && !is_only(rhs, "arglist") {
1735
+ let rhs = self.process(rhs)?;
1736
+ Ok(interpolate!(receiver, "&.", name, " = ", rhs))
1737
+ } else {
1738
+ Err(runtime_error(format!("dunno what to do: {}", inspect_element(self.tree, rhs))))
1739
+ }
1740
+ }
1741
+
1742
+ /// `Ruby2Ruby#process_safe_op_asgn`.
1743
+ fn process_safe_op_asgn(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1744
+ let lhs = self.process(exp.nth(1))?;
1745
+ let rhs = self.process(exp.nth(2))?;
1746
+ let index = to_s_element(self.tree, exp.nth(3))?;
1747
+ let op = to_s_element(self.tree, exp.nth(4))?;
1748
+ Ok(interpolate!(lhs, "&.", index, " ", op, "= ", rhs))
1749
+ }
1750
+
1751
+ /// `Ruby2Ruby#process_sclass`.
1752
+ fn process_sclass(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1753
+ let recv = self.process(exp.nth(1))?;
1754
+ let mut block = vec![Element::Symbol(Symbol::named("block"))];
1755
+ block.extend(exp.rest(2).iter().cloned());
1756
+ let block = self.process_block(&Sexp::new(block))?;
1757
+ let block = indent(Some(&block))?;
1758
+ Ok(interpolate!("class << ", recv, "\n", block, "\nend"))
1759
+ }
1760
+
1761
+ /// `Ruby2Ruby#process_splat`.
1762
+ fn process_splat(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1763
+ match exp.nth(1) {
1764
+ None => Ok(Code::from("*")),
1765
+ arg => {
1766
+ let arg = self.process(arg)?;
1767
+ Ok(interpolate!("*", arg))
1768
+ }
1769
+ }
1770
+ }
1771
+
1772
+ /// `Ruby2Ruby#process_super`.
1773
+ fn process_super(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1774
+ let mut args = Vec::new();
1775
+ for arg in exp.rest(1) {
1776
+ args.push(self.process(some(arg))?);
1777
+ }
1778
+ let joined = join(&args, ", ")?;
1779
+ Ok(interpolate!("super(", joined, ")"))
1780
+ }
1781
+
1782
+ /// `Ruby2Ruby#process_svalue`.
1783
+ fn process_svalue(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1784
+ let mut args = Vec::new();
1785
+ for arg in exp.rest(1) {
1786
+ args.push(self.process(some(arg))?);
1787
+ }
1788
+ join(&args, ", ")
1789
+ }
1790
+
1791
+ /// `Ruby2Ruby#process_to_ary`.
1792
+ fn process_to_ary(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1793
+ Ok(self.process(exp.nth(1))?.unwrap_or_default())
1794
+ }
1795
+
1796
+ /// `Ruby2Ruby#process_undef`.
1797
+ fn process_undef(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1798
+ let name = self.process(exp.nth(1))?;
1799
+ Ok(interpolate!("undef ", name))
1800
+ }
1801
+
1802
+ /// `Ruby2Ruby#process_valias`.
1803
+ fn process_valias(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1804
+ let lhs = to_s_element(self.tree, exp.nth(1))?;
1805
+ let rhs = to_s_element(self.tree, exp.nth(2))?;
1806
+ Ok(interpolate!("alias ", lhs, " ", rhs))
1807
+ }
1808
+
1809
+ /// `Ruby2Ruby#process_when`.
1810
+ fn process_when(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1811
+ let Some(cond) = self.process(exp.nth(1))? else {
1812
+ return Err(no_method_error("[]", "nil"));
1813
+ };
1814
+ let cond = cond.slice(1, -2);
1815
+ let mut rhs = Vec::new();
1816
+ for sexp in exp.rest(2).iter().filter(|sexp| !matches!(sexp, Element::Nil)) {
1817
+ let processed = self.process(Some(sexp))?;
1818
+ rhs.push(Some(indent(processed.as_ref())?));
1819
+ }
1820
+ if rhs.is_empty() {
1821
+ rhs.push(Some(indent(Some(&Code::from("# do nothing")))?));
1822
+ }
1823
+ let rhs = chomp(&join(&rhs, "\n")?);
1824
+ Ok(interpolate!("when ", cond, " then\n", rhs))
1825
+ }
1826
+
1827
+ /// `Ruby2Ruby#process_yield`.
1828
+ fn process_yield(&mut self, exp: &Sexp<'t>) -> Result<Code> {
1829
+ let mut args = Vec::new();
1830
+ for arg in exp.rest(1) {
1831
+ args.push(self.process(some(arg))?);
1832
+ }
1833
+ if args.is_empty() {
1834
+ Ok(Code::from("yield"))
1835
+ } else {
1836
+ let joined = join(&args, ", ")?;
1837
+ Ok(interpolate!("yield(", joined, ")"))
1838
+ }
1839
+ }
1840
+
1841
+ // ---------------------------------------------------------------------
1842
+ // Utility methods
1843
+
1844
+ /// `Ruby2Ruby#cond_loop`: a `while`/`until` loop, `begin ... end while`
1845
+ /// when the condition is checked after the body.
1846
+ fn cond_loop(&mut self, exp: &Sexp<'t>, name: &str) -> Result<Code> {
1847
+ let cond = self.process(exp.nth(1))?;
1848
+ let body = self.process(exp.nth(2))?;
1849
+ let head_controlled = truthy(exp.nth(3));
1850
+
1851
+ let body = match body {
1852
+ Some(body) => Some(chomp(&indent(Some(&body))?)),
1853
+ None => None,
1854
+ };
1855
+
1856
+ let mut code = Vec::new();
1857
+ if head_controlled {
1858
+ code.push(Some(interpolate!(name, " ", cond, " do")));
1859
+ if body.is_some() {
1860
+ code.push(body);
1861
+ }
1862
+ code.push(Some(Code::from("end")));
1863
+ } else {
1864
+ code.push(Some(Code::from("begin")));
1865
+ if body.is_some() {
1866
+ code.push(body);
1867
+ }
1868
+ code.push(Some(interpolate!("end ", name, " ", cond)));
1869
+ }
1870
+ join(&code, "\n")
1871
+ }
1872
+
1873
+ /// `Ruby2Ruby#parenthesize`: parens unless the parent's type makes
1874
+ /// them unnecessary.
1875
+ fn parenthesize(&self, exp: Code) -> Result<Code> {
1876
+ let bare = match self.context_at(1) {
1877
+ None => true,
1878
+ Some(parent) => parent.is_any(&["defn", "defs", "class", "sclass", "if", "iter", "resbody", "when", "while"]),
1879
+ };
1880
+ if bare {
1881
+ Ok(exp)
1882
+ } else {
1883
+ Ok(interpolate!("(", exp, ")"))
1884
+ }
1885
+ }
1886
+
1887
+ /// `Ruby2Ruby#util_dthing`: the inside of an interpolated string,
1888
+ /// symbol, regexp or command.
1889
+ fn util_dthing(&mut self, dthing_type: DthingType, exp: &Sexp<'t>) -> Result<Code> {
1890
+ let mut result = dthing_escape(dthing_type, exp.nth(1))?;
1891
+ for pt in exp.rest(2) {
1892
+ let pt = some(pt);
1893
+ if type_is(pt, "str")? {
1894
+ let last = match pt {
1895
+ Some(Element::Sexp(sexp)) => sexp.last(),
1896
+ _ => None,
1897
+ };
1898
+ let escaped = dthing_escape(dthing_type, last)?;
1899
+ result.push_code(&escaped)?;
1900
+ } else if type_is(pt, "evstr")? {
1901
+ let code = self.process(pt)?;
1902
+ result = interpolate!(result, "#{", code, "}");
1903
+ } else {
1904
+ return Err(runtime_error(format!("unknown type: {}", inspect_element(self.tree, pt))));
1905
+ }
1906
+ }
1907
+ Ok(result)
1908
+ }
1909
+
1910
+ /// `Ruby2Ruby#util_module_or_class`: the name, superclass and body of
1911
+ /// a class or module, ending in `end`.
1912
+ fn util_module_or_class(&mut self, exp: &Sexp<'t>, is_class: bool) -> Result<Code> {
1913
+ let name = exp.nth(1);
1914
+ let mut body: &[Element<'t>] = exp.rest(2);
1915
+ let mut superk = None;
1916
+ if is_class && !body.is_empty() {
1917
+ superk = some(&body[0]);
1918
+ body = &body[1..];
1919
+ }
1920
+
1921
+ let name = match name {
1922
+ Some(Element::Sexp(_)) => self.process(name)?.unwrap_or_default(),
1923
+ other => to_s_element(self.tree, other)?,
1924
+ };
1925
+ let mut result = name;
1926
+
1927
+ if truthy(superk) {
1928
+ if let Some(superk) = self.process(superk)? {
1929
+ result = interpolate!(result, " < ", superk);
1930
+ }
1931
+ }
1932
+ result.push_str("\n");
1933
+
1934
+ let mut processed = Vec::with_capacity(body.len());
1935
+ for sexp in body {
1936
+ let Some(code) = self.process(some(sexp))? else {
1937
+ return Err(no_method_error("chomp", "nil"));
1938
+ };
1939
+ processed.push(Some(chomp(&code)));
1940
+ }
1941
+ if !processed.is_empty() {
1942
+ let body = indent(Some(&join(&processed, "\n\n")?))?;
1943
+ result = interpolate!(result, body, "\n");
1944
+ }
1945
+ Ok(interpolate!(result, "end"))
1946
+ }
1947
+ }
1948
+
1949
+ /// `Ruby2Ruby#rewrite_call`: `recv.!` without arguments becomes `not`.
1950
+ fn rewrite_call(exp: Sexp<'_>) -> Sexp<'_> {
1951
+ let is_not = matches!(exp.nth(2), Some(Element::Symbol(symbol)) if symbol.is("!")) && exp.rest(3).is_empty();
1952
+ if !is_not {
1953
+ return exp;
1954
+ }
1955
+ let recv = exp.elements.get(1).cloned().unwrap_or(Element::Nil);
1956
+ Sexp::new(vec![Element::Symbol(Symbol::named("not")), recv])
1957
+ }
1958
+
1959
+ /// `Ruby2Ruby#rewrite_if`: `if not c` becomes `if c` with the branches
1960
+ /// swapped.
1961
+ fn rewrite_if(exp: Sexp<'_>) -> Result<Sexp<'_>> {
1962
+ let c = exp.nth(1);
1963
+ if !type_is(c, "not")? {
1964
+ return Ok(exp);
1965
+ }
1966
+ let nc = as_sexp(c.expect("a sexp")).elements.get(1).cloned().unwrap_or(Element::Nil);
1967
+ let t = exp.elements.get(2).cloned().unwrap_or(Element::Nil);
1968
+ let f = exp.elements.get(3).cloned().unwrap_or(Element::Nil);
1969
+ Ok(Sexp::new(vec![Element::Symbol(Symbol::named("if")), nc, f, t]))
1970
+ }
1971
+
1972
+ /// `Ruby2Ruby#rewrite_until`: `until not c` becomes `while c`.
1973
+ fn rewrite_until(exp: Sexp<'_>) -> Result<Sexp<'_>> {
1974
+ rewrite_negated_loop(exp, "while")
1975
+ }
1976
+
1977
+ /// `Ruby2Ruby#rewrite_while`: `while not c` becomes `until c`.
1978
+ fn rewrite_while(exp: Sexp<'_>) -> Result<Sexp<'_>> {
1979
+ rewrite_negated_loop(exp, "until")
1980
+ }
1981
+
1982
+ /// The loop with condition `not c` as the opposite loop on `c`.
1983
+ fn rewrite_negated_loop<'t>(exp: Sexp<'t>, opposite: &'static str) -> Result<Sexp<'t>> {
1984
+ let c = exp.nth(1);
1985
+ if !type_is(c, "not")? {
1986
+ return Ok(exp);
1987
+ }
1988
+ let nc = as_sexp(c.expect("a sexp")).elements.get(1).cloned().unwrap_or(Element::Nil);
1989
+ let mut elements = vec![Element::Symbol(Symbol::named(opposite)), nc];
1990
+ elements.extend(exp.rest(2).iter().cloned());
1991
+ Ok(Sexp::new(elements))
1992
+ }
1993
+
1994
+ /// `Ruby2Ruby#process_str`: `String#dump` of the string.
1995
+ fn process_str(exp: &Sexp<'_>) -> Result<Code> {
1996
+ match exp.nth(1) {
1997
+ Some(Element::Value(Value::String(string))) => Ok(dump(&string.bytes, string.encoding)),
1998
+ other => Err(no_method_error("dump", receiver_text(other))),
1999
+ }
2000
+ }
2001
+
2002
+ /// `Ruby2Ruby#process_xstr`.
2003
+ fn process_xstr(exp: &Sexp<'_>) -> Result<Code> {
2004
+ let dumped = process_str(exp)?;
2005
+ let inner = dumped.slice(1, -2);
2006
+ Ok(interpolate!("`", inner, "`"))
2007
+ }
2008
+
2009
+ /// The pattern of `process_defn`'s first `when`:
2010
+ /// `q(:defn, atom, t(:args), q(:ivar, atom))`.
2011
+ fn is_ivar_reader(sexp: &Sexp<'_>) -> bool {
2012
+ matches!(sexp.elements.as_slice(), [Element::Symbol(defn), name, Element::Sexp(args), Element::Sexp(ivar)]
2013
+ if defn.is("defn") && is_atom(name) && args.is_type("args")
2014
+ && matches!(ivar.elements.as_slice(), [Element::Symbol(kind), value] if kind.is("ivar") && is_atom(value)))
2015
+ }
2016
+
2017
+ /// The pattern of `process_defn`'s second `when`:
2018
+ /// `q(:defn, atom, t(:args), q(:iasgn, atom, q(:lvar, atom)))`.
2019
+ fn is_ivar_writer(sexp: &Sexp<'_>) -> bool {
2020
+ matches!(sexp.elements.as_slice(), [Element::Symbol(defn), name, Element::Sexp(args), Element::Sexp(iasgn)]
2021
+ if defn.is("defn") && is_atom(name) && args.is_type("args")
2022
+ && matches!(iasgn.elements.as_slice(), [Element::Symbol(kind), ivar, Element::Sexp(lvar)]
2023
+ if kind.is("iasgn") && is_atom(ivar)
2024
+ && matches!(lvar.elements.as_slice(), [Element::Symbol(kind), value] if kind.is("lvar") && is_atom(value))))
2025
+ }
2026
+
2027
+ /// `Sexp::Matcher#=~`: the pattern is satisfied by `sexp` or by any sexp
2028
+ /// below it (`match_subs?` is true).
2029
+ fn matches_anywhere(sexp: &Sexp<'_>, pattern: &dyn Fn(&Sexp<'_>) -> bool) -> bool {
2030
+ pattern(sexp)
2031
+ || sexp.elements.iter().any(|element| matches!(element, Element::Sexp(sub) if matches_anywhere(sub, pattern)))
2032
+ }
2033
+
2034
+ /// `Sexp::Atom#satisfy?`: anything but a sexp.
2035
+ fn is_atom(element: &Element<'_>) -> bool {
2036
+ !matches!(element, Element::Sexp(_))
2037
+ }
2038
+
2039
+ /// `Sexp#value` (the last element of a sexp of at most two elements) of a
2040
+ /// `lit` sexp.
2041
+ fn sexp_value<'a, 't>(element: Option<&'a Element<'t>>) -> Result<Option<&'a Element<'t>>> {
2042
+ match element {
2043
+ Some(Element::Sexp(sexp)) if sexp.elements.len() > 2 => Err(runtime_error("multi item sexp".to_string())),
2044
+ Some(Element::Sexp(sexp)) => Ok(sexp.last()),
2045
+ other => Err(no_method_error("value", receiver_text(other))),
2046
+ }
2047
+ }
2048
+
2049
+ /// The `type` argument of `Ruby2Ruby#dthing_escape`.
2050
+ #[derive(Clone, Copy, Debug)]
2051
+ enum DthingType {
2052
+ Dregx,
2053
+ Dstr,
2054
+ Dsym,
2055
+ Dxstr,
2056
+ }
2057
+
2058
+ /// `Ruby2Ruby#dthing_escape`: a literal part of an interpolated string as
2059
+ /// it is written inside the delimiters.
2060
+ fn dthing_escape(dthing_type: DthingType, lit: Option<&Element<'_>>) -> Result<Code> {
2061
+ let (method, string) = match dthing_type {
2062
+ DthingType::Dregx | DthingType::Dxstr => ("gsub", lit),
2063
+ DthingType::Dstr | DthingType::Dsym => ("dump", lit),
2064
+ };
2065
+ let string = match string {
2066
+ Some(Element::Value(Value::String(string))) => Code::new(string.bytes.clone(), string.encoding),
2067
+ Some(Element::Text(code)) => code.clone(),
2068
+ other => return Err(no_method_error(method, receiver_text(other))),
2069
+ };
2070
+ match dthing_type {
2071
+ DthingType::Dregx => {
2072
+ check_regexp_target(&string)?;
2073
+ Ok(Code { bytes: escape_slashes(&string.bytes), encoding: string.encoding })
2074
+ }
2075
+ DthingType::Dstr | DthingType::Dsym => {
2076
+ let dumped = dump(&string.bytes, string.encoding.unwrap_or(UTF_8));
2077
+ Ok(dumped.slice(1, -2).unwrap_or_default())
2078
+ }
2079
+ DthingType::Dxstr => {
2080
+ check_regexp_target(&string)?;
2081
+ Ok(Code { bytes: replace_backticks_with_prematch(&string.bytes), encoding: string.encoding })
2082
+ }
2083
+ }
2084
+ }
2085
+
2086
+ /// `Ruby2Ruby#re_opt`: the regexp flags for a numeric code (bits 0..8;
2087
+ /// `Regexp::CODES` is `{2=>"x", 1=>"i", 4=>"m", 32=>"n", 16=>"u"}`).
2088
+ fn re_opt(options: &Integer) -> Code {
2089
+ let low = options.limbs.first().copied().unwrap_or(0);
2090
+ let mut flags = String::new();
2091
+ for bit in 0..=8 {
2092
+ if low & (1 << bit) != 0 {
2093
+ match 1u32 << bit {
2094
+ 1 => flags.push('i'),
2095
+ 2 => flags.push('x'),
2096
+ 4 => flags.push('m'),
2097
+ 16 => flags.push('u'),
2098
+ 32 => flags.push('n'),
2099
+ _ => {}
2100
+ }
2101
+ }
2102
+ }
2103
+ Code::from(flags.as_str())
2104
+ }
2105
+
2106
+ /// The sexp inside an element known to be one.
2107
+ fn as_sexp<'a, 't>(element: &'a Element<'t>) -> &'a Sexp<'t> {
2108
+ match element {
2109
+ Element::Sexp(sexp) => sexp,
2110
+ _ => unreachable!("find_nodes returns sexps"),
2111
+ }
2112
+ }
2113
+
2114
+ /// An element as Ruby2Ruby's `process` sees it: nil as `None`.
2115
+ fn some<'a, 't>(element: &'a Element<'t>) -> Option<&'a Element<'t>> {
2116
+ match element {
2117
+ Element::Nil => None,
2118
+ other => Some(other),
2119
+ }
2120
+ }
2121
+
2122
+ /// `element.sexp_type`: the first element of a sexp; `NoMethodError` for
2123
+ /// anything else.
2124
+ fn sexp_type<'a, 't>(element: Option<&'a Element<'t>>) -> Result<Option<&'a Symbol<'t>>> {
2125
+ match element {
2126
+ Some(Element::Sexp(sexp)) => Ok(sexp.type_symbol()),
2127
+ other => Err(no_method_error("sexp_type", receiver_text(other))),
2128
+ }
2129
+ }
2130
+
2131
+ /// `element.sexp_type == :name`.
2132
+ fn type_is(element: Option<&Element<'_>>, name: &str) -> Result<bool> {
2133
+ Ok(sexp_type(element)?.is_some_and(|symbol| symbol.is(name)))
2134
+ }
2135
+
2136
+ /// `names.include? sexp_type`.
2137
+ fn is_symbol_in(sexp_type: Option<&Symbol<'_>>, names: &[&str]) -> bool {
2138
+ sexp_type.is_some_and(|symbol| symbol.is_any(names))
2139
+ }
2140
+
2141
+ /// `value == 0` for the numbers the translator writes.
2142
+ fn is_numeric_zero(value: &Value) -> bool {
2143
+ match value {
2144
+ Value::Integer(integer) => integer.is_zero(),
2145
+ Value::Float(float) => *float == 0.0,
2146
+ Value::Rational(rational) => rational.0.is_zero(),
2147
+ _ => false,
2148
+ }
2149
+ }
2150
+
2151
+ // -------------------------------------------------------------------------
2152
+ // Exceptions
2153
+
2154
+ fn runtime_error(message: String) -> RubyException {
2155
+ RubyException { class: "RuntimeError", message }
2156
+ }
2157
+
2158
+ /// `NoMethodError` as Ruby 3.3 words it.
2159
+ fn no_method_error(method: &str, receiver: &str) -> RubyException {
2160
+ RubyException { class: "NoMethodError", message: format!("undefined method `{method}' for {receiver}") }
2161
+ }
2162
+
2163
+ /// A path through Ruby2Ruby that needs Ruby behavior this port does not
2164
+ /// have, and that no translated tree reaches.
2165
+ fn not_ported(what: &str) -> RubyException {
2166
+ RubyException { class: "NotImplementedError", message: format!("flay_rs does not port {what}") }
2167
+ }
2168
+
2169
+ /// The receiver in a Ruby 3.3 `NoMethodError` message.
2170
+ fn receiver_text(element: Option<&Element<'_>>) -> &'static str {
2171
+ match element {
2172
+ None | Some(Element::Nil) => "nil",
2173
+ Some(Element::Value(Value::True)) => "true",
2174
+ Some(Element::Value(Value::False)) => "false",
2175
+ other => match class_name(other) {
2176
+ "Symbol" => "an instance of Symbol",
2177
+ "String" => "an instance of String",
2178
+ "Integer" => "an instance of Integer",
2179
+ "Float" => "an instance of Float",
2180
+ "Rational" => "an instance of Rational",
2181
+ "Complex" => "an instance of Complex",
2182
+ "Range" => "an instance of Range",
2183
+ "Regexp" => "an instance of Regexp",
2184
+ "Array" => "an instance of Array",
2185
+ _ => "an instance of Sexp",
2186
+ },
2187
+ }
2188
+ }
2189
+
2190
+ /// The class of an element.
2191
+ fn class_name(element: Option<&Element<'_>>) -> &'static str {
2192
+ match element {
2193
+ None | Some(Element::Nil) => "NilClass",
2194
+ Some(Element::Sexp(_)) => "Sexp",
2195
+ Some(Element::Symbol(_)) => "Symbol",
2196
+ Some(Element::Text(_)) => "String",
2197
+ Some(Element::Value(value)) => match value {
2198
+ Value::Nil => "NilClass",
2199
+ Value::True => "TrueClass",
2200
+ Value::False => "FalseClass",
2201
+ Value::Symbol(_) => "Symbol",
2202
+ Value::String(_) => "String",
2203
+ Value::Integer(_) => "Integer",
2204
+ Value::Float(_) => "Float",
2205
+ Value::Rational(_) => "Rational",
2206
+ Value::Complex(_) => "Complex",
2207
+ Value::Range(_) => "Range",
2208
+ Value::Regexp(_) => "Regexp",
2209
+ Value::Array(_) => "Array",
2210
+ Value::Sexp(_) => "Sexp",
2211
+ },
2212
+ }
2213
+ }
2214
+
2215
+ // -------------------------------------------------------------------------
2216
+ // Strings
2217
+
2218
+ /// A Ruby String that Ruby2Ruby builds: its bytes, and the encoding of its
2219
+ /// non-ASCII bytes (`None` while it has none).
2220
+ #[derive(Clone, Debug, Default, PartialEq)]
2221
+ struct Code {
2222
+ bytes: Vec<u8>,
2223
+ encoding: Option<Encoding>,
2224
+ }
2225
+
2226
+ impl From<&str> for Code {
2227
+ fn from(text: &str) -> Self {
2228
+ Code { bytes: text.as_bytes().to_vec(), encoding: None }
2229
+ }
2230
+ }
2231
+
2232
+ impl Code {
2233
+ fn new(bytes: Vec<u8>, encoding: Encoding) -> Self {
2234
+ let encoding = if bytes.is_ascii() { None } else { Some(encoding) };
2235
+ Code { bytes, encoding }
2236
+ }
2237
+
2238
+ fn push_str(&mut self, text: &str) {
2239
+ self.bytes.extend_from_slice(text.as_bytes());
2240
+ }
2241
+
2242
+ /// Appends `other` as Ruby appends strings: an ASCII-only string takes
2243
+ /// the other's encoding; two strings with non-ASCII bytes in different
2244
+ /// encodings raise `Encoding::CompatibilityError`.
2245
+ fn push_code(&mut self, other: &Code) -> Result<()> {
2246
+ match (self.encoding, other.encoding) {
2247
+ (Some(mine), Some(theirs)) if mine != theirs => {
2248
+ return Err(RubyException {
2249
+ class: "Encoding::CompatibilityError",
2250
+ message: format!("incompatible character encodings: {mine} and {theirs}"),
2251
+ });
2252
+ }
2253
+ (None, Some(theirs)) => self.encoding = Some(theirs),
2254
+ _ => {}
2255
+ }
2256
+ self.bytes.extend_from_slice(&other.bytes);
2257
+ Ok(())
2258
+ }
2259
+
2260
+ /// The start of each character: UTF-8 sequences for a UTF-8 string,
2261
+ /// bytes otherwise.
2262
+ fn char_starts(&self) -> Vec<usize> {
2263
+ if self.encoding == Some(UTF_8) {
2264
+ (0..self.bytes.len()).filter(|index| !matches!(self.bytes[*index], 0x80..=0xbf)).collect()
2265
+ } else {
2266
+ (0..self.bytes.len()).collect()
2267
+ }
2268
+ }
2269
+
2270
+ /// `String#size`.
2271
+ fn char_count(&self) -> usize {
2272
+ self.char_starts().len()
2273
+ }
2274
+
2275
+ /// `self[start..finish]` with character indexes, negative ones counting
2276
+ /// from the end; `None` (Ruby's nil) when `start` is out of range.
2277
+ fn slice(&self, start: i64, finish: i64) -> Option<Code> {
2278
+ let starts = self.char_starts();
2279
+ let length = starts.len() as i64;
2280
+ let start = if start < 0 { start + length } else { start };
2281
+ if start < 0 || start > length {
2282
+ return None;
2283
+ }
2284
+ let finish = if finish < 0 { finish + length } else { finish };
2285
+ let finish = (finish + 1).min(length).max(start);
2286
+ let byte_at = |index: i64| starts.get(index as usize).copied().unwrap_or(self.bytes.len());
2287
+ Some(Code::new(self.bytes[byte_at(start)..byte_at(finish)].to_vec(), self.encoding.unwrap_or(UTF_8)))
2288
+ }
2289
+
2290
+ /// The bytes as text, for an exception message.
2291
+ fn lossy(&self) -> String {
2292
+ String::from_utf8_lossy(&self.bytes).into_owned()
2293
+ }
2294
+ }
2295
+
2296
+ /// The bytes as text, for an exception message.
2297
+ impl std::fmt::Display for Code {
2298
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2299
+ formatter.write_str(&String::from_utf8_lossy(&self.bytes))
2300
+ }
2301
+ }
2302
+
2303
+ /// A piece of `"#{a}#{b}"`.
2304
+ trait Piece {
2305
+ fn append_to(&self, code: &mut Code) -> Result<()>;
2306
+ }
2307
+
2308
+ impl Piece for str {
2309
+ fn append_to(&self, code: &mut Code) -> Result<()> {
2310
+ code.push_str(self);
2311
+ Ok(())
2312
+ }
2313
+ }
2314
+
2315
+ impl Piece for Code {
2316
+ fn append_to(&self, code: &mut Code) -> Result<()> {
2317
+ code.push_code(self)
2318
+ }
2319
+ }
2320
+
2321
+ /// nil interpolates as "".
2322
+ impl Piece for Option<Code> {
2323
+ fn append_to(&self, code: &mut Code) -> Result<()> {
2324
+ match self {
2325
+ Some(piece) => code.push_code(piece),
2326
+ None => Ok(()),
2327
+ }
2328
+ }
2329
+ }
2330
+
2331
+ impl<T: Piece + ?Sized> Piece for &T {
2332
+ fn append_to(&self, code: &mut Code) -> Result<()> {
2333
+ (**self).append_to(code)
2334
+ }
2335
+ }
2336
+
2337
+
2338
+ /// `Array#join(separator)`; nil joins as "".
2339
+ fn join(parts: &[Option<Code>], separator: &str) -> Result<Code> {
2340
+ let mut code = Code::default();
2341
+ for (index, part) in parts.iter().enumerate() {
2342
+ if index > 0 {
2343
+ code.push_str(separator);
2344
+ }
2345
+ part.append_to(&mut code)?;
2346
+ }
2347
+ Ok(code)
2348
+ }
2349
+
2350
+ fn join_codes(parts: &[Code], separator: &str) -> Result<Code> {
2351
+ let parts: Vec<Option<Code>> = parts.iter().cloned().map(Some).collect();
2352
+ join(&parts, separator)
2353
+ }
2354
+
2355
+ /// `Array#join(separator)` of sexp elements: a sexp (an Array) is joined
2356
+ /// recursively with the same separator, anything else with `to_s`.
2357
+ fn join_flat(tree: &Tree, elements: &[Element<'_>], separator: &str) -> Result<Code> {
2358
+ let mut parts = Vec::with_capacity(elements.len());
2359
+ for element in elements {
2360
+ parts.push(Some(match element {
2361
+ Element::Sexp(sexp) => join_flat(tree, &sexp.elements, separator)?,
2362
+ other => to_s_element(tree, Some(other))?,
2363
+ }));
2364
+ }
2365
+ join(&parts, separator)
2366
+ }
2367
+
2368
+ /// Ruby raises `ArgumentError` when a regexp is matched against a string
2369
+ /// with an invalid byte sequence.
2370
+ fn check_regexp_target(code: &Code) -> Result<()> {
2371
+ if code.encoding == Some(UTF_8) && std::str::from_utf8(&code.bytes).is_err() {
2372
+ return Err(RubyException { class: "ArgumentError", message: "invalid byte sequence in UTF-8".to_string() });
2373
+ }
2374
+ Ok(())
2375
+ }
2376
+
2377
+ /// `Ruby2Ruby#indent`: `@indent` before every line
2378
+ /// (`s.to_s.split(/\n/)`, which drops trailing empty lines).
2379
+ fn indent(code: Option<&Code>) -> Result<Code> {
2380
+ let Some(code) = code else {
2381
+ return Ok(Code::default());
2382
+ };
2383
+ check_regexp_target(code)?;
2384
+ let mut lines: Vec<&[u8]> = code.bytes.split(|byte| *byte == b'\n').collect();
2385
+ while lines.last().is_some_and(|line| line.is_empty()) {
2386
+ lines.pop();
2387
+ }
2388
+ let mut bytes = Vec::with_capacity(code.bytes.len() + INDENT.len() * lines.len());
2389
+ for (index, line) in lines.iter().enumerate() {
2390
+ if index > 0 {
2391
+ bytes.push(b'\n');
2392
+ }
2393
+ bytes.extend_from_slice(INDENT.as_bytes());
2394
+ bytes.extend_from_slice(line);
2395
+ }
2396
+ Ok(Code { bytes, encoding: code.encoding })
2397
+ }
2398
+
2399
+ /// `String#lines`: lines keeping their "\n".
2400
+ fn lines(bytes: &[u8]) -> Vec<&[u8]> {
2401
+ bytes.split_inclusive(|byte| *byte == b'\n').collect()
2402
+ }
2403
+
2404
+ /// `String#strip`: leading and trailing whitespace and NULs removed.
2405
+ fn strip(code: &Code) -> Code {
2406
+ let is_strippable = |byte: &u8| matches!(byte, b'\0' | b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r');
2407
+ let start = code.bytes.iter().position(|byte| !is_strippable(byte)).unwrap_or(code.bytes.len());
2408
+ let end = code.bytes.iter().rposition(|byte| !is_strippable(byte)).map_or(start, |index| index + 1);
2409
+ Code::new(code.bytes[start..end.max(start)].to_vec(), code.encoding.unwrap_or(UTF_8))
2410
+ }
2411
+
2412
+ /// `String#chomp`: one trailing "\r\n", "\n" or "\r" removed.
2413
+ fn chomp(code: &Code) -> Code {
2414
+ let bytes = &code.bytes;
2415
+ let end = if bytes.ends_with(b"\r\n") {
2416
+ bytes.len() - 2
2417
+ } else if bytes.ends_with(b"\n") || bytes.ends_with(b"\r") {
2418
+ bytes.len() - 1
2419
+ } else {
2420
+ bytes.len()
2421
+ };
2422
+ Code::new(bytes[..end].to_vec(), code.encoding.unwrap_or(UTF_8))
2423
+ }
2424
+
2425
+ /// `String#chomp(suffix)`.
2426
+ fn chomp_suffix<'a>(bytes: &'a [u8], suffix: &[u8]) -> &'a [u8] {
2427
+ bytes.strip_suffix(suffix).unwrap_or(bytes)
2428
+ }
2429
+
2430
+ fn contains(bytes: &[u8], needle: &[u8]) -> bool {
2431
+ bytes.windows(needle.len()).any(|window| window == needle)
2432
+ }
2433
+
2434
+ /// `/\A...\z/`-free `/(^|\n)word/`: a line starts with `word`.
2435
+ fn has_line_starting_with(bytes: &[u8], word: &[u8]) -> bool {
2436
+ if bytes.starts_with(word) {
2437
+ return true;
2438
+ }
2439
+ let mut needle = vec![b'\n'];
2440
+ needle.extend_from_slice(word);
2441
+ contains(bytes, &needle)
2442
+ }
2443
+
2444
+ /// `/^end\z/`: the last line is exactly `word`.
2445
+ fn is_line_at_end(bytes: &[u8], word: &[u8]) -> bool {
2446
+ bytes.ends_with(word) && (bytes.len() == word.len() || bytes[bytes.len() - word.len() - 1] == b'\n')
2447
+ }
2448
+
2449
+ /// `name =~ /SUFFIX$/` for a Symbol name: `suffix` at the end, or before a
2450
+ /// newline.
2451
+ fn matches_end_of_line(bytes: &[u8], suffix: &[u8]) -> bool {
2452
+ let mut position = 0;
2453
+ while let Some(offset) = bytes[position..].windows(suffix.len()).position(|window| window == suffix) {
2454
+ let end = position + offset + suffix.len();
2455
+ if end == bytes.len() || bytes[end] == b'\n' {
2456
+ return true;
2457
+ }
2458
+ position += offset + 1;
2459
+ }
2460
+ false
2461
+ }
2462
+
2463
+ /// Ruby's `\s`: space, tab, newline, vertical tab, form feed, carriage
2464
+ /// return.
2465
+ fn is_space(byte: u8) -> bool {
2466
+ matches!(byte, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
2467
+ }
2468
+
2469
+ /// `code =~ /^\s*$/`: some line holds only whitespace (or the string is
2470
+ /// empty). `^` does not match after a newline that ends the string.
2471
+ fn has_blank_line(bytes: &[u8]) -> bool {
2472
+ if bytes.is_empty() {
2473
+ return true;
2474
+ }
2475
+ let mut line_start = 0;
2476
+ while line_start < bytes.len() {
2477
+ let line_end = bytes[line_start..].iter().position(|byte| *byte == b'\n').map_or(bytes.len(), |offset| line_start + offset);
2478
+ if bytes[line_start..line_end].iter().all(|byte| is_space(*byte)) {
2479
+ return true;
2480
+ }
2481
+ line_start = line_end + 1;
2482
+ }
2483
+ false
2484
+ }
2485
+
2486
+ /// `gsub(/\n\s*\n+/, "\n")`: from a newline to the last newline of the
2487
+ /// whitespace after it becomes one newline.
2488
+ fn squeeze_blank_lines(bytes: &[u8]) -> Vec<u8> {
2489
+ let mut result = Vec::with_capacity(bytes.len());
2490
+ let mut position = 0;
2491
+ while position < bytes.len() {
2492
+ if bytes[position] == b'\n' {
2493
+ let run_end = bytes[position + 1..].iter().position(|byte| !is_space(*byte)).map_or(bytes.len(), |offset| position + 1 + offset);
2494
+ if let Some(last_newline) = bytes[position + 1..run_end].iter().rposition(|byte| *byte == b'\n') {
2495
+ result.push(b'\n');
2496
+ position = position + 1 + last_newline + 1;
2497
+ continue;
2498
+ }
2499
+ }
2500
+ result.push(bytes[position]);
2501
+ position += 1;
2502
+ }
2503
+ result
2504
+ }
2505
+
2506
+ /// `sub(/\n\s*end\z/, "")`: the final `end` and the whitespace before it,
2507
+ /// from that whitespace's first newline.
2508
+ fn remove_trailing_end(bytes: &[u8]) -> Vec<u8> {
2509
+ if !bytes.ends_with(b"end") {
2510
+ return bytes.to_vec();
2511
+ }
2512
+ let end_start = bytes.len() - 3;
2513
+ let mut run_start = end_start;
2514
+ while run_start > 0 && is_space(bytes[run_start - 1]) {
2515
+ run_start -= 1;
2516
+ }
2517
+ match bytes[run_start..end_start].iter().position(|byte| *byte == b'\n') {
2518
+ Some(offset) => bytes[..run_start + offset].to_vec(),
2519
+ None => bytes.to_vec(),
2520
+ }
2521
+ }
2522
+
2523
+ /// `sub(/\(\)$/, "")`: the first `()` at the end of a line removed.
2524
+ fn remove_empty_parens_at_end_of_line(bytes: &[u8]) -> Vec<u8> {
2525
+ let found = (0..bytes.len().saturating_sub(1))
2526
+ .find(|index| &bytes[*index..*index + 2] == b"()" && (index + 2 == bytes.len() || bytes[index + 2] == b'\n'));
2527
+ match found {
2528
+ Some(index) => [&bytes[..index], &bytes[index + 2..]].concat(),
2529
+ None => bytes.to_vec(),
2530
+ }
2531
+ }
2532
+
2533
+ /// `sub(/=$/, "")`: the first `=` at the end of a line removed.
2534
+ fn remove_equals_at_end_of_line(bytes: &[u8]) -> Vec<u8> {
2535
+ let found = (0..bytes.len()).find(|index| bytes[*index] == b'=' && (index + 1 == bytes.len() || bytes[index + 1] == b'\n'));
2536
+ match found {
2537
+ Some(index) => [&bytes[..index], &bytes[index + 1..]].concat(),
2538
+ None => bytes.to_vec(),
2539
+ }
2540
+ }
2541
+
2542
+ /// `sub(/\n\s*/, " ")`: the first newline and the whitespace after it
2543
+ /// become a space.
2544
+ fn join_first_line_break(bytes: &[u8]) -> Vec<u8> {
2545
+ let Some(newline) = bytes.iter().position(|byte| *byte == b'\n') else {
2546
+ return bytes.to_vec();
2547
+ };
2548
+ let rest = bytes[newline + 1..].iter().position(|byte| !is_space(*byte)).map_or(bytes.len(), |offset| newline + 1 + offset);
2549
+ [&bytes[..newline], b" ", &bytes[rest..]].concat()
2550
+ }
2551
+
2552
+ /// `gsub(/(\A|[^\\])\//, '\1\/')`: a `/` not after a backslash gets one.
2553
+ fn escape_slashes(bytes: &[u8]) -> Vec<u8> {
2554
+ let mut result = Vec::with_capacity(bytes.len());
2555
+ let mut position = 0;
2556
+ while position < bytes.len() {
2557
+ if position == 0 && bytes[0] == b'/' {
2558
+ result.extend_from_slice(b"\\/");
2559
+ position = 1;
2560
+ } else if bytes[position] != b'\\' && bytes.get(position + 1) == Some(&b'/') {
2561
+ result.push(bytes[position]);
2562
+ result.extend_from_slice(b"\\/");
2563
+ position += 2;
2564
+ } else {
2565
+ result.push(bytes[position]);
2566
+ position += 1;
2567
+ }
2568
+ }
2569
+ result
2570
+ }
2571
+
2572
+ /// `gsub(/`/, '\`')`: in a replacement string "\`" is the text before the
2573
+ /// match, so each backtick becomes everything before it.
2574
+ fn replace_backticks_with_prematch(bytes: &[u8]) -> Vec<u8> {
2575
+ let mut result = Vec::with_capacity(bytes.len());
2576
+ for (index, byte) in bytes.iter().enumerate() {
2577
+ if *byte == b'`' {
2578
+ result.extend_from_slice(&bytes[..index]);
2579
+ } else {
2580
+ result.push(*byte);
2581
+ }
2582
+ }
2583
+ result
2584
+ }
2585
+
2586
+ // -------------------------------------------------------------------------
2587
+ // Ruby's to_s and inspect
2588
+
2589
+ /// `to_s` of an element (what `"#{element}"` interpolates).
2590
+ fn to_s_element(tree: &Tree, element: Option<&Element<'_>>) -> Result<Code> {
2591
+ match element {
2592
+ None | Some(Element::Nil) => Ok(Code::default()),
2593
+ Some(Element::Symbol(symbol)) => Ok(symbol.to_code()),
2594
+ Some(Element::Text(code)) => Ok(code.clone()),
2595
+ // Sexp#to_s is inspect.
2596
+ Some(Element::Sexp(sexp)) => Ok(inspect_sexp(tree, sexp)),
2597
+ Some(Element::Value(value)) => to_s_value(tree, value),
2598
+ }
2599
+ }
2600
+
2601
+ /// `"%s" % [x]` where `x` may be nil: "" for nil.
2602
+ fn to_s_or_nil(tree: &Tree, element: Option<&Element<'_>>) -> Result<Option<Code>> {
2603
+ match element {
2604
+ None | Some(Element::Nil) => Ok(None),
2605
+ other => to_s_element(tree, other).map(Some),
2606
+ }
2607
+ }
2608
+
2609
+ /// `to_s` of a tree value.
2610
+ fn to_s_value(tree: &Tree, value: &Value) -> Result<Code> {
2611
+ match value {
2612
+ Value::Nil => Ok(Code::default()),
2613
+ Value::True => Ok(Code::from("true")),
2614
+ Value::False => Ok(Code::from("false")),
2615
+ Value::Symbol(id) => {
2616
+ let (bytes, encoding) = tree.symbol(*id);
2617
+ Ok(Code::new(bytes.to_vec(), encoding))
2618
+ }
2619
+ Value::String(string) => Ok(Code::new(string.bytes.clone(), string.encoding)),
2620
+ Value::Integer(integer) => Ok(Code::from(integer.to_s().as_str())),
2621
+ Value::Float(float) => Ok(Code::from(float_to_s(*float).as_str())),
2622
+ Value::Rational(rational) => Ok(Code::from(format!("{}/{}", rational.0.to_s(), rational.1.to_s()).as_str())),
2623
+ Value::Sexp(id) => Ok(inspect_tree_sexp(tree, *id)),
2624
+ // Array#to_s is inspect.
2625
+ Value::Array(_) => Ok(inspect_value(tree, value)),
2626
+ Value::Complex(_) | Value::Range(_) | Value::Regexp(_) => {
2627
+ Err(not_ported(&format!("{}#to_s", class_name(Some(&Element::Value(value))))))
2628
+ }
2629
+ }
2630
+ }
2631
+
2632
+ /// `inspect` of an element.
2633
+ fn inspect_element(tree: &Tree, element: Option<&Element<'_>>) -> Code {
2634
+ match element {
2635
+ None | Some(Element::Nil) => Code::from("nil"),
2636
+ Some(Element::Sexp(sexp)) => inspect_sexp(tree, sexp),
2637
+ Some(Element::Symbol(symbol)) => inspect_symbol(&symbol.bytes, symbol.encoding),
2638
+ Some(Element::Text(code)) => inspect_string(&code.bytes, code.encoding.unwrap_or(UTF_8)),
2639
+ Some(Element::Value(value)) => inspect_value(tree, value),
2640
+ }
2641
+ }
2642
+
2643
+ /// `Sexp#inspect`: `s(a, b, ...)`.
2644
+ fn inspect_sexp(tree: &Tree, sexp: &Sexp<'_>) -> Code {
2645
+ let parts: Vec<Code> = sexp.elements.iter().map(|element| inspect_element(tree, Some(element))).collect();
2646
+ inspect_list("s(", &parts, ")")
2647
+ }
2648
+
2649
+ fn inspect_tree_sexp(tree: &Tree, id: SexpId) -> Code {
2650
+ let parts: Vec<Code> = tree.get(id).elements.iter().map(|value| inspect_value(tree, value)).collect();
2651
+ inspect_list("s(", &parts, ")")
2652
+ }
2653
+
2654
+ /// The parts joined with ", " between `open` and `close`. Inspect strings
2655
+ /// never conflict in encoding: non-ASCII ones are all UTF-8 or escaped.
2656
+ fn inspect_list(open: &str, parts: &[Code], close: &str) -> Code {
2657
+ let mut code = Code::from(open);
2658
+ for (index, part) in parts.iter().enumerate() {
2659
+ if index > 0 {
2660
+ code.push_str(", ");
2661
+ }
2662
+ if code.push_code(part).is_err() {
2663
+ code.bytes.extend_from_slice(&part.bytes);
2664
+ }
2665
+ }
2666
+ code.push_str(close);
2667
+ code
2668
+ }
2669
+
2670
+ /// `inspect` of a tree value.
2671
+ fn inspect_value(tree: &Tree, value: &Value) -> Code {
2672
+ match value {
2673
+ Value::Nil => Code::from("nil"),
2674
+ Value::True => Code::from("true"),
2675
+ Value::False => Code::from("false"),
2676
+ Value::Symbol(id) => {
2677
+ let (bytes, encoding) = tree.symbol(*id);
2678
+ inspect_symbol(bytes, encoding)
2679
+ }
2680
+ Value::String(string) => inspect_string(&string.bytes, string.encoding),
2681
+ Value::Integer(integer) => Code::from(integer.to_s().as_str()),
2682
+ Value::Float(float) => Code::from(float_to_s(*float).as_str()),
2683
+ Value::Rational(rational) => Code::from(format!("({}/{})", rational.0.to_s(), rational.1.to_s()).as_str()),
2684
+ Value::Complex(complex) => inspect_complex(tree, &complex.0, &complex.1),
2685
+ Value::Range(range) => inspect_range(range),
2686
+ Value::Regexp(regexp) => inspect_regexp(&regexp.source, regexp.options, regexp.encoding),
2687
+ Value::Array(elements) => {
2688
+ let parts: Vec<Code> = elements.iter().map(|element| inspect_value(tree, element)).collect();
2689
+ inspect_list("[", &parts, "]")
2690
+ }
2691
+ Value::Sexp(id) => inspect_tree_sexp(tree, *id),
2692
+ }
2693
+ }
2694
+
2695
+ /// `Complex#inspect` (`f_format`): `(real+imaginaryi)`, with `*` before
2696
+ /// the `i` when the imaginary part does not end in a digit.
2697
+ fn inspect_complex(tree: &Tree, real: &Value, imaginary: &Value) -> Code {
2698
+ let mut text = inspect_value(tree, real).lossy();
2699
+ let negative = match imaginary {
2700
+ Value::Integer(integer) => integer.negative,
2701
+ Value::Float(float) => !float.is_nan() && float.is_sign_negative(),
2702
+ Value::Rational(rational) => rational.0.negative,
2703
+ _ => false,
2704
+ };
2705
+ text.push(if negative { '-' } else { '+' });
2706
+ let magnitude = match imaginary {
2707
+ Value::Integer(integer) => Value::integer(Integer::new(false, &integer.limbs)),
2708
+ Value::Float(float) => Value::Float(float.abs()),
2709
+ Value::Rational(rational) => {
2710
+ Value::Rational(Box::new((Integer::new(false, &rational.0.limbs), rational.1.clone())))
2711
+ }
2712
+ other => other.clone(),
2713
+ };
2714
+ text.push_str(&inspect_value(tree, &magnitude).lossy());
2715
+ if !text.ends_with(|character: char| character.is_ascii_digit()) {
2716
+ text.push('*');
2717
+ }
2718
+ text.push('i');
2719
+ Code::from(format!("({text})").as_str())
2720
+ }
2721
+
2722
+ /// `Range#inspect`: the beginning unless it is nil (and the end is not),
2723
+ /// the end unless it is nil (and the beginning is not).
2724
+ fn inspect_range(range: &(Option<Integer>, Option<Integer>, bool)) -> Code {
2725
+ let (first, last, exclude_end) = range;
2726
+ let mut text = String::new();
2727
+ if first.is_some() || last.is_none() {
2728
+ text.push_str(&first.as_ref().map_or("nil".to_string(), Integer::to_s));
2729
+ }
2730
+ text.push_str(if *exclude_end { "..." } else { ".." });
2731
+ if first.is_none() || last.is_some() {
2732
+ text.push_str(&last.as_ref().map_or("nil".to_string(), Integer::to_s));
2733
+ }
2734
+ Code::from(text.as_str())
2735
+ }
2736
+
2737
+ /// `Symbol#inspect` (`sym_inspect`): `:name` when the name is a valid
2738
+ /// symbol name that prints as is, otherwise `:"..."` (`String#inspect`).
2739
+ fn inspect_symbol(bytes: &[u8], encoding: Encoding) -> Code {
2740
+ if is_symname(bytes, encoding) {
2741
+ let mut code = Code::from(":");
2742
+ code.bytes.extend_from_slice(bytes);
2743
+ if !bytes.is_ascii() {
2744
+ code.encoding = Some(encoding);
2745
+ }
2746
+ code
2747
+ } else {
2748
+ // A Symbol whose bytes are all ASCII is US-ASCII, so NUL and other
2749
+ // controls show as \x escapes rather than \u.
2750
+ let encoding = if bytes.is_ascii() { US_ASCII } else { encoding };
2751
+ let inspected = inspect_string(bytes, encoding);
2752
+ let mut code = Code::from(":");
2753
+ code.bytes.extend_from_slice(&inspected.bytes);
2754
+ code.encoding = inspected.encoding;
2755
+ code
2756
+ }
2757
+ }
2758
+
2759
+ /// The US-ASCII encoding's name.
2760
+ const US_ASCII: Encoding = "US-ASCII";
2761
+
2762
+ /// `rb_str_symname_p`: the name is a valid symbol name, in the default
2763
+ /// external encoding (UTF-8) unless it is ASCII, without NULs, and every
2764
+ /// character prints.
2765
+ fn is_symname(bytes: &[u8], encoding: Encoding) -> bool {
2766
+ if encoding != UTF_8 && !bytes.is_ascii() {
2767
+ return false;
2768
+ }
2769
+ if bytes.contains(&0) || symname_type(bytes).is_none() {
2770
+ return false;
2771
+ }
2772
+ match std::str::from_utf8(bytes) {
2773
+ Ok(text) => text.chars().all(|character| is_print(character as u32)),
2774
+ Err(_) => false,
2775
+ }
2776
+ }
2777
+
2778
+ /// Ruby's ID types (`enum ruby_id_types`).
2779
+ #[derive(Clone, Copy, Debug, PartialEq)]
2780
+ enum IdType {
2781
+ Local,
2782
+ Instance,
2783
+ Global,
2784
+ Attrset,
2785
+ Const,
2786
+ Class,
2787
+ Junk,
2788
+ }
2789
+
2790
+ /// `rb_enc_symname_type` with `IDSET_ATTRSET_FOR_SYNTAX` (a local or
2791
+ /// constant name may end in `=`): the name's ID type, or `None` when it is
2792
+ /// not a symbol name. Constants and locals are told apart by an ASCII
2793
+ /// capital only; both allow the same suffixes, so this never changes the
2794
+ /// answer.
2795
+ fn symname_type(name: &[u8]) -> Option<IdType> {
2796
+ let attrset_allowed = |id_type: IdType| matches!(id_type, IdType::Local | IdType::Const);
2797
+ let at = |index: usize| name.get(index).copied().unwrap_or(0);
2798
+ let len = name.len();
2799
+ if len == 0 {
2800
+ return None;
2801
+ }
2802
+
2803
+ // enc_synmane_type_leading_chars: (stop here?, type, bytes read)
2804
+ let (stop, mut id_type, nread) = match at(0) {
2805
+ 0 => return None,
2806
+ b'$' => {
2807
+ if is_special_global_name(&name[1..]) {
2808
+ (true, IdType::Global, len)
2809
+ } else {
2810
+ (false, IdType::Global, 1)
2811
+ }
2812
+ }
2813
+ b'@' => match at(1) {
2814
+ b'@' => (false, IdType::Class, 2),
2815
+ _ => (false, IdType::Instance, 1),
2816
+ },
2817
+ b'<' => match at(1) {
2818
+ b'<' => (true, IdType::Junk, 2),
2819
+ b'=' => match at(2) {
2820
+ b'>' => (true, IdType::Junk, 3),
2821
+ _ => (true, IdType::Junk, 2),
2822
+ },
2823
+ _ => (true, IdType::Junk, 1),
2824
+ },
2825
+ b'>' => match at(1) {
2826
+ b'>' | b'=' => (true, IdType::Junk, 2),
2827
+ _ => (true, IdType::Junk, 1),
2828
+ },
2829
+ b'=' => match at(1) {
2830
+ b'~' => (true, IdType::Junk, 2),
2831
+ b'=' => match at(2) {
2832
+ b'=' => (true, IdType::Junk, 3),
2833
+ _ => (true, IdType::Junk, 2),
2834
+ },
2835
+ _ => return None,
2836
+ },
2837
+ b'*' => match at(1) {
2838
+ b'*' => (true, IdType::Junk, 2),
2839
+ _ => (true, IdType::Junk, 1),
2840
+ },
2841
+ b'+' | b'-' => match at(1) {
2842
+ b'@' => (true, IdType::Junk, 2),
2843
+ _ => (true, IdType::Junk, 1),
2844
+ },
2845
+ b'|' | b'^' | b'&' | b'/' | b'%' | b'~' | b'`' => (true, IdType::Junk, 1),
2846
+ b'[' => match at(1) {
2847
+ b']' => match at(2) {
2848
+ b'=' => (true, IdType::Junk, 3),
2849
+ _ => (true, IdType::Junk, 2),
2850
+ },
2851
+ _ => (false, IdType::Junk, 0),
2852
+ },
2853
+ b'!' => match at(1) {
2854
+ b'=' | b'~' => (true, IdType::Junk, 2),
2855
+ // JUNK is not in IDSET_ATTRSET_FOR_SYNTAX.
2856
+ _ => (true, IdType::Junk, 1),
2857
+ },
2858
+ first if first.is_ascii_uppercase() => (false, IdType::Const, 0),
2859
+ _ => (false, IdType::Local, 0),
2860
+ };
2861
+
2862
+ let mut m = nread;
2863
+ if !stop {
2864
+ if m >= len || (at(m) != b'_' && !at(m).is_ascii_alphabetic() && at(m).is_ascii()) {
2865
+ if len > 1 && name[len - 1] == b'=' {
2866
+ if let Some(prefix_type) = symname_type(&name[..len - 1]) {
2867
+ if attrset_allowed(prefix_type) {
2868
+ return Some(IdType::Attrset);
2869
+ }
2870
+ }
2871
+ }
2872
+ return None;
2873
+ }
2874
+ while m < len && is_identchar(at(m)) {
2875
+ m += utf8_char_length(&name[m..]);
2876
+ }
2877
+ if m < len {
2878
+ match at(m) {
2879
+ b'!' | b'?' => {
2880
+ if matches!(id_type, IdType::Global | IdType::Class | IdType::Instance) {
2881
+ return None;
2882
+ }
2883
+ id_type = IdType::Junk;
2884
+ m += 1;
2885
+ if m + 1 >= len && at(m) == b'=' {
2886
+ if !attrset_allowed(id_type) {
2887
+ return None;
2888
+ }
2889
+ id_type = IdType::Attrset;
2890
+ m += 1;
2891
+ }
2892
+ }
2893
+ b'=' => {
2894
+ if !attrset_allowed(id_type) {
2895
+ return None;
2896
+ }
2897
+ id_type = IdType::Attrset;
2898
+ m += 1;
2899
+ }
2900
+ _ => {}
2901
+ }
2902
+ }
2903
+ }
2904
+ if m == len {
2905
+ Some(id_type)
2906
+ } else {
2907
+ None
2908
+ }
2909
+ }
2910
+
2911
+ /// `is_special_global_name`: `$` followed by one punctuation character,
2912
+ /// `-` and one identifier character, or digits.
2913
+ fn is_special_global_name(rest: &[u8]) -> bool {
2914
+ let Some(first) = rest.first() else {
2915
+ return false;
2916
+ };
2917
+ let end = if b"~*$?!@/\\;,.=:<>\"&`'+0".contains(first) {
2918
+ 1
2919
+ } else if *first == b'-' {
2920
+ match rest.get(1) {
2921
+ None => return false,
2922
+ Some(next) if is_identchar(*next) => 1 + utf8_char_length(&rest[1..]),
2923
+ Some(_) => 1,
2924
+ }
2925
+ } else if first.is_ascii_digit() {
2926
+ rest.iter().take_while(|byte| byte.is_ascii_digit()).count()
2927
+ } else {
2928
+ return false;
2929
+ };
2930
+ end == rest.len()
2931
+ }
2932
+
2933
+ /// `is_identchar`: an ASCII letter, digit or `_`, or any non-ASCII byte.
2934
+ fn is_identchar(byte: u8) -> bool {
2935
+ byte.is_ascii_alphanumeric() || byte == b'_' || !byte.is_ascii()
2936
+ }
2937
+
2938
+ /// `rb_enc_mbclen` in UTF-8: the length of the character at the start, 1
2939
+ /// for an invalid byte.
2940
+ fn utf8_char_length(bytes: &[u8]) -> usize {
2941
+ decode_utf8(bytes).map_or(1, |(_, length)| length)
2942
+ }
2943
+
2944
+ /// The UTF-8 character at the start of `bytes` and its length.
2945
+ fn decode_utf8(bytes: &[u8]) -> Option<(u32, usize)> {
2946
+ let length = match bytes.first()? {
2947
+ 0x00..=0x7f => 1,
2948
+ 0xc2..=0xdf => 2,
2949
+ 0xe0..=0xef => 3,
2950
+ 0xf0..=0xf4 => 4,
2951
+ _ => return None,
2952
+ };
2953
+ let text = std::str::from_utf8(bytes.get(..length)?).ok()?;
2954
+ Some((text.chars().next()? as u32, length))
2955
+ }
2956
+
2957
+ /// `rb_enc_isprint` for a character: ASCII 0x20..0x7E, or a non-ASCII
2958
+ /// Unicode character for which [`unicode_is_print`] holds.
2959
+ fn is_print(codepoint: u32) -> bool {
2960
+ if codepoint < 0x80 {
2961
+ (0x20..0x7f).contains(&codepoint)
2962
+ } else {
2963
+ unicode_is_print(codepoint)
2964
+ }
2965
+ }
2966
+
2967
+ /// `[[:print:]]` for a non-ASCII Unicode character, approximated: every
2968
+ /// character but the C1 controls, the line and paragraph separators,
2969
+ /// surrogates and noncharacters. Onigmo's table also leaves out unassigned
2970
+ /// code points and a few format characters.
2971
+ fn unicode_is_print(codepoint: u32) -> bool {
2972
+ !((0x80..=0x9f).contains(&codepoint)
2973
+ || codepoint == 0x2028
2974
+ || codepoint == 0x2029
2975
+ || (0xd800..=0xdfff).contains(&codepoint)
2976
+ || (0xfdd0..=0xfdef).contains(&codepoint)
2977
+ || codepoint & 0xfffe == 0xfffe)
2978
+ }
2979
+
2980
+ /// `String#inspect` (`rb_str_inspect`) with UTF-8 as the default external
2981
+ /// encoding.
2982
+ fn inspect_string(bytes: &[u8], encoding: Encoding) -> Code {
2983
+ let unicode = encoding == UTF_8;
2984
+ let mut out = Vec::with_capacity(bytes.len() + 2);
2985
+ out.push(b'"');
2986
+ let mut position = 0;
2987
+ while position < bytes.len() {
2988
+ let character = if unicode {
2989
+ decode_utf8(&bytes[position..])
2990
+ } else if encoding == ASCII_8BIT || bytes[position].is_ascii() {
2991
+ Some((u32::from(bytes[position]), 1))
2992
+ } else {
2993
+ None
2994
+ };
2995
+ let Some((c, length)) = character else {
2996
+ out.extend_from_slice(format!("\\x{:02X}", bytes[position]).as_bytes());
2997
+ position += 1;
2998
+ continue;
2999
+ };
3000
+ let next = position + length;
3001
+ let escaped_interpolation = c == u32::from(b'#') && matches!(bytes.get(next), Some(b'$' | b'@' | b'{'));
3002
+ if c == u32::from(b'"') || c == u32::from(b'\\') || escaped_interpolation {
3003
+ out.push(b'\\');
3004
+ out.extend_from_slice(&bytes[position..next]);
3005
+ } else if let Some(escape) = special_escape(c) {
3006
+ out.extend_from_slice(escape.as_bytes());
3007
+ } else if (unicode && is_print(c) && c != 0x85) || (c < 0x80 && is_print(c)) {
3008
+ out.extend_from_slice(&bytes[position..next]);
3009
+ } else {
3010
+ out.extend_from_slice(escaped_char(c, unicode).as_bytes());
3011
+ }
3012
+ position = next;
3013
+ }
3014
+ out.push(b'"');
3015
+ Code::new(out, UTF_8)
3016
+ }
3017
+
3018
+ /// The backslash escapes `String#inspect` uses for control characters.
3019
+ fn special_escape(c: u32) -> Option<&'static str> {
3020
+ Some(match c {
3021
+ 0x0a => "\\n",
3022
+ 0x0d => "\\r",
3023
+ 0x09 => "\\t",
3024
+ 0x0c => "\\f",
3025
+ 0x0b => "\\v",
3026
+ 0x08 => "\\b",
3027
+ 0x07 => "\\a",
3028
+ 0x1b => "\\e",
3029
+ _ => return None,
3030
+ })
3031
+ }
3032
+
3033
+ /// `rb_str_buf_cat_escaped_char`.
3034
+ fn escaped_char(c: u32, unicode: bool) -> String {
3035
+ if unicode {
3036
+ if c < 0x7f && is_print(c) {
3037
+ char::from_u32(c).map(String::from).unwrap_or_default()
3038
+ } else if c < 0x10000 {
3039
+ format!("\\u{c:04X}")
3040
+ } else {
3041
+ format!("\\u{{{c:X}}}")
3042
+ }
3043
+ } else if c < 0x100 {
3044
+ format!("\\x{c:02X}")
3045
+ } else {
3046
+ format!("\\x{{{c:X}}}")
3047
+ }
3048
+ }
3049
+
3050
+ /// `String#dump` (`rb_str_dump`): ASCII only, `\u` escapes for UTF-8
3051
+ /// characters, `\x` for other non-printing bytes.
3052
+ fn dump(bytes: &[u8], encoding: Encoding) -> Code {
3053
+ let utf8 = encoding == UTF_8;
3054
+ let mut out = Vec::with_capacity(bytes.len() + 2);
3055
+ out.push(b'"');
3056
+ let mut position = 0;
3057
+ while position < bytes.len() {
3058
+ let c = bytes[position];
3059
+ position += 1;
3060
+ match c {
3061
+ b'"' | b'\\' => out.extend_from_slice(&[b'\\', c]),
3062
+ b'#' => {
3063
+ if matches!(bytes.get(position), Some(b'$' | b'@' | b'{')) {
3064
+ out.push(b'\\');
3065
+ }
3066
+ out.push(b'#');
3067
+ }
3068
+ b'\n' => out.extend_from_slice(b"\\n"),
3069
+ b'\r' => out.extend_from_slice(b"\\r"),
3070
+ b'\t' => out.extend_from_slice(b"\\t"),
3071
+ 0x0c => out.extend_from_slice(b"\\f"),
3072
+ 0x0b => out.extend_from_slice(b"\\v"),
3073
+ 0x08 => out.extend_from_slice(b"\\b"),
3074
+ 0x07 => out.extend_from_slice(b"\\a"),
3075
+ 0x1b => out.extend_from_slice(b"\\e"),
3076
+ 0x20..=0x7e => out.push(c),
3077
+ _ => {
3078
+ if utf8 && c > 0x7f {
3079
+ if let Some((codepoint, length)) = decode_utf8(&bytes[position - 1..]) {
3080
+ position += length - 1;
3081
+ let escape = if codepoint <= 0xffff { format!("\\u{codepoint:04X}") } else { format!("\\u{{{codepoint:X}}}") };
3082
+ out.extend_from_slice(escape.as_bytes());
3083
+ continue;
3084
+ }
3085
+ }
3086
+ out.extend_from_slice(format!("\\x{c:02X}").as_bytes());
3087
+ }
3088
+ }
3089
+ }
3090
+ out.push(b'"');
3091
+ Code { bytes: out, encoding: None }
3092
+ }
3093
+
3094
+ /// `Regexp#inspect` (`rb_reg_desc`) with UTF-8 as the default external
3095
+ /// encoding: `/source/` with `/` escaped, then the `m`, `i`, `x` and `n`
3096
+ /// flags.
3097
+ fn inspect_regexp(source: &[u8], options: u32, encoding: Encoding) -> Code {
3098
+ const IGNORECASE: u32 = 1;
3099
+ const EXTENDED: u32 = 2;
3100
+ const MULTILINE: u32 = 4;
3101
+ const NOENCODING: u32 = 32;
3102
+
3103
+ let mut out = vec![b'/'];
3104
+ out.extend_from_slice(&regexp_source_text(source, encoding));
3105
+ out.push(b'/');
3106
+ if options & MULTILINE != 0 {
3107
+ out.push(b'm');
3108
+ }
3109
+ if options & IGNORECASE != 0 {
3110
+ out.push(b'i');
3111
+ }
3112
+ if options & EXTENDED != 0 {
3113
+ out.push(b'x');
3114
+ }
3115
+ if options & NOENCODING != 0 {
3116
+ out.push(b'n');
3117
+ }
3118
+ Code::new(out, encoding)
3119
+ }
3120
+
3121
+ /// `rb_reg_expr_str` with `/` as the terminator: the source as is when
3122
+ /// every character prints (non-ASCII ones only in the default external
3123
+ /// encoding) and there is no unescaped `/`; otherwise escaped.
3124
+ fn regexp_source_text(source: &[u8], encoding: Encoding) -> Vec<u8> {
3125
+ let utf8 = encoding == UTF_8;
3126
+ let valid = !utf8 || std::str::from_utf8(source).is_ok();
3127
+ let needs_escape = !valid
3128
+ || source.iter().any(|byte| {
3129
+ if byte.is_ascii() {
3130
+ *byte == b'/' || !(0x20..0x7f).contains(byte)
3131
+ } else {
3132
+ !utf8
3133
+ }
3134
+ });
3135
+ if !needs_escape {
3136
+ return source.to_vec();
3137
+ }
3138
+
3139
+ let mut out = Vec::with_capacity(source.len() + 4);
3140
+ let mut position = 0;
3141
+ while position < source.len() {
3142
+ let byte = source[position];
3143
+ if byte == b'\\' && position + 1 < source.len() {
3144
+ let next_length = if utf8 { utf8_char_length(&source[position + 1..]) } else { 1 };
3145
+ let end = (position + 1 + next_length).min(source.len());
3146
+ out.extend_from_slice(&source[position..end]);
3147
+ position = end;
3148
+ } else if !byte.is_ascii() {
3149
+ match if utf8 { decode_utf8(&source[position..]) } else { None } {
3150
+ Some((codepoint, length)) => {
3151
+ out.extend_from_slice(escaped_char(codepoint, true).as_bytes());
3152
+ position += length;
3153
+ }
3154
+ None => {
3155
+ out.extend_from_slice(format!("\\x{byte:02X}").as_bytes());
3156
+ position += 1;
3157
+ }
3158
+ }
3159
+ } else if byte == b'/' {
3160
+ out.extend_from_slice(b"\\/");
3161
+ position += 1;
3162
+ } else if (0x20..0x7f).contains(&byte) || is_space(byte) {
3163
+ out.push(byte);
3164
+ position += 1;
3165
+ } else {
3166
+ out.extend_from_slice(format!("\\x{byte:02X}").as_bytes());
3167
+ position += 1;
3168
+ }
3169
+ }
3170
+ out
3171
+ }
3172
+
3173
+ #[cfg(test)]
3174
+ mod tests {
3175
+ use super::*;
3176
+
3177
+ fn code(text: &str) -> Code {
3178
+ Code::from(text)
3179
+ }
3180
+
3181
+ /// `Ruby2Ruby.new.process(sexp.deep_clone)` for each statement of a
3182
+ /// source, as Ruby 3.3.14 with ruby2ruby 2.6.2 prints them.
3183
+ #[test]
3184
+ fn statements_print_as_ruby2ruby_does() {
3185
+ let source = b"# c\ndef m\n 1\nend\ncase x\nin {a: 1, **nil} then 1\nin [Integer => y, *rest] then 2\nend\n\
3186
+ /a#{b}c/io\n`ls #{x} \\`y`\nx = *a\ndef foo(...) = bar(...)\nclass A; end\nfoo(a, b: 1)\n";
3187
+ let parsed = crate::parse_source(source, "t.rb", "3.3.14");
3188
+ let Ok((tree, Value::Sexp(root))) = &parsed.outcome else { panic!("parsed") };
3189
+ let comments = Comments::new(source, tree);
3190
+ let printed: Vec<String> = tree
3191
+ .each_sexp(*root)
3192
+ .map(|sexp| match sexp_to_ruby(tree, &comments, sexp, &tree.get(sexp).elements) {
3193
+ Ok(text) => String::from_utf8(text.bytes).unwrap(),
3194
+ Err(exception) => format!("{}: {}", exception.class, exception.message),
3195
+ })
3196
+ .collect();
3197
+ assert_eq!(
3198
+ printed,
3199
+ [
3200
+ "# c\ndef m\n 1\nend",
3201
+ "case x\nin { a: 1, **nil } then\n 1\nin [Integer => y, *rest] then\n 2\nend",
3202
+ "/a#{b}c/i",
3203
+ "`ls #{x} y`",
3204
+ "x = *a",
3205
+ "def foo(...)\n bar(...)\nend",
3206
+ "class A\nend",
3207
+ "foo(a, :b => 1)",
3208
+ ]
3209
+ );
3210
+ // A keyword parameter alone has no process_kwarg.
3211
+ let parsed = crate::parse_source(b"def f(k: 1); end\n", "t.rb", "3.3.14");
3212
+ let Ok((tree, _)) = &parsed.outcome else { panic!("parsed") };
3213
+ let kwarg = (0..tree.sexps.len() as SexpId).find(|id| tree.type_name(*id) == b"kwarg").unwrap();
3214
+ let error = sexp_to_ruby(tree, &Comments::default(), kwarg, &tree.get(kwarg).elements).unwrap_err();
3215
+ assert_eq!(error.message, "Bug! Unknown node-type :kwarg to Ruby2Ruby");
3216
+ }
3217
+
3218
+ #[test]
3219
+ fn indent_drops_trailing_empty_lines() {
3220
+ assert_eq!(indent(Some(&code("a\n\nb\n\n"))).unwrap().bytes, b" a\n \n b");
3221
+ assert_eq!(indent(Some(&code(""))).unwrap().bytes, b"");
3222
+ assert_eq!(indent(None).unwrap().bytes, b"");
3223
+ }
3224
+
3225
+ #[test]
3226
+ fn regexp_emulations_match_ruby() {
3227
+ // "a\n" =~ /^$/ is nil in Ruby: ^ does not match at the very end.
3228
+ assert!(!has_blank_line(b"a\n"));
3229
+ assert!(has_blank_line(b"a\n\nb"));
3230
+ assert!(has_blank_line(b""));
3231
+ assert!(has_blank_line(b"a\n \nb"));
3232
+ assert_eq!(squeeze_blank_lines(b"a \n \n b"), b"a \n b");
3233
+ assert_eq!(squeeze_blank_lines(b"a\n\n\nb\nc"), b"a\nb\nc");
3234
+ assert_eq!(remove_trailing_end(b"x\n\n end"), b"x");
3235
+ assert_eq!(remove_trailing_end(b"x end"), b"x end");
3236
+ assert_eq!(remove_empty_parens_at_end_of_line(b"foo()\nbar()"), b"foo\nbar()");
3237
+ assert_eq!(join_first_line_break(b"rescue\n x"), b"rescue x");
3238
+ // "a/b//c".gsub(/(\A|[^\\])\//, '\1\/') and "ab`cd`e".gsub(/`/, '\`')
3239
+ assert_eq!(escape_slashes(b"a/b//c"), br"a\/b\//c");
3240
+ assert_eq!(escape_slashes(b"/x"), br"\/x");
3241
+ assert_eq!(replace_backticks_with_prematch(b"ab`cd`e"), b"ababcdab`cde");
3242
+ }
3243
+
3244
+ #[test]
3245
+ fn strip_removes_nuls_too() {
3246
+ assert_eq!(strip(&code("\0 a \0")).bytes, b"a");
3247
+ }
3248
+
3249
+ #[test]
3250
+ fn symbols_inspect_as_ruby_does() {
3251
+ let inspect = |name: &str| String::from_utf8(inspect_symbol(name.as_bytes(), UTF_8).bytes).unwrap();
3252
+ assert_eq!(inspect("a"), ":a");
3253
+ assert_eq!(inspect("a b"), ":\"a b\"");
3254
+ assert_eq!(inspect("foo="), ":foo=");
3255
+ assert_eq!(inspect("[]="), ":[]=");
3256
+ assert_eq!(inspect("é"), ":é");
3257
+ assert_eq!(inspect("@a"), ":@a");
3258
+ assert_eq!(inspect("$1"), ":$1");
3259
+ assert_eq!(inspect("Foo?"), ":Foo?");
3260
+ assert_eq!(inspect("a?="), ":\"a?=\"");
3261
+ assert_eq!(inspect("$~"), ":$~");
3262
+ assert_eq!(inspect("$-w"), ":$-w");
3263
+ assert_eq!(inspect("$-"), ":\"$-\"");
3264
+ assert_eq!(inspect("!"), ":!");
3265
+ assert_eq!(inspect("!x"), ":\"!x\"");
3266
+ assert_eq!(inspect("a!="), ":\"a!=\"");
3267
+ assert_eq!(inspect("[]?"), ":\"[]?\"");
3268
+ assert_eq!(inspect("Foo="), ":Foo=");
3269
+ assert_eq!(inspect("@a="), ":\"@a=\"");
3270
+ assert_eq!(inspect("["), ":\"[\"");
3271
+ // :"\0__detached_thread__" in timeout.rb: a US-ASCII Symbol.
3272
+ assert_eq!(inspect("\0a"), ":\"\\x00a\"");
3273
+ }
3274
+
3275
+ #[test]
3276
+ fn strings_dump_as_ruby_does() {
3277
+ assert_eq!(dump("é\x01#{".as_bytes(), UTF_8).bytes, b"\"\\u00E9\\x01\\#{\"");
3278
+ assert_eq!(dump(b"\xff", ASCII_8BIT).bytes, br#""\xFF""#);
3279
+ }
3280
+
3281
+ #[test]
3282
+ fn regexps_inspect_as_ruby_does() {
3283
+ let inspect = |source: &str, options| String::from_utf8(inspect_regexp(source.as_bytes(), options, UTF_8).bytes).unwrap();
3284
+ assert_eq!(inspect("x", 32), "/x/n");
3285
+ assert_eq!(inspect("a/b\\/c", 16), "/a\\/b\\/c/");
3286
+ assert_eq!(inspect("é/", 16), "/\\u00E9\\//");
3287
+ assert_eq!(inspect("é", 16), "/é/");
3288
+ assert_eq!(inspect("\x01/", 0), "/\\x01\\//");
3289
+ assert_eq!(inspect("a\nb/", 0), "/a\nb\\//");
3290
+ }
3291
+ }