{"size": 1464, "ext": "js", "max_stars_repo_path": "examples/dead-code-elimination/tree-shake.js", "max_stars_repo_name": "fujia-blogs/fee", "max_stars_repo_stars_event_min_datetime": "2022-01-08T07:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T07:44:20.000Z", "max_issues_repo_path": "examples/dead-code-elimination/tree-shake.js", "max_issues_repo_name": "fujia-blogs/fee", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/dead-code-elimination/tree-shake.js", "max_forks_repo_name": "fujia-blogs/fee", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.5230769231, "max_line_length": 67, "alphanum_fraction": 0.6222677596}
const acorn = require('acorn');
const fs = require('fs');

const JSEmitter = require('./js-emitter');

const l = console.log;

const args = process.argv[2];
const buffer = fs.readFileSync(args).toString();
const body = acorn.parse(buffer).body;
const jsEmitter = new JSEmitter();

let decls = new Map();
let calledDecls = [];
let code = [];

// traversal process
body.forEach((node) => {
  if (node.type == 'FunctionDeclaration') {
    const code = jsEmitter.run([node]);
    decls.set(jsEmitter.visitNode(node.id), code);
    return;
  }

  if (node.type == 'ExpressionStatement') {
    if (node.expression.type == 'CallExpression') {
      const callNode = node.expression;
      calledDecls.push(jsEmitter.visitIdentifier(callNode.callee));
      const args = callNode.arguments;
      for (const arg of args) {
        if (arg.type == 'Identifier') {
          calledDecls.push(jsEmitter.visitNode(arg));
        }
      }
    }
  }

  if (node.type == 'VariableDeclaration') {
    const kind = node.kind;
    for (const decl of node.declarations) {
      decls.set(
        jsEmitter.visitNode(decl.id),
        jsEmitter.visitVariableDeclarator(decl, kind)
      );
    }
    return;
  }

  if (node.type == 'Identifier') {
    calledDecls.push(node.name);
  }

  code.push(jsEmitter.run([node]));
});

// generate code
code = calledDecls
  .map((c) => {
    return decls.get(c);
  })
  .concat([code])
  .join('');

fs.writeFileSync('test.shook.js', code);
