cb01e8d9a53c16448f9634ff44de0c519274a950864a45a9c32de3787179680bd6d78afeaa08cba2e7f6da926c563edf870399bdadbba5b17a5eaa587e9e16 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /**
  2. * Fixes block-shadowed let/const bindings in Safari 10/11.
  3. * https://kangax.github.io/compat-table/es6/#test-let_scope_shadow_resolution
  4. */
  5. export default function({ types: t }) {
  6. return {
  7. name: "transform-safari-block-shadowing",
  8. visitor: {
  9. VariableDeclarator(path) {
  10. // the issue only affects let and const bindings:
  11. const kind = path.parent.kind;
  12. if (kind !== "let" && kind !== "const") return;
  13. // ignore non-block-scoped bindings:
  14. const block = path.scope.block;
  15. if (t.isFunction(block) || t.isProgram(block)) return;
  16. const bindings = t.getOuterBindingIdentifiers(path.node.id);
  17. for (const name of Object.keys(bindings)) {
  18. let scope = path.scope;
  19. // ignore parent bindings (note: impossible due to let/const?)
  20. if (!scope.hasOwnBinding(name)) continue;
  21. // check if shadowed within the nearest function/program boundary
  22. while ((scope = scope.parent)) {
  23. if (scope.hasOwnBinding(name)) {
  24. path.scope.rename(name);
  25. break;
  26. }
  27. if (t.isFunction(scope.block) || t.isProgram(scope.block)) {
  28. break;
  29. }
  30. }
  31. }
  32. },
  33. },
  34. };
  35. }