cfsolve 0.1.4 → 0.1.5

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.
Files changed (74) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -0
  3. data/README.md +26 -6
  4. data/UPSTREAM.md +23 -8
  5. data/lib/cfsolve/profiles/safari-26-ios/answers.json +805 -797
  6. data/lib/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +909 -899
  7. data/lib/cfsolve/version.rb +2 -2
  8. data/lib/cfsolve.rb +22 -11
  9. data/vendor/cfsolve/README.md +5 -53
  10. data/vendor/cfsolve/examples/listing_dump.rs +24 -0
  11. data/vendor/cfsolve/examples/probe_similarity.rs +37 -0
  12. data/vendor/cfsolve/examples/rebase_reference.rs +96 -0
  13. data/vendor/cfsolve/examples/reread_capture.rs +31 -0
  14. data/vendor/cfsolve/examples/turnstile_smoke.rs +24 -3
  15. data/vendor/cfsolve/profiles/safari-26-ios/answers.json +805 -797
  16. data/vendor/cfsolve/profiles/safari-26-ios/challenge-page-answers.json +909 -899
  17. data/vendor/cfsolve/src/capture/sessions.rs +88 -4
  18. data/vendor/cfsolve/src/capture.rs +1 -0
  19. data/vendor/cfsolve/src/deobfuscate/ast.rs +16 -0
  20. data/vendor/cfsolve/src/deobfuscate/control_flow.rs +1 -1
  21. data/vendor/cfsolve/src/deobfuscate/dead_branches.rs +33 -0
  22. data/vendor/cfsolve/src/deobfuscate/merged_functions.rs +24 -4
  23. data/vendor/cfsolve/src/embedding_page/extra_params.rs +10 -113
  24. data/vendor/cfsolve/src/embedding_page/page.rs +70 -99
  25. data/vendor/cfsolve/src/session/initial.rs +6 -7
  26. data/vendor/cfsolve/src/session/probes.rs +0 -1
  27. data/vendor/cfsolve/src/stage2/analysis/analyze.rs +4 -33
  28. data/vendor/cfsolve/src/stage2/analysis/discovery.rs +9 -17
  29. data/vendor/cfsolve/src/stage2/benchmark.rs +42 -62
  30. data/vendor/cfsolve/src/stage2/call_stack.rs +133 -227
  31. data/vendor/cfsolve/src/stage2/challenge_page.rs +10 -3
  32. data/vendor/cfsolve/src/stage2/probes/dates.rs +0 -44
  33. data/vendor/cfsolve/src/stage2/probes/parent_info.rs +345 -61
  34. data/vendor/cfsolve/src/stage2/probes/performance.rs +42 -5
  35. data/vendor/cfsolve/src/stage2/probes/stack.rs +45 -117
  36. data/vendor/cfsolve/src/stage2/probes/websocket_echo.rs +7 -76
  37. data/vendor/cfsolve/src/stage2/probes.rs +0 -1
  38. data/vendor/cfsolve/src/stage2/reference.json +1 -1
  39. data/vendor/cfsolve/src/stage2/reference.rs +70 -115
  40. data/vendor/cfsolve/src/stage2/registry.rs +6 -11
  41. data/vendor/cfsolve/src/stage2/replay.rs +3 -34
  42. data/vendor/cfsolve/src/stage2/stylesheets.rs +0 -35
  43. data/vendor/cfsolve/src/stage2/trace.rs +1 -1
  44. data/vendor/cfsolve/src/stage2/vocabulary.rs +6 -111
  45. data/vendor/cfsolve/src/stage2.rs +0 -1
  46. data/vendor/cfsolve/src/vm/dataflow.rs +15 -6
  47. data/vendor/cfsolve/src/vm/disassemble.rs +5 -68
  48. data/vendor/cfsolve/src/vm/encoded_strings.rs +1553 -0
  49. data/vendor/cfsolve/src/vm/extract.rs +193 -343
  50. data/vendor/cfsolve/src/vm/interpret/access.rs +2 -10
  51. data/vendor/cfsolve/src/vm/interpret/builtin.rs +0 -13
  52. data/vendor/cfsolve/src/vm/interpret/intrinsic.rs +28 -43
  53. data/vendor/cfsolve/src/vm/interpret/mix32.rs +216 -86
  54. data/vendor/cfsolve/src/vm/interpret/native_dispatch.rs +42 -21
  55. data/vendor/cfsolve/src/vm/interpret/pattern.rs +272 -100
  56. data/vendor/cfsolve/src/vm/interpret/register_helpers.rs +259 -36
  57. data/vendor/cfsolve/src/vm/interpret/run.rs +0 -4
  58. data/vendor/cfsolve/src/vm/machine.rs +14 -70
  59. data/vendor/cfsolve/src/vm/output.rs +3 -5
  60. data/vendor/cfsolve/src/vm/registers.rs +26 -46
  61. data/vendor/cfsolve/src/vm/session.rs +11 -9
  62. data/vendor/cfsolve/src/vm.rs +1 -1
  63. metadata +6 -12
  64. data/lib/cfsolve/profiles/chrome-157-macos/answers.json +0 -4777
  65. data/lib/cfsolve/profiles/chrome-157-macos.json +0 -613
  66. data/vendor/cfsolve/profiles/chrome-157-macos/answers.json +0 -4777
  67. data/vendor/cfsolve/profiles/chrome-157-macos.json +0 -613
  68. data/vendor/cfsolve/src/stage2/fixtures/encoded_benchmark_worker.js +0 -1
  69. data/vendor/cfsolve/src/stage2/probes/parent_info_array.rs +0 -326
  70. data/vendor/cfsolve/src/stage2/value_labels.rs +0 -185
  71. data/vendor/cfsolve/src/vm/encoded_names.rs +0 -635
  72. data/vendor/cfsolve/src/vm/fixtures/free_functions/README.md +0 -9
  73. data/vendor/cfsolve/src/vm/fixtures/free_functions/machine.js +0 -7438
  74. data/vendor/cfsolve/src/vm/fixtures/free_functions/program.base64 +0 -1
@@ -34,11 +34,11 @@ use oxc::allocator::{Allocator, CloneIn};
34
34
  use oxc::ast::AstKind;
35
35
  use oxc::ast::ast::{
36
36
  Argument, ArrayExpressionElement, AssignmentOperator, AssignmentTarget,
37
- AssignmentTargetPropertyIdentifier, BinaryExpression, BindingIdentifier, BindingPattern, Class,
38
- Expression, ForStatement, ForStatementInit, Function, IdentifierReference, LogicalExpression,
39
- MemberExpression, ObjectPropertyKind, PropertyKey, PropertyKind, SequenceExpression,
40
- SimpleAssignmentTarget, Statement, UpdateExpression, VariableDeclaration,
41
- VariableDeclarationKind, VariableDeclarator,
37
+ AssignmentTargetPropertyIdentifier, BinaryExpression, BindingIdentifier, BindingPattern,
38
+ CallExpression, Class, Expression, ForStatement, ForStatementInit, Function,
39
+ IdentifierReference, LogicalExpression, MemberExpression, ObjectExpression, ObjectPropertyKind,
40
+ PropertyKey, PropertyKind, SimpleAssignmentTarget, Statement, UpdateExpression,
41
+ VariableDeclaration, VariableDeclarationKind, VariableDeclarator,
42
42
  };
43
43
  use oxc::ast::builder::AstBuilder;
44
44
  use oxc::ast_visit::{Visit, VisitMut, walk, walk_mut};
@@ -213,12 +213,13 @@ pub(super) fn matches_routine<'a>(
213
213
  ) -> Option<Captures<'a>> {
214
214
  let template = template.script();
215
215
  let template_function = template_function(template);
216
+ let actual_locals = locals(routine);
216
217
  let matcher = Matcher {
217
218
  template,
218
219
  script,
219
220
  template_locals: locals(Routine::function(template_function)?),
220
- actual_locals: locals(routine),
221
- dead: dead_statements(script, routine),
221
+ dead: dead_statements(script, routine, &actual_locals),
222
+ actual_locals,
222
223
  mentions: mentions(script, |visitor| visit_routine(visitor, routine)),
223
224
  helpers,
224
225
  inlined: RefCell::default(),
@@ -256,8 +257,8 @@ struct Matcher<'t, 'a, 'helpers> {
256
257
  script: Script<'a>,
257
258
  template_locals: HashSet<SymbolId>,
258
259
  actual_locals: HashSet<SymbolId>,
259
- /// Statements of the function to skip, by address.
260
- dead: HashSet<usize>,
260
+ /// Statements of the function to skip, and the helper copies they leave.
261
+ dead: Dead<'a>,
261
262
  /// Reads of each binding in the function.
262
263
  mentions: HashMap<Binding<'a>, usize>,
263
264
  helpers: &'helpers BinaryHelpers<'a>,
@@ -319,23 +320,52 @@ fn address(statement: &Statement<'_>) -> usize {
319
320
  }
320
321
 
321
322
  /// A statement that may only build a helper object.
322
- struct Candidate<'a> {
323
- address: usize,
323
+ struct Candidate<'s, 'a> {
324
+ statement: &'s Statement<'a>,
324
325
  object: Binding<'a>,
325
- /// The local `x` of `x = d.k`.
326
- copy: Option<Binding<'a>>,
326
+ built: Built<'s, 'a>,
327
327
  }
328
328
 
329
- /// Statements that only build helper objects nothing uses: `d = {}` or `d = { k: function ..
330
- /// }`, `d.k = function ..`, and `x = d.k`, where `d` and `x` are never otherwise mentioned.
331
- /// They create objects and functions and read plain data properties, so skipping them changes
332
- /// nothing observable.
333
- fn dead_statements<'a>(script: Script<'a>, routine: Routine<'a>) -> HashSet<usize> {
329
+ /// What a [`Candidate`] does to its helper object `d`.
330
+ #[derive(Clone, Copy)]
331
+ enum Built<'s, 'a> {
332
+ /// `d = { k: function .. }`, with no properties or only function properties.
333
+ Literal(&'s ObjectExpression<'a>),
334
+ /// `d.k = function ..`.
335
+ Property(&'s str, &'s Function<'a>),
336
+ /// `x = d.k`.
337
+ Copy(Binding<'a>, &'s str),
338
+ }
339
+
340
+ /// Statements to skip when matching, and the helpers that copies of their functions stand for.
341
+ #[derive(Default)]
342
+ struct Dead<'a> {
343
+ statements: HashSet<usize>,
344
+ /// Locals holding [`BinaryHelper`] copies, which the skipped statements assign.
345
+ helpers: HashMap<Binding<'a>, BinaryHelper>,
346
+ }
347
+
348
+ /// Statements that only build helper objects: `d = {}` or `d = { k: function .. }`, `d.k =
349
+ /// function ..`, and `x = d.k`, where `d` is never otherwise mentioned. They create objects and
350
+ /// functions and read plain data properties, so skipping them changes nothing observable if `x`
351
+ /// is never otherwise mentioned either.
352
+ ///
353
+ /// A copy `x` may also be a local otherwise mentioned only as the callee of calls with two
354
+ /// arguments, if the function it copies is a [`BinaryHelper`] and the statements building it
355
+ /// lead the routine. Nothing else then runs before `x` holds the helper, and nothing assigns it
356
+ /// again, so each call computes the helper's operator.
357
+ fn dead_statements<'a>(
358
+ script: Script<'a>,
359
+ routine: Routine<'a>,
360
+ locals: &HashSet<SymbolId>,
361
+ ) -> Dead<'a> {
334
362
  let statements = flattened(script, routine.statements);
335
- // `d` of `d.k`.
336
- let object = |member: Option<&MemberExpression<'a>>| match member? {
363
+ // `d` and `k` of `d.k`.
364
+ let member = |member: Option<&'a MemberExpression<'a>>| match member? {
337
365
  MemberExpression::StaticMemberExpression(member) => match &member.object {
338
- Expression::Identifier(object) => Some(script.binding(object)),
366
+ Expression::Identifier(object) => {
367
+ Some((script.binding(object), member.property.name.as_str()))
368
+ }
339
369
  _ => None,
340
370
  },
341
371
  _ => None,
@@ -351,33 +381,39 @@ fn dead_statements<'a>(script: Script<'a>, routine: Routine<'a>) -> HashSet<usiz
351
381
  if assignment.operator != AssignmentOperator::Assign {
352
382
  continue;
353
383
  }
354
- let (object, copy) = match (&assignment.left, &assignment.right) {
384
+ let (object, built) = match (&assignment.left, &assignment.right) {
355
385
  (
356
386
  AssignmentTarget::AssignmentTargetIdentifier(object),
357
387
  Expression::ObjectExpression(literal),
358
388
  ) if literal.properties.iter().all(is_function_property) => {
359
- (script.binding(object), None)
389
+ (script.binding(object), Built::Literal(literal))
360
390
  }
361
391
  (AssignmentTarget::AssignmentTargetIdentifier(copy), right) => {
362
- let Some(object) = object(right.as_member_expression()) else {
392
+ let Some((object, key)) = member(right.as_member_expression()) else {
363
393
  continue;
364
394
  };
365
- (object, Some(script.binding(copy)))
395
+ (object, Built::Copy(script.binding(copy), key))
366
396
  }
367
- (left, Expression::FunctionExpression(_)) => {
368
- let Some(object) = object(left.as_member_expression()) else {
397
+ (left, Expression::FunctionExpression(function)) => {
398
+ let Some((object, key)) = member(left.as_member_expression()) else {
369
399
  continue;
370
400
  };
371
- (object, None)
401
+ (object, Built::Property(key, function))
372
402
  }
373
403
  _ => continue,
374
404
  };
375
405
  candidates.push(Candidate {
376
- address: address(statement),
406
+ statement,
377
407
  object,
378
- copy,
408
+ built,
379
409
  });
380
410
  }
411
+ let copies = leading_copies(script, &statements, &candidates);
412
+ let mut calls = Calls {
413
+ script,
414
+ counts: HashMap::default(),
415
+ };
416
+ visit_routine(&mut calls, routine);
381
417
  // Drop candidates until every helper object and copy is mentioned only in the remaining
382
418
  // candidates, so no kept statement reads a removed object.
383
419
  let all_mentions = mentions(script, |visitor| visit_routine(visitor, routine));
@@ -385,24 +421,20 @@ fn dead_statements<'a>(script: Script<'a>, routine: Routine<'a>) -> HashSet<usiz
385
421
  loop {
386
422
  let objects: HashSet<Binding<'a>> = candidates
387
423
  .iter()
388
- .filter(|candidate| candidate.copy.is_none())
424
+ .filter(|candidate| !matches!(candidate.built, Built::Copy(..)))
389
425
  .map(|candidate| candidate.object)
390
426
  .collect();
391
427
  let mut inside_mentions: HashMap<Binding<'a>, usize> = HashMap::default();
392
428
  let mut inside_writes: HashMap<Binding<'a>, usize> = HashMap::default();
393
- for &statement in &statements {
394
- if candidates
395
- .iter()
396
- .any(|candidate| candidate.address == address(statement))
397
- {
398
- let read = mentions(script, |visitor| visitor.visit_statement(statement));
399
- for (binding, count) in read {
400
- *inside_mentions.entry(binding).or_default() += count;
401
- }
402
- let written = writes(script, |visitor| visitor.visit_statement(statement));
403
- for (binding, count) in written {
404
- *inside_writes.entry(binding).or_default() += count;
405
- }
429
+ for candidate in &candidates {
430
+ let statement = candidate.statement;
431
+ let read = mentions(script, |visitor| visitor.visit_statement(statement));
432
+ for (binding, count) in read {
433
+ *inside_mentions.entry(binding).or_default() += count;
434
+ }
435
+ let written = writes(script, |visitor| visitor.visit_statement(statement));
436
+ for (binding, count) in written {
437
+ *inside_writes.entry(binding).or_default() += count;
406
438
  }
407
439
  }
408
440
  let only_inside =
@@ -410,21 +442,139 @@ fn dead_statements<'a>(script: Script<'a>, routine: Routine<'a>) -> HashSet<usiz
410
442
  // Helper objects must also hold only the literals these statements assign.
411
443
  let only_written_inside =
412
444
  |binding: &Binding<'a>| all_writes.get(binding) == inside_writes.get(binding);
445
+ // A helper copy assigned once, read only by calls.
446
+ let count = |counts: &HashMap<Binding<'a>, usize>, copy: &Binding<'a>| {
447
+ counts.get(copy).copied().unwrap_or_default()
448
+ };
449
+ let called = |copy: &Binding<'a>| {
450
+ matches!(copy, Binding::Symbol(symbol) if locals.contains(symbol))
451
+ && copies.contains_key(copy)
452
+ && all_writes.get(copy) == Some(&1)
453
+ && count(&all_mentions, copy)
454
+ == count(&inside_mentions, copy) + count(&calls.counts, copy)
455
+ };
413
456
  let before = candidates.len();
414
457
  candidates.retain(|candidate| {
415
458
  objects.contains(&candidate.object)
416
459
  && only_inside(&candidate.object)
417
460
  && only_written_inside(&candidate.object)
418
- && candidate.copy.as_ref().is_none_or(only_inside)
461
+ && match &candidate.built {
462
+ Built::Copy(copy, _) => only_inside(copy) || called(copy),
463
+ _ => true,
464
+ }
419
465
  });
420
466
  if candidates.len() == before {
421
467
  break;
422
468
  }
423
469
  }
424
- candidates
425
- .into_iter()
426
- .map(|candidate| candidate.address)
427
- .collect()
470
+ let mut dead = Dead::default();
471
+ for candidate in candidates {
472
+ dead.statements.insert(address(candidate.statement));
473
+ if let Built::Copy(copy, _) = candidate.built
474
+ && let Some(&helper) = copies.get(&copy)
475
+ {
476
+ dead.helpers.insert(copy, helper);
477
+ }
478
+ }
479
+ dead
480
+ }
481
+
482
+ /// The copies `x = d.k` among the candidates leading `statements`, before anything else runs,
483
+ /// of functions that are [`BinaryHelper`]s when copied.
484
+ fn leading_copies<'a>(
485
+ script: Script<'a>,
486
+ statements: &[&Statement<'a>],
487
+ candidates: &[Candidate<'_, 'a>],
488
+ ) -> HashMap<Binding<'a>, BinaryHelper> {
489
+ let mut objects: HashMap<Binding<'a>, HashMap<&str, &Function<'a>>> = HashMap::default();
490
+ let mut copies = HashMap::default();
491
+ for &statement in statements {
492
+ let candidate = candidates
493
+ .iter()
494
+ .find(|candidate| ptr::eq(candidate.statement, statement));
495
+ let Some(candidate) = candidate else {
496
+ // Declarations without initializers and empty statements do nothing.
497
+ let inert = match statement {
498
+ Statement::EmptyStatement(_) => true,
499
+ Statement::VariableDeclaration(declaration) => {
500
+ !declaration.kind.is_using()
501
+ && declaration
502
+ .declarations
503
+ .iter()
504
+ .all(|declarator| declarator.init.is_none())
505
+ }
506
+ _ => false,
507
+ };
508
+ if inert {
509
+ continue;
510
+ }
511
+ break;
512
+ };
513
+ match candidate.built {
514
+ Built::Literal(literal) => {
515
+ let properties = literal.properties.iter().filter_map(|property| {
516
+ let ObjectPropertyKind::ObjectProperty(property) = property else {
517
+ return None;
518
+ };
519
+ let Expression::FunctionExpression(function) = &property.value else {
520
+ return None;
521
+ };
522
+ Some((property_name(&property.key)?, &**function))
523
+ });
524
+ // Later duplicate keys replace earlier ones, as in the literal.
525
+ objects.insert(candidate.object, properties.collect());
526
+ }
527
+ Built::Property(key, function) => {
528
+ // Assigning to a property of anything but a built object may throw or run code.
529
+ let Some(properties) = objects.get_mut(&candidate.object) else {
530
+ break;
531
+ };
532
+ properties.insert(key, function);
533
+ }
534
+ Built::Copy(copy, key) => {
535
+ let Some(properties) = objects.get(&candidate.object) else {
536
+ break;
537
+ };
538
+ match properties
539
+ .get(key)
540
+ .and_then(|function| binary_helper(script, function))
541
+ {
542
+ Some(helper) => copies.insert(copy, helper),
543
+ None => copies.remove(&copy),
544
+ };
545
+ }
546
+ }
547
+ }
548
+ copies
549
+ }
550
+
551
+ /// The name of a plain property key.
552
+ fn property_name<'s>(key: &'s PropertyKey<'_>) -> Option<&'s str> {
553
+ match key {
554
+ PropertyKey::StaticIdentifier(key) => Some(key.name.as_str()),
555
+ PropertyKey::StringLiteral(key) => key.value.as_str(),
556
+ _ => None,
557
+ }
558
+ }
559
+
560
+ /// Counts calls `f(a, b)` with two plain arguments, by the binding the callee names.
561
+ struct Calls<'s> {
562
+ script: Script<'s>,
563
+ counts: HashMap<Binding<'s>, usize>,
564
+ }
565
+
566
+ impl<'x> Visit<'x> for Calls<'_> {
567
+ fn visit_call_expression(&mut self, call: &CallExpression<'x>) {
568
+ if let Expression::Identifier(callee) = &call.callee
569
+ && !call.optional
570
+ && let [first, second] = &call.arguments[..]
571
+ && first.as_expression().is_some()
572
+ && second.as_expression().is_some()
573
+ {
574
+ *self.counts.entry(resolve(self.script, callee)).or_default() += 1;
575
+ }
576
+ walk::walk_call_expression(self, call);
577
+ }
428
578
  }
429
579
 
430
580
  /// A plain property whose value is a function expression.
@@ -636,7 +786,8 @@ impl<'a> Matcher<'_, 'a, '_> {
636
786
  return false;
637
787
  };
638
788
  let template = running(self.template, &body.statements, None).0;
639
- let (statements, completes) = running(self.script, actual.statements, Some(&self.dead));
789
+ let (statements, completes) =
790
+ running(self.script, actual.statements, Some(&self.dead.statements));
640
791
  match actual.returns {
641
792
  // The return follows the routine's statements if they can complete.
642
793
  Some(returned) if completes => {
@@ -705,8 +856,32 @@ impl<'a> Matcher<'_, 'a, '_> {
705
856
  state: &mut State<'a>,
706
857
  ) -> bool {
707
858
  let template = running(self.template, template, None).0;
708
- let actual = running(self.script, actual, Some(&self.dead)).0;
709
- template.len() == actual.len() && self.pairs(&template, &actual, state)
859
+ let actual = running(self.script, actual, Some(&self.dead.statements)).0;
860
+ if template.len() == actual.len() {
861
+ return self.pairs(&template, &actual, state);
862
+ }
863
+ // Extra assignments before the final `return` run as `return (t = a, .., e);` does.
864
+ if let Some((Statement::ReturnStatement(returns), template)) = template.split_last()
865
+ && let Some((Statement::ReturnStatement(returned), actual)) = actual.split_last()
866
+ && let (Some(returns), Some(returned)) = (&returns.argument, &returned.argument)
867
+ && template.len() < actual.len()
868
+ {
869
+ let (kept, temporaries) = actual.split_at(template.len());
870
+ let temporaries: Option<Vec<&Expression<'_>>> = temporaries
871
+ .iter()
872
+ .map(|statement| match statement {
873
+ Statement::ExpressionStatement(statement) => Some(&statement.expression),
874
+ _ => None,
875
+ })
876
+ .collect();
877
+ return temporaries.is_some_and(|temporaries| {
878
+ self.pairs(template, kept, state)
879
+ && self
880
+ .substituted(temporaries, returned)
881
+ .is_some_and(|returned| self.expression(returns, returned, state))
882
+ });
883
+ }
884
+ false
710
885
  }
711
886
 
712
887
  /// Matches statements pairwise, in order.
@@ -1204,17 +1379,26 @@ impl<'a> Matcher<'_, 'a, '_> {
1204
1379
  fn normalized<'m>(&'m self, expression: &Expression<'_>) -> Option<&'m Expression<'m>> {
1205
1380
  let expression = expression.without_parentheses();
1206
1381
  if let Expression::SequenceExpression(sequence) = expression {
1207
- return self.substituted(sequence);
1382
+ let (last, temporaries) = sequence.expressions.split_last()?;
1383
+ return self.substituted(temporaries, last);
1208
1384
  }
1209
1385
  if let Expression::CallExpression(call) = expression
1210
1386
  && let Expression::Identifier(callee) = &call.callee
1211
1387
  && let callee = resolve(self.script, callee)
1212
- && !matches!(callee, Binding::Symbol(symbol) if self.actual_locals.contains(&symbol))
1213
- && let Some(helper) = self.helpers.get(&callee)
1388
+ && let local = matches!(callee,
1389
+ Binding::Symbol(symbol) if self.actual_locals.contains(&symbol))
1390
+ && let Some(helper) = if local {
1391
+ self.dead.helpers.get(&callee)
1392
+ } else {
1393
+ self.helpers.get(&callee)
1394
+ }
1214
1395
  && let [first, second] = &call.arguments[..]
1215
1396
  && let (Some(first), Some(second)) = (first.as_expression(), second.as_expression())
1216
1397
  {
1217
- self.inlined.borrow_mut().insert(callee);
1398
+ // Local copies are created by the function itself, so nothing else need resolve.
1399
+ if !local {
1400
+ self.inlined.borrow_mut().insert(callee);
1401
+ }
1218
1402
  let (left, right) = if helper.swapped {
1219
1403
  (second, first)
1220
1404
  } else {
@@ -1272,10 +1456,15 @@ impl<'a> Matcher<'_, 'a, '_> {
1272
1456
  }
1273
1457
  }
1274
1458
 
1275
- /// `(t = a, u = b, e)` with the temporaries substituted (see [`Self::normalized`]).
1276
- fn substituted<'m>(&'m self, sequence: &SequenceExpression<'_>) -> Option<&'m Expression<'m>> {
1277
- let (last, temporaries) = sequence.expressions.split_last()?;
1459
+ /// `last`, after the assignments `temporaries` to temporaries only it and later temporaries'
1460
+ /// values read, with their values substituted (see [`Self::normalized`]).
1461
+ fn substituted<'m, 'e, 'x: 'e>(
1462
+ &'m self,
1463
+ temporaries: impl IntoIterator<Item = &'e Expression<'x>>,
1464
+ last: &Expression<'_>,
1465
+ ) -> Option<&'m Expression<'m>> {
1278
1466
  let mut values: HashMap<SymbolId, &'m Expression<'m>> = HashMap::default();
1467
+ let mut assigned = Vec::new();
1279
1468
  for temporary in temporaries {
1280
1469
  let Expression::AssignmentExpression(assignment) = temporary else {
1281
1470
  return None;
@@ -1294,16 +1483,28 @@ impl<'a> Matcher<'_, 'a, '_> {
1294
1483
  }
1295
1484
  let value = self.substitute(&assignment.right, &values);
1296
1485
  values.insert(name, value);
1486
+ assigned.push((name, &assignment.right));
1297
1487
  }
1298
- // Every read of each temporary is in the final expression, which does not write it.
1299
- let reads = mentions(self.script, |visitor| visitor.visit_expression(last));
1300
- let written = writes(self.script, |visitor| visitor.visit_expression(last));
1301
- let all_read_here = values.keys().all(|&name| {
1488
+ // Every read of each temporary is in a later value or the final expression, and nothing
1489
+ // there writes it. Each is read, so the match covers its value.
1490
+ let mut reads = mentions(self.script, |visitor| visitor.visit_expression(last));
1491
+ let mut written = writes(self.script, |visitor| visitor.visit_expression(last));
1492
+ for &(name, value) in assigned.iter().rev() {
1302
1493
  let name = Binding::Symbol(name);
1303
- self.mentions.get(&name) == reads.get(&name) && !written.contains_key(&name)
1304
- });
1305
- if !all_read_here {
1306
- return None;
1494
+ if !reads.contains_key(&name)
1495
+ || self.mentions.get(&name) != reads.get(&name)
1496
+ || written.contains_key(&name)
1497
+ {
1498
+ return None;
1499
+ }
1500
+ // Earlier temporaries may read this one's value.
1501
+ for (binding, count) in mentions(self.script, |visitor| visitor.visit_expression(value))
1502
+ {
1503
+ *reads.entry(binding).or_default() += count;
1504
+ }
1505
+ for (binding, count) in writes(self.script, |visitor| visitor.visit_expression(value)) {
1506
+ *written.entry(binding).or_default() += count;
1507
+ }
1307
1508
  }
1308
1509
  Some(self.substitute(last, &values))
1309
1510
  }
@@ -1476,7 +1677,10 @@ fn running<'s, 'x>(
1476
1677
  });
1477
1678
  let kept =
1478
1679
  reachable || initializes || matches!(statement, Statement::FunctionDeclaration(_));
1479
- reachable &= completes(statement);
1680
+ reachable &= !matches!(
1681
+ statement,
1682
+ Statement::ReturnStatement(_) | Statement::ThrowStatement(_)
1683
+ );
1480
1684
  let runs = match statement {
1481
1685
  _ if declaration.is_some() => initializes,
1482
1686
  Statement::EmptyStatement(_) => false,
@@ -1489,19 +1693,6 @@ fn running<'s, 'x>(
1489
1693
  (running, reachable)
1490
1694
  }
1491
1695
 
1492
- /// Whether execution can reach the statement after this one. Loops and other complex
1493
- /// control flow remain conservative; a branch only terminates when both arms terminate.
1494
- fn completes(statement: &Statement<'_>) -> bool {
1495
- match statement {
1496
- Statement::ReturnStatement(_) | Statement::ThrowStatement(_) => false,
1497
- Statement::BlockStatement(block) => block.body.iter().all(completes),
1498
- Statement::IfStatement(branch) => {
1499
- completes(&branch.consequent) || branch.alternate.as_ref().is_none_or(completes)
1500
- }
1501
- _ => true,
1502
- }
1503
- }
1504
-
1505
1696
  /// `var x = e;`, which assigns where it stands: the declaration itself only scopes `x`. A `let`
1506
1697
  /// behaves the same once the template has matched every use after it.
1507
1698
  fn initialized<'s, 'x>(
@@ -1689,25 +1880,6 @@ mod tests {
1689
1880
  }
1690
1881
  }
1691
1882
 
1692
- #[test]
1693
- fn ignores_code_after_branches_that_both_terminate() {
1694
- let template = "function f(a) { if (a) { return 1; } else { throw 2; } }";
1695
- assert!(
1696
- check(
1697
- template,
1698
- "function f(a) { if (a) { return 1; } else { throw 2; } return 3; }"
1699
- )
1700
- .is_some()
1701
- );
1702
- assert!(
1703
- check(
1704
- "function f(a) { if (a) { return 1; } }",
1705
- "function f(a) { if (a) { return 1; } return 3; }"
1706
- )
1707
- .is_none()
1708
- );
1709
- }
1710
-
1711
1883
  #[test]
1712
1884
  fn matches_renamed_and_reordered_functions() {
1713
1885
  let template =