js: Automatically convert _.each to for…of.

This commit was automatically generated by the following script,
followed by lint --fix and a few small manual lint-related cleanups.

import * as babelParser from "recast/parsers/babel";
import * as recast from "recast";
import * as tsParser from "recast/parsers/typescript";
import { builders as b, namedTypes as n } from "ast-types";
import { Context } from "ast-types/lib/path-visitor";
import K from "ast-types/gen/kinds";
import { NodePath } from "ast-types/lib/node-path";
import assert from "assert";
import fs from "fs";
import path from "path";
import process from "process";

const checkExpression = (node: n.Node): node is K.ExpressionKind =>
  n.Expression.check(node);
const checkStatement = (node: n.Node): node is K.StatementKind =>
  n.Statement.check(node);

for (const file of process.argv.slice(2)) {
  console.log("Parsing", file);
  const ast = recast.parse(fs.readFileSync(file, { encoding: "utf8" }), {
    parser: path.extname(file) === ".ts" ? tsParser : babelParser,
  });
  let changed = false;
  let inLoop = false;
  let replaceReturn = false;

  const visitLoop = (...args: string[]) =>
    function(this: Context, path: NodePath) {
      for (const arg of args) {
        this.visit(path.get(arg));
      }
      const old = { inLoop };
      inLoop = true;
      this.visit(path.get("body"));
      inLoop = old.inLoop;
      return false;
    };

  recast.visit(ast, {
    visitDoWhileStatement: visitLoop("test"),

    visitExpressionStatement(path) {
      const { expression, comments } = path.node;
      let valueOnly;
      if (
        n.CallExpression.check(expression) &&
        n.MemberExpression.check(expression.callee) &&
        !expression.callee.computed &&
        n.Identifier.check(expression.callee.object) &&
        expression.callee.object.name === "_" &&
        n.Identifier.check(expression.callee.property) &&
        ["each", "forEach"].includes(expression.callee.property.name) &&
        [2, 3].includes(expression.arguments.length) &&
        checkExpression(expression.arguments[0]) &&
        (n.FunctionExpression.check(expression.arguments[1]) ||
          n.ArrowFunctionExpression.check(expression.arguments[1])) &&
        [1, 2].includes(expression.arguments[1].params.length) &&
        n.Identifier.check(expression.arguments[1].params[0]) &&
        ((valueOnly = expression.arguments[1].params[1] === undefined) ||
          n.Identifier.check(expression.arguments[1].params[1])) &&
        (expression.arguments[2] === undefined ||
          n.ThisExpression.check(expression.arguments[2]))
      ) {
        const old = { inLoop, replaceReturn };
        inLoop = false;
        replaceReturn = true;
        this.visit(
          path
            .get("expression")
            .get("arguments")
            .get(1)
            .get("body")
        );
        inLoop = old.inLoop;
        replaceReturn = old.replaceReturn;

        const [right, { body, params }] = expression.arguments;
        const loop = b.forOfStatement(
          b.variableDeclaration("let", [
            b.variableDeclarator(
              valueOnly ? params[0] : b.arrayPattern([params[1], params[0]])
            ),
          ]),
          valueOnly
            ? right
            : b.callExpression(
                b.memberExpression(right, b.identifier("entries")),
                []
              ),
          checkStatement(body) ? body : b.expressionStatement(body)
        );
        loop.comments = comments;
        path.replace(loop);
        changed = true;
      }
      this.traverse(path);
    },

    visitForStatement: visitLoop("init", "test", "update"),

    visitForInStatement: visitLoop("left", "right"),

    visitForOfStatement: visitLoop("left", "right"),

    visitFunction(path) {
      this.visit(path.get("params"));
      const old = { replaceReturn };
      replaceReturn = false;
      this.visit(path.get("body"));
      replaceReturn = old.replaceReturn;
      return false;
    },

    visitReturnStatement(path) {
      if (replaceReturn) {
        assert(!inLoop); // could use labeled continue if this ever fires
        const { argument, comments } = path.node;
        if (argument === null) {
          const s = b.continueStatement();
          s.comments = comments;
          path.replace(s);
        } else {
          const s = b.expressionStatement(argument);
          s.comments = comments;
          path.replace(s, b.continueStatement());
        }
        return false;
      }
      this.traverse(path);
    },

    visitWhileStatement: visitLoop("test"),
  });

  if (changed) {
    console.log("Writing", file);
    fs.writeFileSync(file, recast.print(ast).code, { encoding: "utf8" });
  }
}

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
This commit is contained in:
Anders Kaseorg
2020-02-05 21:19:47 -08:00
committed by Tim Abbott
parent 811e128787
commit 02511bff1c
103 changed files with 602 additions and 502 deletions

View File

@@ -861,11 +861,11 @@ exports.filter_people_by_search_terms = function (users, search_terms) {
// Loop through users and populate filtered_users only
// if they include search_terms
_.each(users, function (user) {
for (const user of users) {
const person = exports.get_by_email(user.email);
// Get person object (and ignore errors)
if (!person || !person.full_name) {
return;
continue;
}
// Return user emails that include search terms
@@ -876,7 +876,8 @@ exports.filter_people_by_search_terms = function (users, search_terms) {
if (match) {
filtered_users.set(person.user_id, true);
}
});
}
return filtered_users;
};
@@ -1019,15 +1020,15 @@ exports.extract_people_from_message = function (message) {
}
// Add new people involved in this message to the people list
_.each(involved_people, function (person) {
for (const person of involved_people) {
if (person.unknown_local_echo_user) {
return;
continue;
}
const user_id = person.user_id || person.id;
if (people_by_user_id_dict.has(user_id)) {
return;
continue;
}
exports.report_late_add(user_id, person.email);
@@ -1039,7 +1040,7 @@ exports.extract_people_from_message = function (message) {
is_admin: person.is_realm_admin || false,
is_bot: person.is_bot || false,
});
});
}
};
function safe_lower(s) {
@@ -1094,15 +1095,15 @@ exports.maybe_incr_recipient_count = function (message) {
}
// Track the number of PMs we've sent to this person to improve autocomplete
_.each(message.display_recipient, function (recip) {
for (const recip of message.display_recipient) {
if (recip.unknown_local_echo_user) {
return;
continue;
}
const user_id = recip.id;
exports.incr_recipient_count(user_id);
});
}
};
exports.set_full_name = function (person_obj, new_full_name) {
@@ -1181,20 +1182,20 @@ exports.is_my_user_id = function (user_id) {
};
exports.initialize = function () {
_.each(page_params.realm_users, function (person) {
for (const person of page_params.realm_users) {
exports.add_in_realm(person);
});
}
_.each(page_params.realm_non_active_users, function (person) {
for (const person of page_params.realm_non_active_users) {
exports.add(person);
});
}
_.each(page_params.cross_realm_bots, function (person) {
for (const person of page_params.cross_realm_bots) {
if (!people_dict.has(person.email)) {
exports.add(person);
}
cross_realm_dict.set(person.user_id, person);
});
}
exports.initialize_current_user(page_params.user_id);