flog-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,1851 @@
1
+ //! Scores one file's Prism tree the way Flog 4.10.0 scores the ruby_parser
2
+ //! tree that `Prism::Translation::RubyParser` builds from it.
3
+ //!
4
+ //! Each `visit_*`/`process_*` method below corresponds to one translator
5
+ //! method and the Flog `process_*` method that handles its result. Flog's
6
+ //! `process` pushes the sexp type onto `context`; `in_context` does the same
7
+ //! here, because two rules read it: named blocks (`process_iter`) and magic
8
+ //! numbers directly under a constant assignment (`process_lit`).
9
+
10
+ use indexmap::IndexMap;
11
+ use ruby_prism::{
12
+ BlockNode, BlockParametersNode, CallNode, Node, NodeList, ParametersNode, RescueNode,
13
+ StatementsNode,
14
+ };
15
+
16
+ use crate::literal::{dsl_name, is_zero_or_minus_one};
17
+ use crate::scores::{call_score, OtherScore};
18
+ use crate::translation::{match_form, plain_call_type, sexp_type, transparent_child, MatchForm};
19
+
20
+ /// Per-label tallies in Flog's insertion order. Each name keeps its
21
+ /// individual additions so results from several files can be merged with the
22
+ /// same floating-point additions Flog performs.
23
+ pub type Tallies = IndexMap<String, IndexMap<String, Vec<f64>>>;
24
+
25
+ /// An exception Flog itself raises while processing a file (not a syntax
26
+ /// error), with the Ruby exception class it raises.
27
+ #[derive(Clone, Debug, PartialEq, Eq)]
28
+ pub struct FlogException {
29
+ pub class: &'static str,
30
+ pub message: String,
31
+ }
32
+
33
+ /// The value `process_cdecl` receives: the check `val.sexp_type == :iter`
34
+ /// decides whether the constant opens a class scope, and a missing value
35
+ /// (`A, B = ...`) crashes on `nil.sexp_type`.
36
+ #[derive(Clone, Copy, PartialEq, Eq)]
37
+ enum CdeclValue {
38
+ Missing,
39
+ Iter,
40
+ Other,
41
+ }
42
+
43
+ pub struct Scorer<'a> {
44
+ file: &'a str,
45
+ methods_only: bool,
46
+ multiplier: f64,
47
+ context: Vec<&'static str>,
48
+ in_pattern: bool,
49
+ /// MethodBasedSexpProcessor's `@class_stack`, outermost first.
50
+ class_stack: Vec<String>,
51
+ /// MethodBasedSexpProcessor's `@method_stack`, outermost first.
52
+ method_stack: Vec<String>,
53
+ /// MethodBasedSexpProcessor's `@sclass` depth.
54
+ sclass_depth: usize,
55
+ signature_cache: Option<String>,
56
+ pub calls: Tallies,
57
+ pub method_locations: IndexMap<String, String>,
58
+ pub exception: Option<FlogException>,
59
+ }
60
+
61
+ impl<'a> Scorer<'a> {
62
+ pub fn new(file: &'a str, methods_only: bool) -> Self {
63
+ Scorer {
64
+ file,
65
+ methods_only,
66
+ multiplier: 1.0,
67
+ context: Vec::new(),
68
+ in_pattern: false,
69
+ class_stack: Vec::new(),
70
+ method_stack: Vec::new(),
71
+ sclass_depth: 0,
72
+ signature_cache: None,
73
+ calls: IndexMap::new(),
74
+ method_locations: IndexMap::new(),
75
+ exception: None,
76
+ }
77
+ }
78
+
79
+ // ------------------------------------------------------------------
80
+ // Flog and MethodBasedSexpProcessor state
81
+ // ------------------------------------------------------------------
82
+
83
+ /// `Flog#add_to_score`.
84
+ fn add_to_score(&mut self, name: &str, score: f64) {
85
+ if self.exception.is_some() || (self.methods_only && self.method_stack.is_empty()) {
86
+ return;
87
+ }
88
+ let increment = score * self.multiplier;
89
+ let signature = self.signature();
90
+ let tally = match self.calls.get_mut(signature.as_str()) {
91
+ Some(tally) => tally,
92
+ None => self.calls.entry(signature).or_default(),
93
+ };
94
+ match tally.get_mut(name) {
95
+ Some(additions) => additions.push(increment),
96
+ None => {
97
+ tally.insert(name.to_string(), vec![increment]);
98
+ }
99
+ }
100
+ }
101
+
102
+ fn add_other(&mut self, kind: OtherScore) {
103
+ self.add_to_score(kind.name(), kind.score());
104
+ }
105
+
106
+ /// `Flog#penalize_by`: add the bonus, run, then restore the saved value.
107
+ fn penalize_by(&mut self, bonus: f64, body: impl FnOnce(&mut Self)) {
108
+ let old = self.multiplier;
109
+ self.multiplier += bonus;
110
+ body(self);
111
+ self.multiplier = old;
112
+ }
113
+
114
+ /// `SexpProcessor#in_context`, called by `process` for every sexp.
115
+ fn in_context(&mut self, sexp_type: &'static str, body: impl FnOnce(&mut Self)) {
116
+ self.context.push(sexp_type);
117
+ body(self);
118
+ self.context.pop();
119
+ }
120
+
121
+ /// `MethodBasedSexpProcessor#in_klass`, including `with_new_method_stack`.
122
+ fn in_klass(&mut self, name: String, body: impl FnOnce(&mut Self)) {
123
+ self.class_stack.push(name);
124
+ let saved_methods = std::mem::take(&mut self.method_stack);
125
+ self.signature_cache = None;
126
+ body(self);
127
+ self.method_stack = saved_methods;
128
+ self.class_stack.pop();
129
+ self.signature_cache = None;
130
+ }
131
+
132
+ /// `MethodBasedSexpProcessor#in_method`: push the name and record the
133
+ /// location `"file:line-line_max"`.
134
+ fn in_method(&mut self, name: String, line: i32, line_max: i32, body: impl FnOnce(&mut Self)) {
135
+ self.method_stack.push(name);
136
+ self.signature_cache = None;
137
+ let signature = self.signature();
138
+ if self.exception.is_none() {
139
+ self.method_locations
140
+ .insert(signature, format!("{}:{}-{}", self.file, line, line_max));
141
+ }
142
+ body(self);
143
+ self.method_stack.pop();
144
+ self.signature_cache = None;
145
+ }
146
+
147
+ /// `MethodBasedSexpProcessor#in_sklass`, including `with_new_method_stack`.
148
+ fn in_sklass(&mut self, body: impl FnOnce(&mut Self)) {
149
+ self.sclass_depth += 1;
150
+ let saved_methods = std::mem::take(&mut self.method_stack);
151
+ self.signature_cache = None;
152
+ body(self);
153
+ self.method_stack = saved_methods;
154
+ self.sclass_depth -= 1;
155
+ self.signature_cache = None;
156
+ }
157
+
158
+ /// `MethodBasedSexpProcessor#signature`: `klass_name + method_name`.
159
+ fn signature(&mut self) -> String {
160
+ if let Some(signature) = &self.signature_cache {
161
+ return signature.clone();
162
+ }
163
+ let signature = format!("{}{}", self.klass_name(), self.method_name());
164
+ self.signature_cache = Some(signature.clone());
165
+ signature
166
+ }
167
+
168
+ /// `MethodBasedSexpProcessor#klass_name`: the class stack joined with
169
+ /// `::`, then `sub(/\([^\)]+\)$/, "")`; `main` when empty.
170
+ fn klass_name(&self) -> String {
171
+ if self.class_stack.is_empty() {
172
+ return "main".to_string();
173
+ }
174
+ strip_trailing_parenthesized(&self.class_stack.join("::"))
175
+ }
176
+
177
+ /// `MethodBasedSexpProcessor#method_name`: `#name` unless the name
178
+ /// contains `::`; `#none` outside a method.
179
+ fn method_name(&self) -> String {
180
+ let name = self.method_stack.last().map(String::as_str).unwrap_or("none");
181
+ if name.contains("::") {
182
+ name.to_string()
183
+ } else {
184
+ format!("#{name}")
185
+ }
186
+ }
187
+
188
+ fn raise(&mut self, class: &'static str, message: String) {
189
+ if self.exception.is_none() {
190
+ self.exception = Some(FlogException { class, message });
191
+ }
192
+ }
193
+
194
+ // ------------------------------------------------------------------
195
+ // Entry point
196
+ // ------------------------------------------------------------------
197
+
198
+ /// `Flog#flog_ruby!` after parsing: `process` the translated program.
199
+ pub fn score_program(&mut self, program: &Node<'_>) {
200
+ let statements = program.as_program_node().unwrap().statements();
201
+ self.visit_statements(&statements);
202
+ }
203
+
204
+ // ------------------------------------------------------------------
205
+ // Generic dispatch: `process(visit(node))`
206
+ // ------------------------------------------------------------------
207
+
208
+ fn visit_optional(&mut self, node: Option<Node<'_>>) {
209
+ if let Some(node) = node {
210
+ self.visit(&node);
211
+ }
212
+ }
213
+
214
+ fn visit_each(&mut self, nodes: &NodeList<'_>) {
215
+ for node in nodes.iter() {
216
+ self.visit(&node);
217
+ }
218
+ }
219
+
220
+ /// `visit_statements_node`: one statement is visited on its own; two or
221
+ /// more become `s(:block, ...)`, which `process_block` scores at +0.1.
222
+ fn visit_statements(&mut self, statements: &StatementsNode<'_>) {
223
+ let body = statements.body();
224
+ match body.len() {
225
+ 0 => {}
226
+ 1 => self.visit(&body.first().unwrap()),
227
+ _ => self.in_context("block", |s| s.penalize_by(0.1, |s| s.visit_each(&body))),
228
+ }
229
+ }
230
+
231
+ fn visit_optional_statements(&mut self, statements: Option<StatementsNode<'_>>) {
232
+ if let Some(statements) = statements {
233
+ self.visit_statements(&statements);
234
+ }
235
+ }
236
+
237
+ /// A body the translator spreads into its parent's sexp (class, module
238
+ /// and method bodies, `when`/`in`/`rescue` clause bodies): no `block`.
239
+ fn visit_spread_body(&mut self, body: Option<Node<'_>>) {
240
+ match body {
241
+ None => {}
242
+ Some(Node::StatementsNode { .. }) => {
243
+ let statements = body.unwrap().as_statements_node().unwrap();
244
+ self.visit_each(&statements.body());
245
+ }
246
+ Some(other) => self.visit(&other),
247
+ }
248
+ }
249
+
250
+ fn visit(&mut self, node: &Node<'_>) {
251
+ if self.exception.is_some() {
252
+ return;
253
+ }
254
+ match node {
255
+ // ---------------- definitions ----------------
256
+ Node::ClassNode { .. } => self.visit_class(node),
257
+ Node::ModuleNode { .. } => self.visit_module(node),
258
+ Node::SingletonClassNode { .. } => self.visit_singleton_class(node),
259
+ Node::DefNode { .. } => self.visit_def(node),
260
+
261
+ // ---------------- calls ----------------
262
+ Node::CallNode { .. } => {
263
+ let call = node.as_call_node().unwrap();
264
+ if call.name().as_slice() == b"!~" {
265
+ // s(:not, visit(node.copy(name: :"=~")))
266
+ self.in_context("not", |s| s.visit_call(&call, "=~"));
267
+ } else {
268
+ let name = String::from_utf8_lossy(call.name().as_slice()).into_owned();
269
+ self.visit_call(&call, &name);
270
+ }
271
+ }
272
+ Node::SuperNode { .. } => self.visit_super(node),
273
+ Node::ForwardingSuperNode { .. } => {
274
+ let super_node = node.as_forwarding_super_node().unwrap();
275
+ if let Some(block) = super_node.block() {
276
+ self.in_context("iter", |s| {
277
+ s.process_iter_without_name(|s| s.in_context("zsuper", |_| {}), &block)
278
+ });
279
+ }
280
+ }
281
+ Node::YieldNode { .. } => {
282
+ let yield_node = node.as_yield_node().unwrap();
283
+ self.in_context("yield", |s| {
284
+ s.add_other(OtherScore::Yield);
285
+ if let Some(arguments) = yield_node.arguments() {
286
+ s.visit_each(&arguments.arguments());
287
+ }
288
+ });
289
+ }
290
+ Node::BlockArgumentNode { .. } => self.visit_block_argument(node),
291
+ Node::LambdaNode { .. } => {
292
+ let lambda = node.as_lambda_node().unwrap();
293
+ self.in_context("iter", |s| {
294
+ s.add_other(OtherScore::BlockCall);
295
+ s.in_context("lambda", |_| {});
296
+ s.penalize_by(0.1, |s| {
297
+ s.visit_block_parameters_slot(lambda.parameters());
298
+ s.visit_optional_body(lambda.body());
299
+ });
300
+ });
301
+ }
302
+
303
+ // ---------------- control flow ----------------
304
+ Node::IfNode { .. } => {
305
+ let if_node = node.as_if_node().unwrap();
306
+ self.in_context("if", |s| {
307
+ s.add_other(OtherScore::Branch);
308
+ s.visit(&if_node.predicate());
309
+ s.penalize_by(0.1, |s| {
310
+ s.visit_optional_statements(if_node.statements());
311
+ match if_node.subsequent() {
312
+ None => {}
313
+ Some(Node::ElseNode { .. }) => {
314
+ let else_node = if_node.subsequent().unwrap();
315
+ let statements = else_node.as_else_node().unwrap().statements();
316
+ s.visit_optional_statements(statements);
317
+ }
318
+ Some(elsif) => s.visit(&elsif),
319
+ }
320
+ });
321
+ });
322
+ }
323
+ Node::UnlessNode { .. } => {
324
+ // s(:if, predicate, else_clause, statements)
325
+ let unless = node.as_unless_node().unwrap();
326
+ self.in_context("if", |s| {
327
+ s.add_other(OtherScore::Branch);
328
+ s.visit(&unless.predicate());
329
+ s.penalize_by(0.1, |s| {
330
+ if let Some(else_node) = unless.else_clause() {
331
+ s.visit_optional_statements(else_node.statements());
332
+ }
333
+ s.visit_optional_statements(unless.statements());
334
+ });
335
+ });
336
+ }
337
+ Node::WhileNode { .. } => {
338
+ let while_node = node.as_while_node().unwrap();
339
+ self.process_while("while", &while_node.predicate(), while_node.statements());
340
+ }
341
+ Node::UntilNode { .. } => {
342
+ let until = node.as_until_node().unwrap();
343
+ self.process_while("until", &until.predicate(), until.statements());
344
+ }
345
+ Node::AndNode { .. } => self.process_and_or_chain(node, "and"),
346
+ Node::OrNode { .. } => self.process_and_or_chain(node, "or"),
347
+ Node::CaseNode { .. } => {
348
+ let case = node.as_case_node().unwrap();
349
+ self.in_context("case", |s| {
350
+ s.add_other(OtherScore::Branch);
351
+ s.visit_optional(case.predicate());
352
+ s.penalize_by(0.1, |s| {
353
+ s.visit_each(&case.conditions());
354
+ if let Some(else_node) = case.else_clause() {
355
+ s.visit_optional_statements(else_node.statements());
356
+ }
357
+ });
358
+ });
359
+ }
360
+ Node::WhenNode { .. } => {
361
+ // s(:when, s(:array, *conditions), *statements): process_when.
362
+ let when = node.as_when_node().unwrap();
363
+ self.in_context("when", |s| {
364
+ s.add_other(OtherScore::Branch);
365
+ s.penalize_by(0.1, |s| {
366
+ s.in_context("array", |s| s.visit_each(&when.conditions()));
367
+ s.visit_spread_body(when.statements().map(|st| st.as_node()));
368
+ });
369
+ });
370
+ }
371
+ Node::CaseMatchNode { .. } => {
372
+ let case = node.as_case_match_node().unwrap();
373
+ self.in_context("case", |s| {
374
+ s.add_other(OtherScore::Branch);
375
+ s.visit_optional(case.predicate());
376
+ s.penalize_by(0.1, |s| {
377
+ s.visit_each(&case.conditions());
378
+ if let Some(else_node) = case.else_clause() {
379
+ s.visit_optional_statements(else_node.statements());
380
+ }
381
+ });
382
+ });
383
+ }
384
+ Node::InNode { .. } => {
385
+ // s(:in, pattern, *statements): no Flog rule, children only.
386
+ let in_node = node.as_in_node().unwrap();
387
+ self.in_context("in", |s| {
388
+ let pattern = in_node.pattern();
389
+ if let Node::ConstantPathNode { .. } = pattern {
390
+ s.in_context("const", |s| s.visit(&pattern));
391
+ } else {
392
+ s.visit_pattern(&pattern);
393
+ }
394
+ s.visit_spread_body(in_node.statements().map(|st| st.as_node()));
395
+ });
396
+ }
397
+ Node::MatchPredicateNode { .. } => {
398
+ let predicate = node.as_match_predicate_node().unwrap();
399
+ self.process_one_pattern_case(&predicate.value(), &predicate.pattern());
400
+ }
401
+ Node::MatchRequiredNode { .. } => {
402
+ let required = node.as_match_required_node().unwrap();
403
+ self.process_one_pattern_case(&required.value(), &required.pattern());
404
+ }
405
+ Node::BeginNode { .. } => self.visit_begin(node),
406
+ Node::RescueModifierNode { .. } => {
407
+ // s(:rescue, expression, s(:resbody, s(:array), rescue_expression))
408
+ let rescue = node.as_rescue_modifier_node().unwrap();
409
+ self.in_context("rescue", |s| {
410
+ s.add_other(OtherScore::Branch);
411
+ s.penalize_by(0.1, |s| {
412
+ s.visit(&rescue.expression());
413
+ s.in_context("resbody", |s| {
414
+ s.in_context("array", |_| {});
415
+ s.visit(&rescue.rescue_expression());
416
+ });
417
+ });
418
+ });
419
+ }
420
+ Node::ForNode { .. } => {
421
+ // s(:for, collection, index, statements): no Flog rule.
422
+ let for_node = node.as_for_node().unwrap();
423
+ self.in_context("for", |s| {
424
+ s.visit(&for_node.collection());
425
+ s.visit(&for_node.index());
426
+ s.visit_optional_statements(for_node.statements());
427
+ });
428
+ }
429
+ Node::BreakNode { .. } => {
430
+ let arguments = node.as_break_node().unwrap().arguments();
431
+ self.in_context("break", |s| s.visit_jump_arguments(arguments, false));
432
+ }
433
+ Node::NextNode { .. } => {
434
+ let arguments = node.as_next_node().unwrap().arguments();
435
+ self.in_context("next", |s| s.visit_jump_arguments(arguments, true));
436
+ }
437
+ Node::ReturnNode { .. } => {
438
+ let arguments = node.as_return_node().unwrap().arguments();
439
+ self.in_context("return", |s| s.visit_jump_arguments(arguments, true));
440
+ }
441
+ Node::PreExecutionNode { .. } => {
442
+ let statements = node.as_pre_execution_node().unwrap().statements();
443
+ self.process_execution_block("preexe", statements);
444
+ }
445
+ Node::PostExecutionNode { .. } => {
446
+ let statements = node.as_post_execution_node().unwrap().statements();
447
+ self.process_execution_block("postexe", statements);
448
+ }
449
+
450
+ // ---------------- assignments ----------------
451
+ Node::LocalVariableWriteNode { .. } => {
452
+ let write = node.as_local_variable_write_node().unwrap();
453
+ self.process_assignment("lasgn", |s| s.visit_write_value(&write.value()));
454
+ }
455
+ Node::InstanceVariableWriteNode { .. } => {
456
+ let write = node.as_instance_variable_write_node().unwrap();
457
+ self.process_assignment("iasgn", |s| s.visit_write_value(&write.value()));
458
+ }
459
+ Node::ClassVariableWriteNode { .. } => {
460
+ let write = node.as_class_variable_write_node().unwrap();
461
+ self.in_context("cvdecl", |s| s.visit_write_value(&write.value()));
462
+ }
463
+ Node::GlobalVariableWriteNode { .. } => {
464
+ let write = node.as_global_variable_write_node().unwrap();
465
+ self.in_context("gasgn", |s| s.visit_write_value(&write.value()));
466
+ }
467
+ Node::ConstantWriteNode { .. } => {
468
+ let write = node.as_constant_write_node().unwrap();
469
+ let name = String::from_utf8_lossy(write.name().as_slice()).into_owned();
470
+ let value = write.value();
471
+ self.in_context("cdecl", |s| {
472
+ s.process_cdecl(name, s.cdecl_value(&value), |s| s.visit_write_value(&value))
473
+ });
474
+ }
475
+ Node::ConstantPathWriteNode { .. } => {
476
+ let write = node.as_constant_path_write_node().unwrap();
477
+ let value = write.value();
478
+ let target = write.target().as_node();
479
+ self.in_context("cdecl", |s| match class_name_for_path(&target) {
480
+ Ok(name) => s.process_cdecl(name, s.cdecl_value(&value), |s| s.visit_write_value(&value)),
481
+ Err(message) => s.raise("RuntimeError", message),
482
+ });
483
+ }
484
+ Node::LocalVariableOperatorWriteNode { .. } => {
485
+ let write = node.as_local_variable_operator_write_node().unwrap();
486
+ let operator = constant_text(write.binary_operator().as_slice());
487
+ self.process_assignment("lasgn", |s| {
488
+ s.process_operator_call("lvar", &operator, |s| s.visit_write_value(&write.value()))
489
+ });
490
+ }
491
+ Node::InstanceVariableOperatorWriteNode { .. } => {
492
+ let write = node.as_instance_variable_operator_write_node().unwrap();
493
+ let operator = constant_text(write.binary_operator().as_slice());
494
+ self.process_assignment("iasgn", |s| {
495
+ s.process_operator_call("ivar", &operator, |s| s.visit_write_value(&write.value()))
496
+ });
497
+ }
498
+ Node::ClassVariableOperatorWriteNode { .. } => {
499
+ let write = node.as_class_variable_operator_write_node().unwrap();
500
+ let operator = constant_text(write.binary_operator().as_slice());
501
+ self.in_context("cvdecl", |s| {
502
+ s.process_operator_call("cvar", &operator, |s| s.visit_write_value(&write.value()))
503
+ });
504
+ }
505
+ Node::GlobalVariableOperatorWriteNode { .. } => {
506
+ let write = node.as_global_variable_operator_write_node().unwrap();
507
+ let operator = constant_text(write.binary_operator().as_slice());
508
+ self.in_context("gasgn", |s| {
509
+ s.process_operator_call("gvar", &operator, |s| s.visit(&write.value()))
510
+ });
511
+ }
512
+ Node::ConstantOperatorWriteNode { .. } => {
513
+ let write = node.as_constant_operator_write_node().unwrap();
514
+ let operator = constant_text(write.binary_operator().as_slice());
515
+ // process_cdecl: the value is a call, never an iter.
516
+ self.in_context("cdecl", |s| {
517
+ s.add_other(OtherScore::Assignment);
518
+ s.process_operator_call("const", &operator, |s| s.visit_write_value(&write.value()));
519
+ });
520
+ }
521
+ Node::LocalVariableAndWriteNode { .. } => {
522
+ let write = node.as_local_variable_and_write_node().unwrap();
523
+ self.process_logical_write("op_asgn_and", "lvar", |s| {
524
+ s.process_assignment("lasgn", |s| s.visit_write_value(&write.value()))
525
+ });
526
+ }
527
+ Node::LocalVariableOrWriteNode { .. } => {
528
+ let write = node.as_local_variable_or_write_node().unwrap();
529
+ self.process_logical_write("op_asgn_or", "lvar", |s| {
530
+ s.process_assignment("lasgn", |s| s.visit_write_value(&write.value()))
531
+ });
532
+ }
533
+ Node::InstanceVariableAndWriteNode { .. } => {
534
+ let write = node.as_instance_variable_and_write_node().unwrap();
535
+ self.process_logical_write("op_asgn_and", "ivar", |s| {
536
+ s.process_assignment("iasgn", |s| s.visit(&write.value()))
537
+ });
538
+ }
539
+ Node::InstanceVariableOrWriteNode { .. } => {
540
+ let write = node.as_instance_variable_or_write_node().unwrap();
541
+ self.process_logical_write("op_asgn_or", "ivar", |s| {
542
+ s.process_assignment("iasgn", |s| s.visit(&write.value()))
543
+ });
544
+ }
545
+ Node::ClassVariableAndWriteNode { .. } => {
546
+ let write = node.as_class_variable_and_write_node().unwrap();
547
+ self.process_logical_write("op_asgn_and", "cvar", |s| {
548
+ s.in_context("cvdecl", |s| s.visit_write_value(&write.value()))
549
+ });
550
+ }
551
+ Node::ClassVariableOrWriteNode { .. } => {
552
+ let write = node.as_class_variable_or_write_node().unwrap();
553
+ self.process_logical_write("op_asgn_or", "cvar", |s| {
554
+ s.in_context("cvdecl", |s| s.visit_write_value(&write.value()))
555
+ });
556
+ }
557
+ Node::GlobalVariableAndWriteNode { .. } => {
558
+ let write = node.as_global_variable_and_write_node().unwrap();
559
+ self.process_logical_write("op_asgn_and", "gvar", |s| {
560
+ s.in_context("gasgn", |s| s.visit_write_value(&write.value()))
561
+ });
562
+ }
563
+ Node::GlobalVariableOrWriteNode { .. } => {
564
+ let write = node.as_global_variable_or_write_node().unwrap();
565
+ self.process_logical_write("op_asgn_or", "gvar", |s| {
566
+ s.in_context("gasgn", |s| s.visit_write_value(&write.value()))
567
+ });
568
+ }
569
+ Node::ConstantAndWriteNode { .. } => {
570
+ let write = node.as_constant_and_write_node().unwrap();
571
+ let name = String::from_utf8_lossy(write.name().as_slice()).into_owned();
572
+ let value = write.value();
573
+ self.process_logical_write("op_asgn_and", "const", |s| {
574
+ s.in_context("cdecl", |s| s.process_cdecl(name, s.cdecl_value(&value), |s| s.visit(&value)))
575
+ });
576
+ }
577
+ Node::ConstantOrWriteNode { .. } => {
578
+ let write = node.as_constant_or_write_node().unwrap();
579
+ let name = String::from_utf8_lossy(write.name().as_slice()).into_owned();
580
+ let value = write.value();
581
+ self.process_logical_write("op_asgn_or", "const", |s| {
582
+ s.in_context("cdecl", |s| s.process_cdecl(name, s.cdecl_value(&value), |s| s.visit(&value)))
583
+ });
584
+ }
585
+ Node::ConstantPathOperatorWriteNode { .. } => {
586
+ let write = node.as_constant_path_operator_write_node().unwrap();
587
+ self.in_context("op_asgn", |s| {
588
+ s.visit(&write.target().as_node());
589
+ s.visit_write_value(&write.value());
590
+ });
591
+ }
592
+ Node::ConstantPathAndWriteNode { .. } => {
593
+ let write = node.as_constant_path_and_write_node().unwrap();
594
+ self.in_context("op_asgn_and", |s| {
595
+ s.visit(&write.target().as_node());
596
+ s.visit_write_value(&write.value());
597
+ });
598
+ }
599
+ Node::ConstantPathOrWriteNode { .. } => {
600
+ let write = node.as_constant_path_or_write_node().unwrap();
601
+ self.in_context("op_asgn_or", |s| {
602
+ s.visit(&write.target().as_node());
603
+ s.visit_write_value(&write.value());
604
+ });
605
+ }
606
+ Node::CallOperatorWriteNode { .. } => {
607
+ let write = node.as_call_operator_write_node().unwrap();
608
+ let sexp = sexp_type(node, self.in_pattern).unwrap();
609
+ self.in_context(sexp, |s| {
610
+ s.visit_optional(write.receiver());
611
+ s.visit_write_value(&write.value());
612
+ });
613
+ }
614
+ Node::CallAndWriteNode { .. } => {
615
+ let write = node.as_call_and_write_node().unwrap();
616
+ let sexp = sexp_type(node, self.in_pattern).unwrap();
617
+ self.in_context(sexp, |s| {
618
+ s.visit_optional(write.receiver());
619
+ s.visit_write_value(&write.value());
620
+ });
621
+ }
622
+ Node::CallOrWriteNode { .. } => {
623
+ let write = node.as_call_or_write_node().unwrap();
624
+ let sexp = sexp_type(node, self.in_pattern).unwrap();
625
+ self.in_context(sexp, |s| {
626
+ s.visit_optional(write.receiver());
627
+ s.visit_write_value(&write.value());
628
+ });
629
+ }
630
+ Node::IndexOperatorWriteNode { .. } => {
631
+ let write = node.as_index_operator_write_node().unwrap();
632
+ self.process_index_write(
633
+ write.receiver(),
634
+ write.arguments().map(|a| a.arguments()),
635
+ write.block().map(|b| b.as_node()),
636
+ &write.value(),
637
+ );
638
+ }
639
+ Node::IndexAndWriteNode { .. } => {
640
+ let write = node.as_index_and_write_node().unwrap();
641
+ self.process_index_write(
642
+ write.receiver(),
643
+ write.arguments().map(|a| a.arguments()),
644
+ write.block().map(|b| b.as_node()),
645
+ &write.value(),
646
+ );
647
+ }
648
+ Node::IndexOrWriteNode { .. } => {
649
+ let write = node.as_index_or_write_node().unwrap();
650
+ self.process_index_write(
651
+ write.receiver(),
652
+ write.arguments().map(|a| a.arguments()),
653
+ write.block().map(|b| b.as_node()),
654
+ &write.value(),
655
+ );
656
+ }
657
+ Node::MultiWriteNode { .. } => {
658
+ let write = node.as_multi_write_node().unwrap();
659
+ self.in_context("masgn", |s| {
660
+ s.add_other(OtherScore::Assignment);
661
+ s.in_context("array", |s| {
662
+ s.visit_each(&write.lefts());
663
+ if let Some(rest) = write.rest() {
664
+ if !matches!(rest, Node::ImplicitRestNode { .. }) {
665
+ s.visit(&rest);
666
+ }
667
+ }
668
+ s.visit_each(&write.rights());
669
+ });
670
+ let value = write.value();
671
+ match value.as_array_node() {
672
+ Some(array) if array.opening_loc().is_none() => {
673
+ let elements = array.elements();
674
+ let lone_splat = elements.len() == 1
675
+ && matches!(elements.first(), Some(Node::SplatNode { .. }));
676
+ if lone_splat {
677
+ s.visit(&elements.first().unwrap());
678
+ } else {
679
+ s.visit(&value);
680
+ }
681
+ }
682
+ _ => s.in_context("to_ary", |s| s.visit(&value)),
683
+ }
684
+ });
685
+ }
686
+ Node::MultiTargetNode { .. } => {
687
+ let target = node.as_multi_target_node().unwrap();
688
+ self.in_context("masgn", |s| {
689
+ s.add_other(OtherScore::Assignment);
690
+ s.in_context("array", |s| {
691
+ s.visit_each(&target.lefts());
692
+ if let Some(rest) = target.rest() {
693
+ if !matches!(rest, Node::ImplicitRestNode { .. }) {
694
+ s.visit(&rest);
695
+ }
696
+ }
697
+ s.visit_each(&target.rights());
698
+ });
699
+ });
700
+ }
701
+
702
+ // ---------------- assignment targets (no value) ----------------
703
+ Node::LocalVariableTargetNode { .. }
704
+ | Node::InstanceVariableTargetNode { .. }
705
+ | Node::ClassVariableTargetNode { .. }
706
+ | Node::GlobalVariableTargetNode { .. }
707
+ | Node::ConstantTargetNode { .. }
708
+ | Node::ConstantPathTargetNode { .. }
709
+ | Node::CallTargetNode { .. }
710
+ | Node::IndexTargetNode { .. } => self.visit_target(node, false),
711
+
712
+ // ---------------- literals ----------------
713
+ Node::IntegerNode { .. }
714
+ | Node::FloatNode { .. }
715
+ | Node::RationalNode { .. }
716
+ | Node::ImaginaryNode { .. }
717
+ | Node::SourceLineNode { .. } => self.in_context("lit", |s| s.process_numeric_lit(node)),
718
+ Node::RangeNode { .. } => {
719
+ let range = node.as_range_node().unwrap();
720
+ if crate::translation::range_is_literal(&range, self.in_pattern) {
721
+ return;
722
+ }
723
+ let sexp = if range.is_exclude_end() { "dot3" } else { "dot2" };
724
+ self.in_context(sexp, |s| {
725
+ for bound in [range.left(), range.right()].into_iter().flatten() {
726
+ let empty_parentheses = bound
727
+ .as_parentheses_node()
728
+ .is_some_and(|parentheses| parentheses.body().is_none());
729
+ if !empty_parentheses {
730
+ s.visit(&bound);
731
+ }
732
+ }
733
+ });
734
+ }
735
+ Node::FlipFlopNode { .. } => {
736
+ let flip_flop = node.as_flip_flop_node().unwrap();
737
+ let sexp = sexp_type(node, self.in_pattern).unwrap();
738
+ if sexp != "lit" {
739
+ self.in_context(sexp, |s| {
740
+ s.visit_optional(flip_flop.left());
741
+ s.visit_optional(flip_flop.right());
742
+ });
743
+ }
744
+ }
745
+ Node::ArrayNode { .. } => {
746
+ let array = node.as_array_node().unwrap();
747
+ let sexp = if self.in_pattern { "array_pat" } else { "array" };
748
+ self.in_context(sexp, |s| s.visit_each(&array.elements()));
749
+ }
750
+ Node::HashNode { .. } => {
751
+ let elements = node.as_hash_node().unwrap().elements();
752
+ self.in_context("hash", |s| s.visit_hash_elements(&elements));
753
+ }
754
+ Node::KeywordHashNode { .. } => {
755
+ let elements = node.as_keyword_hash_node().unwrap().elements();
756
+ self.in_context("hash", |s| s.visit_hash_elements(&elements));
757
+ }
758
+ Node::SplatNode { .. } => {
759
+ let splat = node.as_splat_node().unwrap();
760
+ self.in_context("splat", |s| s.visit_optional(splat.expression()));
761
+ }
762
+ Node::InterpolatedStringNode { .. } => {
763
+ let parts = node.as_interpolated_string_node().unwrap().parts();
764
+ self.visit_interpolated("dstr", &parts);
765
+ }
766
+ Node::InterpolatedSymbolNode { .. } => {
767
+ let parts = node.as_interpolated_symbol_node().unwrap().parts();
768
+ self.visit_interpolated("dsym", &parts);
769
+ }
770
+ Node::InterpolatedRegularExpressionNode { .. } => {
771
+ let parts = node.as_interpolated_regular_expression_node().unwrap().parts();
772
+ self.visit_interpolated("dregx", &parts);
773
+ }
774
+ Node::InterpolatedXStringNode { .. } => {
775
+ let parts = node.as_interpolated_x_string_node().unwrap().parts();
776
+ self.visit_interpolated("dxstr", &parts);
777
+ }
778
+ Node::InterpolatedMatchLastLineNode { .. } => {
779
+ let parts = node.as_interpolated_match_last_line_node().unwrap().parts();
780
+ self.in_context("match", |s| s.visit_interpolated("dregx", &parts));
781
+ }
782
+
783
+ // ---------------- other expressions ----------------
784
+ Node::AliasMethodNode { .. } => {
785
+ let alias = node.as_alias_method_node().unwrap();
786
+ self.in_context("alias", |s| {
787
+ s.visit(&alias.new_name());
788
+ s.visit(&alias.old_name());
789
+ s.add_other(OtherScore::Alias);
790
+ });
791
+ }
792
+ Node::UndefNode { .. } => {
793
+ let names = node.as_undef_node().unwrap().names();
794
+ if names.len() == 1 {
795
+ self.in_context("undef", |s| s.visit_each(&names));
796
+ } else {
797
+ self.in_context("block", |s| {
798
+ s.penalize_by(0.1, |s| {
799
+ for name in names.iter() {
800
+ s.in_context("undef", |s| s.visit(&name));
801
+ }
802
+ })
803
+ });
804
+ }
805
+ }
806
+ Node::DefinedNode { .. } => {
807
+ let value = node.as_defined_node().unwrap().value();
808
+ self.in_context("defined", |s| s.visit(&value));
809
+ }
810
+ Node::ParenthesesNode { .. } => {
811
+ if let Some(body) = node.as_parentheses_node().unwrap().body() {
812
+ self.visit(&body);
813
+ }
814
+ }
815
+ Node::StatementsNode { .. } => {
816
+ self.visit_statements(&node.as_statements_node().unwrap());
817
+ }
818
+ Node::ProgramNode { .. } => self.score_program(node),
819
+ Node::ShareableConstantNode { .. } => {
820
+ self.visit(&node.as_shareable_constant_node().unwrap().write());
821
+ }
822
+ Node::ConstantPathNode { .. } => {
823
+ let path = node.as_constant_path_node().unwrap();
824
+ match path.parent() {
825
+ None => self.in_context("colon3", |_| {}),
826
+ Some(parent) => self.in_context("colon2", |s| s.visit(&parent)),
827
+ }
828
+ }
829
+ Node::MatchWriteNode { .. } => {
830
+ // s(:match2, receiver, argument)
831
+ let call = node.as_match_write_node().unwrap().call();
832
+ self.in_context("match2", |s| {
833
+ s.visit_optional(call.receiver());
834
+ if let Some(arguments) = call.arguments() {
835
+ s.visit_optional(arguments.arguments().first());
836
+ }
837
+ });
838
+ }
839
+ Node::ElseNode { .. } => {
840
+ self.visit_optional_statements(node.as_else_node().unwrap().statements());
841
+ }
842
+ Node::EnsureNode { .. } => {
843
+ self.visit_optional_statements(node.as_ensure_node().unwrap().statements());
844
+ }
845
+ Node::EmbeddedStatementsNode { .. } => {
846
+ let statements = node.as_embedded_statements_node().unwrap().statements();
847
+ self.in_context("evstr", |s| s.visit_optional_statements(statements));
848
+ }
849
+
850
+ // ---------------- patterns ----------------
851
+ Node::AlternationPatternNode { .. } => {
852
+ // s(:or, left, right), without the re-association of `or`.
853
+ let alternation = node.as_alternation_pattern_node().unwrap();
854
+ self.in_context("or", |s| {
855
+ s.add_other(OtherScore::Branch);
856
+ s.penalize_by(0.1, |s| {
857
+ s.visit(&alternation.left());
858
+ s.visit(&alternation.right());
859
+ });
860
+ });
861
+ }
862
+ Node::ArrayPatternNode { .. } => {
863
+ let pattern = node.as_array_pattern_node().unwrap();
864
+ self.in_context("array_pat", |s| {
865
+ s.visit_pattern_constant(pattern.constant());
866
+ s.visit_each(&pattern.requireds());
867
+ s.visit_each(&pattern.posts());
868
+ });
869
+ }
870
+ Node::FindPatternNode { .. } => {
871
+ let pattern = node.as_find_pattern_node().unwrap();
872
+ self.in_context("find_pat", |s| {
873
+ s.visit_pattern_constant(pattern.constant());
874
+ s.visit_each(&pattern.requireds());
875
+ });
876
+ }
877
+ Node::HashPatternNode { .. } => {
878
+ let pattern = node.as_hash_pattern_node().unwrap();
879
+ self.in_context("hash_pat", |s| {
880
+ s.visit_pattern_constant(pattern.constant());
881
+ s.visit_hash_elements(&pattern.elements());
882
+ });
883
+ }
884
+ Node::CapturePatternNode { .. } => {
885
+ // visit(target) << visit(value): s(:lasgn, name, value)
886
+ let capture = node.as_capture_pattern_node().unwrap();
887
+ self.process_assignment("lasgn", |s| s.visit(&capture.value()));
888
+ }
889
+ Node::PinnedExpressionNode { .. } => {
890
+ let expression = node.as_pinned_expression_node().unwrap().expression();
891
+ let saved = std::mem::replace(&mut self.in_pattern, false);
892
+ self.visit(&expression);
893
+ self.in_pattern = saved;
894
+ }
895
+ Node::PinnedVariableNode { .. } => {
896
+ self.visit(&node.as_pinned_variable_node().unwrap().variable());
897
+ }
898
+
899
+ // ---------------- nodes that score nothing and have no children ----------------
900
+ Node::AliasGlobalVariableNode { .. }
901
+ | Node::BackReferenceReadNode { .. }
902
+ | Node::ClassVariableReadNode { .. }
903
+ | Node::ConstantReadNode { .. }
904
+ | Node::EmbeddedVariableNode { .. }
905
+ | Node::FalseNode { .. }
906
+ | Node::ForwardingArgumentsNode { .. }
907
+ | Node::ForwardingParameterNode { .. }
908
+ | Node::GlobalVariableReadNode { .. }
909
+ | Node::ImplicitNode { .. }
910
+ | Node::ImplicitRestNode { .. }
911
+ | Node::InstanceVariableReadNode { .. }
912
+ | Node::ItLocalVariableReadNode { .. }
913
+ | Node::LocalVariableReadNode { .. }
914
+ | Node::MatchLastLineNode { .. }
915
+ | Node::NilNode { .. }
916
+ | Node::NumberedReferenceReadNode { .. }
917
+ | Node::RedoNode { .. }
918
+ | Node::RegularExpressionNode { .. }
919
+ | Node::RetryNode { .. }
920
+ | Node::SelfNode { .. }
921
+ | Node::SourceEncodingNode { .. }
922
+ | Node::SourceFileNode { .. }
923
+ | Node::StringNode { .. }
924
+ | Node::SymbolNode { .. }
925
+ | Node::TrueNode { .. }
926
+ | Node::XStringNode { .. } => {}
927
+
928
+ // Parameters are visited through their parent definition or block.
929
+ Node::ParametersNode { .. } => {
930
+ let parameters = node.as_parameters_node().unwrap();
931
+ self.in_context("args", |s| s.visit_parameters(&parameters));
932
+ }
933
+ Node::BlockParametersNode { .. } => {
934
+ self.visit_block_parameters(&node.as_block_parameters_node().unwrap());
935
+ }
936
+ Node::OptionalParameterNode { .. } => {
937
+ let parameter = node.as_optional_parameter_node().unwrap();
938
+ self.process_assignment("lasgn", |s| s.visit(&parameter.value()));
939
+ }
940
+ Node::OptionalKeywordParameterNode { .. } => {
941
+ let parameter = node.as_optional_keyword_parameter_node().unwrap();
942
+ self.in_context("kwarg", |s| s.visit(&parameter.value()));
943
+ }
944
+ Node::RequiredKeywordParameterNode { .. }
945
+ | Node::RequiredParameterNode { .. }
946
+ | Node::RestParameterNode { .. }
947
+ | Node::KeywordRestParameterNode { .. }
948
+ | Node::BlockParameterNode { .. }
949
+ | Node::NoBlockParameterNode { .. }
950
+ | Node::NoKeywordsParameterNode { .. }
951
+ | Node::BlockLocalVariableNode { .. }
952
+ | Node::ItParametersNode { .. }
953
+ | Node::NumberedParametersNode { .. } => {}
954
+
955
+ // The translator never visits these on their own.
956
+ Node::ArgumentsNode { .. }
957
+ | Node::AssocNode { .. }
958
+ | Node::AssocSplatNode { .. }
959
+ | Node::BlockNode { .. }
960
+ | Node::RescueNode { .. }
961
+ | Node::ErrorRecoveryNode { .. } => {
962
+ let message = format!("unexpected node visited directly: {node:?}");
963
+ self.raise("RuntimeError", message);
964
+ }
965
+ }
966
+ }
967
+
968
+ // ------------------------------------------------------------------
969
+ // Definitions
970
+ // ------------------------------------------------------------------
971
+
972
+ /// `visit_class_node` + Flog `process_class`: superclass at +1.0, then
973
+ /// the body spread into the class sexp.
974
+ fn visit_class(&mut self, node: &Node<'_>) {
975
+ let class = node.as_class_node().unwrap();
976
+ let name = match class_name(&class.constant_path()) {
977
+ Ok(name) => name,
978
+ Err(message) => return self.raise("RuntimeError", message),
979
+ };
980
+ self.in_context("class", |s| {
981
+ s.in_klass(name, |s| {
982
+ s.penalize_by(1.0, |s| s.visit_optional(class.superclass()));
983
+ s.visit_spread_body(class.body());
984
+ });
985
+ });
986
+ }
987
+
988
+ fn visit_module(&mut self, node: &Node<'_>) {
989
+ let module = node.as_module_node().unwrap();
990
+ let name = match class_name(&module.constant_path()) {
991
+ Ok(name) => name,
992
+ Err(message) => return self.raise("RuntimeError", message),
993
+ };
994
+ self.in_context("module", |s| {
995
+ s.in_klass(name, |s| s.visit_spread_body(module.body()));
996
+ });
997
+ }
998
+
999
+ /// `visit_singleton_class_node` + Flog `process_sclass`: receiver and
1000
+ /// body at +0.5 inside `in_sklass`, then `sclass` outside it. The body is
1001
+ /// visited as one node, so 2+ statements form a `block` (+0.1).
1002
+ fn visit_singleton_class(&mut self, node: &Node<'_>) {
1003
+ let singleton = node.as_singleton_class_node().unwrap();
1004
+ self.in_context("sclass", |s| {
1005
+ s.in_sklass(|s| {
1006
+ s.penalize_by(0.5, |s| {
1007
+ s.visit(&singleton.expression());
1008
+ s.visit_optional_body(singleton.body());
1009
+ });
1010
+ });
1011
+ s.add_other(OtherScore::Sclass);
1012
+ });
1013
+ }
1014
+
1015
+ /// `visit_def_node` + `MethodBasedSexpProcessor#process_defn`/`process_defs`.
1016
+ /// The line is the name's line; `line_max` is the definition's last line.
1017
+ fn visit_def(&mut self, node: &Node<'_>) {
1018
+ let def = node.as_def_node().unwrap();
1019
+ let bare_name = String::from_utf8_lossy(def.name_loc().as_slice()).into_owned();
1020
+ let line = def.name_loc().start_line();
1021
+ let line_max = node.location().end_line();
1022
+ let receiver = def.receiver();
1023
+ let sexp = if receiver.is_some() { "defs" } else { "defn" };
1024
+
1025
+ self.in_context(sexp, |s| {
1026
+ let name = if receiver.is_some() || s.sclass_depth > 0 {
1027
+ format!("::{bare_name}")
1028
+ } else {
1029
+ bare_name
1030
+ };
1031
+ if let Some(receiver) = receiver {
1032
+ s.visit(&receiver);
1033
+ }
1034
+ s.in_method(name, line, line_max, |s| {
1035
+ s.in_context("args", |s| {
1036
+ if let Some(parameters) = def.parameters() {
1037
+ s.visit_parameters(&parameters);
1038
+ }
1039
+ });
1040
+ s.visit_spread_body(def.body());
1041
+ });
1042
+ });
1043
+ }
1044
+
1045
+ // ------------------------------------------------------------------
1046
+ // Calls and blocks
1047
+ // ------------------------------------------------------------------
1048
+
1049
+ /// `visit_call_node`, under the given method name (`=~` for `!~`).
1050
+ fn visit_call(&mut self, call: &CallNode<'_>, name: &str) {
1051
+ if name == "=~" {
1052
+ if let Some(form) = match_form(call) {
1053
+ let receiver = call.receiver();
1054
+ let argument = call.arguments().and_then(|a| a.arguments().first());
1055
+ return self.in_context(form.sexp_type(), |s| match form {
1056
+ MatchForm::ReceiverRegexp => {
1057
+ s.visit_optional(receiver);
1058
+ s.visit_optional(argument);
1059
+ }
1060
+ MatchForm::ArgumentFirst => {
1061
+ s.visit_optional(argument);
1062
+ s.visit_optional(receiver);
1063
+ }
1064
+ });
1065
+ }
1066
+ }
1067
+
1068
+ match call.block() {
1069
+ Some(Node::BlockNode { .. }) => {
1070
+ let block = call.block().unwrap().as_block_node().unwrap();
1071
+ self.in_context("iter", |s| s.process_call_iter(call, name, &block));
1072
+ }
1073
+ _ => {
1074
+ let call_sexp = plain_call_type(call);
1075
+ self.in_context(call_sexp, |s| s.process_call_sexp(call, name, call_sexp));
1076
+ }
1077
+ }
1078
+ }
1079
+
1080
+ /// Flog's processing of the call sexp: `process_call`, `process_safe_call`,
1081
+ /// `process_attrasgn`, or the generic walk for `safe_attrasgn`.
1082
+ fn process_call_sexp(&mut self, call: &CallNode<'_>, name: &str, call_sexp: &'static str) {
1083
+ let arguments: Vec<Node<'_>> = call
1084
+ .arguments()
1085
+ .map(|arguments| arguments.arguments().iter().collect())
1086
+ .unwrap_or_default();
1087
+ let block_argument = match call.block() {
1088
+ Some(block @ Node::BlockArgumentNode { .. }) => Some(block),
1089
+ _ => None,
1090
+ };
1091
+
1092
+ match call_sexp {
1093
+ "call" | "safe_call" => {
1094
+ let receiver_bonus = if call_sexp == "call" { 0.2 } else { 0.3 };
1095
+ self.penalize_by(receiver_bonus, |s| s.visit_optional(call.receiver()));
1096
+ self.penalize_by(0.2, |s| {
1097
+ for argument in &arguments {
1098
+ s.visit(argument);
1099
+ }
1100
+ if let Some(block) = &block_argument {
1101
+ s.visit(block);
1102
+ }
1103
+ });
1104
+ self.add_to_score(name, call_score(name));
1105
+ }
1106
+ _ => {
1107
+ // s(:attrasgn, receiver, name, *arguments, write_value)
1108
+ let (write_value, arguments) = match arguments.split_last() {
1109
+ Some((last, rest)) => (Some(last), rest),
1110
+ None => (None, &arguments[..]),
1111
+ };
1112
+ if call_sexp == "attrasgn" {
1113
+ self.add_other(OtherScore::Assignment);
1114
+ }
1115
+ self.visit_optional(call.receiver());
1116
+ for argument in arguments {
1117
+ self.visit(argument);
1118
+ }
1119
+ if let Some(block) = &block_argument {
1120
+ self.visit(block);
1121
+ }
1122
+ if let Some(value) = write_value {
1123
+ self.visit_write_value(value);
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+
1129
+ /// Flog `process_iter` for a call with a literal block.
1130
+ fn process_call_iter(&mut self, call: &CallNode<'_>, name: &str, block: &BlockNode<'_>) {
1131
+ let call_sexp = plain_call_type(call);
1132
+
1133
+ if call_sexp == "call" && call.receiver().is_none() && self.named_block_context() {
1134
+ let first_argument = call.arguments().and_then(|a| a.arguments().first());
1135
+ if let Some(dsl) = first_argument.and_then(|arg| dsl_name(&arg, self.in_pattern)) {
1136
+ // in_klass "name(arg)" { in_method arg { process_until_empty } }
1137
+ let class_entry = if dsl.is_string_or_symbol {
1138
+ format!("{}({})", name, dsl.text)
1139
+ } else {
1140
+ name.to_string()
1141
+ };
1142
+ let location = call.location();
1143
+ let (line, line_max) = (location.start_line(), location.end_line());
1144
+ self.in_klass(class_entry, |s| {
1145
+ s.in_method(dsl.text, line, line_max, |s| {
1146
+ s.in_context(call_sexp, |s| s.process_call_sexp(call, name, call_sexp));
1147
+ s.visit_block_parameters_slot(block.parameters());
1148
+ s.visit_optional_body(block.body());
1149
+ });
1150
+ });
1151
+ return;
1152
+ }
1153
+ }
1154
+
1155
+ self.process_iter_without_name(
1156
+ |s| s.in_context(call_sexp, |s| s.process_call_sexp(call, name, call_sexp)),
1157
+ block,
1158
+ );
1159
+ }
1160
+
1161
+ /// The named-block test in `process_iter`: every enclosing sexp is a
1162
+ /// `class`, `module`, `scope`, `block` or `iter`.
1163
+ fn named_block_context(&self) -> bool {
1164
+ // `context` here excludes the `iter` itself, which is always allowed.
1165
+ self.context[..self.context.len() - 1]
1166
+ .iter()
1167
+ .all(|kind| matches!(*kind, "class" | "module" | "scope" | "block" | "iter"))
1168
+ }
1169
+
1170
+ /// Flog `process_iter` without the named-block rule: `block_call`, the
1171
+ /// receiver sexp at the current factor, then parameters and body at +0.1.
1172
+ fn process_iter_without_name(
1173
+ &mut self,
1174
+ receiver: impl FnOnce(&mut Self),
1175
+ block: &BlockNode<'_>,
1176
+ ) {
1177
+ self.add_other(OtherScore::BlockCall);
1178
+ receiver(self);
1179
+ self.penalize_by(0.1, |s| {
1180
+ s.visit_block_parameters_slot(block.parameters());
1181
+ s.visit_optional_body(block.body());
1182
+ });
1183
+ }
1184
+
1185
+ /// The parameter slot of an iter: `0` (deleted by `process_iter`) unless
1186
+ /// the block declares parameters.
1187
+ fn visit_block_parameters_slot(&mut self, parameters: Option<Node<'_>>) {
1188
+ if let Some(Node::BlockParametersNode { .. }) = parameters {
1189
+ let parameters = parameters.unwrap().as_block_parameters_node().unwrap();
1190
+ self.visit_block_parameters(&parameters);
1191
+ }
1192
+ }
1193
+
1194
+ /// A body the translator visits as one node: statements (a `block` when
1195
+ /// 2+) or a `begin` with rescue/ensure.
1196
+ fn visit_optional_body(&mut self, body: Option<Node<'_>>) {
1197
+ match body {
1198
+ None => {}
1199
+ Some(Node::StatementsNode { .. }) => {
1200
+ self.visit_statements(&body.unwrap().as_statements_node().unwrap());
1201
+ }
1202
+ Some(other) => self.visit(&other),
1203
+ }
1204
+ }
1205
+
1206
+ /// `visit_super_node` + Flog `process_super`: `super`, then arguments.
1207
+ fn visit_super(&mut self, node: &Node<'_>) {
1208
+ let super_node = node.as_super_node().unwrap();
1209
+ let arguments: Vec<Node<'_>> = super_node
1210
+ .arguments()
1211
+ .map(|arguments| arguments.arguments().iter().collect())
1212
+ .unwrap_or_default();
1213
+ let block = super_node.block();
1214
+ let process_super = |s: &mut Self, block_argument: Option<&Node<'_>>| {
1215
+ s.in_context("super", |s| {
1216
+ s.add_other(OtherScore::Super);
1217
+ for argument in &arguments {
1218
+ s.visit(argument);
1219
+ }
1220
+ if let Some(block) = block_argument {
1221
+ s.visit(block);
1222
+ }
1223
+ });
1224
+ };
1225
+ match &block {
1226
+ Some(Node::BlockNode { .. }) => {
1227
+ let block = block.as_ref().unwrap().as_block_node().unwrap();
1228
+ self.in_context("iter", |s| {
1229
+ s.process_iter_without_name(|s| process_super(s, None), &block)
1230
+ });
1231
+ }
1232
+ Some(block_argument) => process_super(self, Some(block_argument)),
1233
+ None => process_super(self, None),
1234
+ }
1235
+ }
1236
+
1237
+ /// `visit_block_argument_node` + Flog `process_block_pass`.
1238
+ fn visit_block_argument(&mut self, node: &Node<'_>) {
1239
+ let expression = node.as_block_argument_node().unwrap().expression();
1240
+ let in_pattern = self.in_pattern;
1241
+ self.in_context("block_pass", |s| {
1242
+ s.add_other(OtherScore::BlockPass);
1243
+ let Some(argument) = expression else { return };
1244
+ match sexp_type(&argument, in_pattern) {
1245
+ Some("lvar" | "dvar" | "ivar" | "cvar" | "self" | "const" | "colon2" | "nil")
1246
+ | Some("lit")
1247
+ | Some("call") => {}
1248
+ Some("lasgn") => s.add_other(OtherScore::ToProcLasgn),
1249
+ Some(
1250
+ "iter" | "dsym" | "dstr" | "hash" | "safe_call" | "and" | "case" | "else"
1251
+ | "if" | "or" | "rescue" | "until" | "when" | "while",
1252
+ ) => s.add_other(OtherScore::ToProcIcky),
1253
+ other => {
1254
+ let kind = other.map(|k| format!("s(:{k}, ...)")).unwrap_or("nil".into());
1255
+ return s.raise("RuntimeError", format!("{{:block_pass_even_ickier!=>{kind}}}"));
1256
+ }
1257
+ }
1258
+ s.visit(&argument);
1259
+ });
1260
+ }
1261
+
1262
+ // ------------------------------------------------------------------
1263
+ // Parameters
1264
+ // ------------------------------------------------------------------
1265
+
1266
+ /// `visit_block_parameters_node`: `s(:args, ...)` plus shadow locals.
1267
+ fn visit_block_parameters(&mut self, parameters: &BlockParametersNode<'_>) {
1268
+ self.in_context("args", |s| {
1269
+ if let Some(parameters) = parameters.parameters() {
1270
+ s.visit_parameters(&parameters);
1271
+ }
1272
+ });
1273
+ }
1274
+
1275
+ /// The children of `visit_parameters_node`, in field order.
1276
+ fn visit_parameters(&mut self, parameters: &ParametersNode<'_>) {
1277
+ for required in parameters.requireds().iter() {
1278
+ self.visit_required_parameter(&required);
1279
+ }
1280
+ self.visit_each(&parameters.optionals());
1281
+ self.visit_optional(parameters.rest());
1282
+ for post in parameters.posts().iter() {
1283
+ self.visit_required_parameter(&post);
1284
+ }
1285
+ self.visit_each(&parameters.keywords());
1286
+ self.visit_optional(parameters.keyword_rest());
1287
+ self.visit_optional(parameters.block());
1288
+ }
1289
+
1290
+ fn visit_required_parameter(&mut self, parameter: &Node<'_>) {
1291
+ match parameter {
1292
+ Node::MultiTargetNode { .. } => self.visit_destructured_parameter(parameter),
1293
+ other => self.visit(other),
1294
+ }
1295
+ }
1296
+
1297
+ /// `visit_destructured_parameter` + Flog `process_masgn`, which turns each
1298
+ /// bare name into `s(:lasgn, name)`.
1299
+ fn visit_destructured_parameter(&mut self, node: &Node<'_>) {
1300
+ let target = node.as_multi_target_node().unwrap();
1301
+ let mut children: Vec<Node<'_>> = target.lefts().iter().collect();
1302
+ children.extend(target.rest());
1303
+ children.extend(target.rights().iter());
1304
+
1305
+ self.in_context("masgn", |s| {
1306
+ s.add_other(OtherScore::Assignment);
1307
+ for child in &children {
1308
+ match child {
1309
+ Node::RequiredParameterNode { .. } | Node::SplatNode { .. } => {
1310
+ s.process_assignment("lasgn", |_| {});
1311
+ }
1312
+ Node::MultiTargetNode { .. } => s.visit_destructured_parameter(child),
1313
+ // The translator's bare `raise`.
1314
+ _ => return s.raise("RuntimeError", "unhandled exception".to_string()),
1315
+ }
1316
+ }
1317
+ });
1318
+ }
1319
+
1320
+ // ------------------------------------------------------------------
1321
+ // Control flow helpers
1322
+ // ------------------------------------------------------------------
1323
+
1324
+ /// `visit_and_node`/`visit_or_node` + Flog `process_and`/`process_or`.
1325
+ ///
1326
+ /// The translator re-associates Prism's left-nested chains so they nest
1327
+ /// to the right, so `a && b && c` scores as `a && (b && c)`. The scored
1328
+ /// shape is the in-order list of operands, each nested one level deeper.
1329
+ fn process_and_or_chain(&mut self, node: &Node<'_>, sexp: &'static str) {
1330
+ let mut operands = Vec::new();
1331
+ self.collect_chain_operands(node, sexp, &mut operands);
1332
+ self.process_chain(&operands, sexp);
1333
+ }
1334
+
1335
+ fn collect_chain_operands<'pr>(
1336
+ &self,
1337
+ node: &Node<'pr>,
1338
+ sexp: &'static str,
1339
+ operands: &mut Vec<Node<'pr>>,
1340
+ ) {
1341
+ let (left, right) = match node {
1342
+ Node::AndNode { .. } => {
1343
+ let and = node.as_and_node().unwrap();
1344
+ (and.left(), and.right())
1345
+ }
1346
+ Node::OrNode { .. } => {
1347
+ let or = node.as_or_node().unwrap();
1348
+ (or.left(), or.right())
1349
+ }
1350
+ _ => {
1351
+ let child = transparent_child(node).expect("chain wrapper has one child");
1352
+ return self.collect_chain_operands(&child, sexp, operands);
1353
+ }
1354
+ };
1355
+ for operand in [left, right] {
1356
+ if sexp_type(&operand, self.in_pattern) == Some(sexp) {
1357
+ self.collect_chain_operands(&operand, sexp, operands);
1358
+ } else {
1359
+ operands.push(operand);
1360
+ }
1361
+ }
1362
+ }
1363
+
1364
+ fn process_chain(&mut self, operands: &[Node<'_>], sexp: &'static str) {
1365
+ self.in_context(sexp, |s| {
1366
+ s.add_other(OtherScore::Branch);
1367
+ s.penalize_by(0.1, |s| {
1368
+ s.visit(&operands[0]);
1369
+ if operands.len() == 2 {
1370
+ s.visit(&operands[1]);
1371
+ } else {
1372
+ s.process_chain(&operands[1..], sexp);
1373
+ }
1374
+ });
1375
+ });
1376
+ }
1377
+
1378
+ /// Flog `process_while`/`process_until`: condition and body at +0.1.
1379
+ fn process_while(
1380
+ &mut self,
1381
+ sexp: &'static str,
1382
+ predicate: &Node<'_>,
1383
+ statements: Option<StatementsNode<'_>>,
1384
+ ) {
1385
+ self.in_context(sexp, |s| {
1386
+ s.add_other(OtherScore::Branch);
1387
+ s.penalize_by(0.1, |s| {
1388
+ s.visit(predicate);
1389
+ s.visit_optional_statements(statements);
1390
+ });
1391
+ });
1392
+ }
1393
+
1394
+ /// `foo in bar` and `foo => bar`:
1395
+ /// `s(:case, value, s(:in, pattern, nil), nil)` scored by `process_case`.
1396
+ fn process_one_pattern_case(&mut self, value: &Node<'_>, pattern: &Node<'_>) {
1397
+ self.in_context("case", |s| {
1398
+ s.add_other(OtherScore::Branch);
1399
+ s.visit(value);
1400
+ s.penalize_by(0.1, |s| s.in_context("in", |s| s.visit_pattern(pattern)));
1401
+ });
1402
+ }
1403
+
1404
+ /// `BEGIN {}`/`END {}`: `s(:iter, s(:preexe), 0, statements)`.
1405
+ fn process_execution_block(&mut self, sexp: &'static str, statements: Option<StatementsNode<'_>>) {
1406
+ self.in_context("iter", |s| {
1407
+ s.add_other(OtherScore::BlockCall);
1408
+ s.in_context(sexp, |_| {});
1409
+ s.penalize_by(0.1, |s| s.visit_optional_statements(statements));
1410
+ });
1411
+ }
1412
+
1413
+ /// `break`, `next` and `return` arguments.
1414
+ fn visit_jump_arguments(
1415
+ &mut self,
1416
+ arguments: Option<ruby_prism::ArgumentsNode<'_>>,
1417
+ splat_is_svalue: bool,
1418
+ ) {
1419
+ let Some(arguments) = arguments else { return };
1420
+ let arguments = arguments.arguments();
1421
+ if arguments.len() == 1 {
1422
+ let argument = arguments.first().unwrap();
1423
+ if splat_is_svalue && matches!(argument, Node::SplatNode { .. }) {
1424
+ self.in_context("svalue", |s| s.visit(&argument));
1425
+ } else {
1426
+ self.visit(&argument);
1427
+ }
1428
+ } else {
1429
+ self.in_context("array", |s| s.visit_each(&arguments));
1430
+ }
1431
+ }
1432
+
1433
+ /// `visit_begin_node`: statements, then `rescue` (scored by Flog's
1434
+ /// `process_rescue`, a branch with children at +0.1), then `ensure`.
1435
+ fn visit_begin(&mut self, node: &Node<'_>) {
1436
+ let begin = node.as_begin_node().unwrap();
1437
+ let statements = begin.statements();
1438
+ let rescue = begin.rescue_clause();
1439
+ let else_statements = begin.else_clause().and_then(|e| e.statements());
1440
+
1441
+ let visit_rescued = |s: &mut Self| match &rescue {
1442
+ Some(rescue) => s.in_context("rescue", |s| {
1443
+ s.add_other(OtherScore::Branch);
1444
+ s.penalize_by(0.1, |s| {
1445
+ if let Some(statements) = &statements {
1446
+ s.visit_statements(statements);
1447
+ }
1448
+ let mut clause = Some(rescue.as_node().as_rescue_node().unwrap());
1449
+ while let Some(current) = clause {
1450
+ s.visit_rescue_clause(&current);
1451
+ clause = current.subsequent();
1452
+ }
1453
+ if let Some(else_statements) = &else_statements {
1454
+ s.visit_statements(else_statements);
1455
+ }
1456
+ });
1457
+ }),
1458
+ None => {
1459
+ if let Some(statements) = &statements {
1460
+ s.visit_statements(statements);
1461
+ }
1462
+ if let Some(else_statements) = &else_statements {
1463
+ s.visit_statements(else_statements);
1464
+ }
1465
+ }
1466
+ };
1467
+
1468
+ match begin.ensure_clause() {
1469
+ None => visit_rescued(self),
1470
+ Some(ensure) => self.in_context("ensure", |s| {
1471
+ let keeps_body =
1472
+ statements.is_some() || rescue.is_some() || begin.else_clause().is_some();
1473
+ if keeps_body {
1474
+ visit_rescued(s);
1475
+ }
1476
+ s.visit_optional_statements(ensure.statements());
1477
+ }),
1478
+ }
1479
+ }
1480
+
1481
+ /// `visit_rescue_node`: `s(:resbody, exceptions, *statements)`, where
1482
+ /// `=> ref` adds `ref = $!` to the exceptions.
1483
+ fn visit_rescue_clause(&mut self, rescue: &RescueNode<'_>) {
1484
+ let exceptions = rescue.exceptions();
1485
+ let reference = rescue.reference();
1486
+ self.in_context("resbody", |s| {
1487
+ let lone_splat =
1488
+ exceptions.len() == 1 && matches!(exceptions.first(), Some(Node::SplatNode { .. }));
1489
+ if lone_splat {
1490
+ let splat = exceptions.first().unwrap().as_splat_node().unwrap();
1491
+ s.in_context("splat", |s| {
1492
+ s.visit_optional(splat.expression());
1493
+ if let Some(reference) = &reference {
1494
+ s.visit_target(reference, true);
1495
+ }
1496
+ });
1497
+ } else {
1498
+ s.in_context("array", |s| {
1499
+ s.visit_each(&exceptions);
1500
+ if let Some(reference) = &reference {
1501
+ s.visit_target(reference, true);
1502
+ }
1503
+ });
1504
+ }
1505
+ s.visit_spread_body(rescue.statements().map(|st| st.as_node()));
1506
+ });
1507
+ }
1508
+
1509
+ // ------------------------------------------------------------------
1510
+ // Assignment helpers
1511
+ // ------------------------------------------------------------------
1512
+
1513
+ /// Flog `process_lasgn`/`process_iasgn` (`process_dasgn_curr`):
1514
+ /// `assignment`, then the value.
1515
+ fn process_assignment(&mut self, sexp: &'static str, value: impl FnOnce(&mut Self)) {
1516
+ self.in_context(sexp, |s| {
1517
+ s.add_other(OtherScore::Assignment);
1518
+ value(s);
1519
+ });
1520
+ }
1521
+
1522
+ /// `x op= y` becomes `s(:call, s(:read, name), op, y)`, scored by
1523
+ /// `process_call`.
1524
+ fn process_operator_call(
1525
+ &mut self,
1526
+ read_sexp: &'static str,
1527
+ operator: &str,
1528
+ argument: impl FnOnce(&mut Self),
1529
+ ) {
1530
+ self.in_context("call", |s| {
1531
+ s.penalize_by(0.2, |s| s.in_context(read_sexp, |_| {}));
1532
+ s.penalize_by(0.2, argument);
1533
+ s.add_to_score(operator, call_score(operator));
1534
+ });
1535
+ }
1536
+
1537
+ /// `x &&= y`/`x ||= y`: `s(:op_asgn_and, s(:read, name), write)`, which
1538
+ /// Flog walks without scoring the operator.
1539
+ fn process_logical_write(
1540
+ &mut self,
1541
+ sexp: &'static str,
1542
+ read_sexp: &'static str,
1543
+ write: impl FnOnce(&mut Self),
1544
+ ) {
1545
+ self.in_context(sexp, |s| {
1546
+ s.in_context(read_sexp, |_| {});
1547
+ write(s);
1548
+ });
1549
+ }
1550
+
1551
+ /// Flog `process_cdecl`: when the value is an `iter`, the assignment and
1552
+ /// value are scored inside a class scope named after the constant.
1553
+ /// A missing value is Flog's `nil.sexp_type` crash.
1554
+ fn process_cdecl(&mut self, name: String, value: CdeclValue, visit_value: impl FnOnce(&mut Self)) {
1555
+ if value == CdeclValue::Missing {
1556
+ return self.raise("NoMethodError", "undefined method `sexp_type' for nil".to_string());
1557
+ }
1558
+ if value == CdeclValue::Iter {
1559
+ self.in_klass(name, |s| {
1560
+ s.add_other(OtherScore::Assignment);
1561
+ visit_value(s);
1562
+ });
1563
+ } else {
1564
+ self.add_other(OtherScore::Assignment);
1565
+ visit_value(self);
1566
+ }
1567
+ }
1568
+
1569
+ fn cdecl_value(&self, value: &Node<'_>) -> CdeclValue {
1570
+ if sexp_type(value, self.in_pattern) == Some("iter") {
1571
+ CdeclValue::Iter
1572
+ } else {
1573
+ CdeclValue::Other
1574
+ }
1575
+ }
1576
+
1577
+ /// An assignment target, as in `a, b = ...`, `for a in ...` or
1578
+ /// `rescue => a`. `receives_exception` is true for a rescue reference,
1579
+ /// which the translator gives the value `s(:gvar, :$!)`.
1580
+ fn visit_target(&mut self, node: &Node<'_>, receives_exception: bool) {
1581
+ match node {
1582
+ Node::LocalVariableTargetNode { .. } => self.process_assignment("lasgn", |_| {}),
1583
+ Node::InstanceVariableTargetNode { .. } => self.process_assignment("iasgn", |_| {}),
1584
+ Node::ClassVariableTargetNode { .. } => self.in_context("cvdecl", |_| {}),
1585
+ Node::GlobalVariableTargetNode { .. } => self.in_context("gasgn", |_| {}),
1586
+ Node::ConstantTargetNode { .. } => {
1587
+ let name = node.as_constant_target_node().unwrap().name();
1588
+ let name = String::from_utf8_lossy(name.as_slice()).into_owned();
1589
+ // `$!` is a gvar, never an iter.
1590
+ let value = if receives_exception { CdeclValue::Other } else { CdeclValue::Missing };
1591
+ self.in_context("cdecl", |s| s.process_cdecl(name, value, |_| {}));
1592
+ }
1593
+ Node::ConstantPathTargetNode { .. } => {
1594
+ let target = node.as_constant_path_target_node().unwrap();
1595
+ self.in_context("const", |s| match target.parent() {
1596
+ None => s.in_context("colon3", |_| {}),
1597
+ Some(parent) => s.in_context("colon2", |s| s.visit(&parent)),
1598
+ });
1599
+ }
1600
+ Node::CallTargetNode { .. } => {
1601
+ let target = node.as_call_target_node().unwrap();
1602
+ self.in_context("attrasgn", |s| {
1603
+ s.add_other(OtherScore::Assignment);
1604
+ s.visit(&target.receiver());
1605
+ });
1606
+ }
1607
+ Node::IndexTargetNode { .. } => {
1608
+ let target = node.as_index_target_node().unwrap();
1609
+ self.in_context("attrasgn", |s| {
1610
+ s.add_other(OtherScore::Assignment);
1611
+ s.visit(&target.receiver());
1612
+ if let Some(arguments) = target.arguments() {
1613
+ s.visit_each(&arguments.arguments());
1614
+ }
1615
+ if let Some(block) = target.block() {
1616
+ s.visit(&block.as_node());
1617
+ }
1618
+ });
1619
+ }
1620
+ // A splat, multiple target or other expression used as a target.
1621
+ other => self.visit(other),
1622
+ }
1623
+ }
1624
+
1625
+ /// `foo[bar] op= baz`: `s(:op_asgn1, receiver, arglist, op, value)`,
1626
+ /// walked without scores of its own.
1627
+ fn process_index_write(
1628
+ &mut self,
1629
+ receiver: Option<Node<'_>>,
1630
+ arguments: Option<NodeList<'_>>,
1631
+ block: Option<Node<'_>>,
1632
+ value: &Node<'_>,
1633
+ ) {
1634
+ self.in_context("op_asgn1", |s| {
1635
+ s.visit_optional(receiver);
1636
+ if arguments.is_some() || block.is_some() {
1637
+ s.in_context("arglist", |s| {
1638
+ if let Some(arguments) = &arguments {
1639
+ s.visit_each(arguments);
1640
+ }
1641
+ s.visit_optional(block);
1642
+ });
1643
+ }
1644
+ s.visit_write_value(value);
1645
+ });
1646
+ }
1647
+
1648
+ /// `visit_write_value`: a bracketless array on the right of `=` is
1649
+ /// wrapped in `s(:svalue, ...)`.
1650
+ fn visit_write_value(&mut self, value: &Node<'_>) {
1651
+ match value.as_array_node() {
1652
+ Some(array) if array.opening_loc().is_none() => {
1653
+ let elements = array.elements();
1654
+ let lone_splat =
1655
+ elements.len() == 1 && matches!(elements.first(), Some(Node::SplatNode { .. }));
1656
+ self.in_context("svalue", |s| {
1657
+ if lone_splat {
1658
+ s.visit(&elements.first().unwrap());
1659
+ } else {
1660
+ s.visit(value);
1661
+ }
1662
+ });
1663
+ }
1664
+ _ => self.visit(value),
1665
+ }
1666
+ }
1667
+
1668
+ // ------------------------------------------------------------------
1669
+ // Literals
1670
+ // ------------------------------------------------------------------
1671
+
1672
+ /// Flog `process_lit` for numbers: `magic_number`, except for 0 and -1
1673
+ /// and except directly under a constant assignment.
1674
+ fn process_numeric_lit(&mut self, node: &Node<'_>) {
1675
+ if is_zero_or_minus_one(node) {
1676
+ return;
1677
+ }
1678
+ // `context[1]`: the parent of this `lit`, below it on the stack.
1679
+ let parent = self.context.len().checked_sub(2).map(|i| self.context[i]);
1680
+ if parent != Some("cdecl") {
1681
+ self.add_other(OtherScore::MagicNumber);
1682
+ }
1683
+ }
1684
+
1685
+ fn visit_hash_elements(&mut self, elements: &NodeList<'_>) {
1686
+ for element in elements.iter() {
1687
+ match &element {
1688
+ Node::AssocNode { .. } => {
1689
+ let assoc = element.as_assoc_node().unwrap();
1690
+ self.visit(&assoc.key());
1691
+ self.visit(&assoc.value());
1692
+ }
1693
+ Node::AssocSplatNode { .. } => {
1694
+ let splat = element.as_assoc_splat_node().unwrap();
1695
+ self.in_context("kwsplat", |s| s.visit_optional(splat.value()));
1696
+ }
1697
+ Node::NoKeywordsParameterNode { .. } => {}
1698
+ other => self.visit(other),
1699
+ }
1700
+ }
1701
+ }
1702
+
1703
+ /// The parts of an interpolated string, symbol, regexp or command. Only
1704
+ /// interpolated code can score; plain string parts never do.
1705
+ fn visit_interpolated(&mut self, sexp: &'static str, parts: &NodeList<'_>) {
1706
+ self.in_context(sexp, |s| s.visit_interpolated_parts(parts));
1707
+ }
1708
+
1709
+ fn visit_interpolated_parts(&mut self, parts: &NodeList<'_>) {
1710
+ for part in parts.iter() {
1711
+ match &part {
1712
+ Node::EmbeddedStatementsNode { .. } => self.visit(&part),
1713
+ Node::InterpolatedStringNode { .. } => {
1714
+ let inner = part.as_interpolated_string_node().unwrap().parts();
1715
+ self.visit_interpolated_parts(&inner);
1716
+ }
1717
+ _ => {}
1718
+ }
1719
+ }
1720
+ }
1721
+
1722
+ // ------------------------------------------------------------------
1723
+ // Patterns
1724
+ // ------------------------------------------------------------------
1725
+
1726
+ fn visit_pattern(&mut self, pattern: &Node<'_>) {
1727
+ let saved = std::mem::replace(&mut self.in_pattern, true);
1728
+ self.visit(pattern);
1729
+ self.in_pattern = saved;
1730
+ }
1731
+
1732
+ /// `visit_pattern_constant`: a constant path is wrapped in `s(:const, ...)`.
1733
+ fn visit_pattern_constant(&mut self, constant: Option<Node<'_>>) {
1734
+ match constant {
1735
+ None => {}
1736
+ Some(Node::ConstantReadNode { .. }) => {}
1737
+ Some(other) => self.in_context("const", |s| s.visit(&other)),
1738
+ }
1739
+ }
1740
+ }
1741
+
1742
+ /// `String#sub(/\([^\)]+\)$/, "")`: remove the leftmost `(...)` group that
1743
+ /// ends at the end of a line (`$` also matches before any newline).
1744
+ fn strip_trailing_parenthesized(name: &str) -> String {
1745
+ let bytes = name.as_bytes();
1746
+ for open in 0..bytes.len() {
1747
+ if bytes[open] != b'(' {
1748
+ continue;
1749
+ }
1750
+ let Some(close_offset) = bytes[open + 1..].iter().position(|b| *b == b')') else {
1751
+ continue;
1752
+ };
1753
+ let close = open + 1 + close_offset;
1754
+ let has_content = close > open + 1;
1755
+ let at_line_end = close + 1 == bytes.len() || bytes[close + 1] == b'\n';
1756
+ if has_content && at_line_end {
1757
+ let mut stripped = String::with_capacity(name.len());
1758
+ stripped.push_str(&name[..open]);
1759
+ stripped.push_str(&name[close + 1..]);
1760
+ return stripped;
1761
+ }
1762
+ }
1763
+ name.to_string()
1764
+ }
1765
+
1766
+ fn constant_text(bytes: &[u8]) -> String {
1767
+ String::from_utf8_lossy(bytes).into_owned()
1768
+ }
1769
+
1770
+ /// The class-stack entry `in_klass` makes from a class or module name.
1771
+ fn class_name(constant_path: &Node<'_>) -> Result<String, String> {
1772
+ match constant_path {
1773
+ Node::ConstantReadNode { .. } => {
1774
+ Ok(constant_text(constant_path.as_constant_read_node().unwrap().name().as_slice()))
1775
+ }
1776
+ _ => class_name_for_path(constant_path),
1777
+ }
1778
+ }
1779
+
1780
+ /// `in_klass` for a `colon2`/`colon3` sexp: `colon3` keeps its last name;
1781
+ /// `colon2` is flattened, `:const` and `:colon2` removed, and the rest joined
1782
+ /// with `::` (so `::A::B` becomes `colon3::A::B`).
1783
+ fn class_name_for_path(path: &Node<'_>) -> Result<String, String> {
1784
+ let constant_path = path.as_constant_path_node().ok_or("unknown class path")?;
1785
+ let name = constant_path.name().map(|n| constant_text(n.as_slice())).unwrap_or_default();
1786
+ let Some(parent) = constant_path.parent() else {
1787
+ return Ok(name);
1788
+ };
1789
+ let mut tokens = Vec::new();
1790
+ flatten_parent(&parent, &mut tokens)?;
1791
+ tokens.push(name);
1792
+ Ok(tokens.join("::"))
1793
+ }
1794
+
1795
+ /// The flattened tokens of a class path's parent (`Sexp#flatten`), with
1796
+ /// `:const` and `:colon2` removed. `nil` flattens to an empty string, as
1797
+ /// `Array#join` prints it.
1798
+ fn flatten_parent(node: &Node<'_>, tokens: &mut Vec<String>) -> Result<(), String> {
1799
+ match node {
1800
+ Node::ConstantReadNode { .. } => {
1801
+ tokens.push(constant_text(node.as_constant_read_node().unwrap().name().as_slice()));
1802
+ }
1803
+ Node::ConstantPathNode { .. } => {
1804
+ let path = node.as_constant_path_node().unwrap();
1805
+ match path.parent() {
1806
+ None => tokens.push("colon3".to_string()),
1807
+ Some(parent) => flatten_parent(&parent, tokens)?,
1808
+ }
1809
+ tokens.push(path.name().map(|n| constant_text(n.as_slice())).unwrap_or_default());
1810
+ }
1811
+ Node::SelfNode { .. } => tokens.push("self".to_string()),
1812
+ Node::NilNode { .. } => tokens.push("nil".to_string()),
1813
+ Node::LocalVariableReadNode { .. } => {
1814
+ tokens.push("lvar".to_string());
1815
+ tokens.push(constant_text(node.as_local_variable_read_node().unwrap().name().as_slice()));
1816
+ }
1817
+ Node::IntegerNode { .. } | Node::SymbolNode { .. } | Node::StringNode { .. } => {
1818
+ let kind = if matches!(node, Node::StringNode { .. }) { "str" } else { "lit" };
1819
+ tokens.push(kind.to_string());
1820
+ let text = match node {
1821
+ Node::IntegerNode { .. } => {
1822
+ let value = node.as_integer_node().unwrap().value();
1823
+ let (negative, limbs) = value.to_u32_digits();
1824
+ crate::ruby_format::integer_to_s(negative, limbs)
1825
+ }
1826
+ Node::SymbolNode { .. } => constant_text(node.as_symbol_node().unwrap().unescaped()),
1827
+ _ => constant_text(node.as_string_node().unwrap().unescaped()),
1828
+ };
1829
+ tokens.push(text);
1830
+ }
1831
+ Node::CallNode { .. } => {
1832
+ let call = node.as_call_node().unwrap();
1833
+ if call.block().is_some() || call.is_safe_navigation() || call.is_attribute_write() {
1834
+ return Err(format!("unsupported class path parent: {node:?}"));
1835
+ }
1836
+ tokens.push("call".to_string());
1837
+ match call.receiver() {
1838
+ None => tokens.push(String::new()),
1839
+ Some(receiver) => flatten_parent(&receiver, tokens)?,
1840
+ }
1841
+ tokens.push(constant_text(call.name().as_slice()));
1842
+ if let Some(arguments) = call.arguments() {
1843
+ for argument in arguments.arguments().iter() {
1844
+ flatten_parent(&argument, tokens)?;
1845
+ }
1846
+ }
1847
+ }
1848
+ _ => return Err(format!("unsupported class path parent: {node:?}")),
1849
+ }
1850
+ Ok(())
1851
+ }