db.js 10.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Mutation Db.
 */

const crypto = require('crypto');
const fs = require('fs');
const fsPath = require('path');

const babelGenerator = require('@babel/generator').default;
const babelTraverse = require('@babel/traverse').default;
const babelTypes = require('@babel/types');
const globals = require('globals');

const random = require('./random.js');

const globalIdentifiers = new Set(Object.keys(globals.builtin));
const propertyNames = new Set([
    // Parsed from https://github.com/tc39/ecma262/blob/master/spec.html
    'add',
    'anchor',
    'apply',
    'big',
    'bind',
    'blink',
    'bold',
    'buffer',
    'byteLength',
    'byteOffset',
    'BYTES_PER_ELEMENT',
    'call',
    'catch',
    'charAt',
    'charCodeAt',
    'clear',
    'codePointAt',
    'compile',
    'concat',
    'constructor',
    'copyWithin',
    '__defineGetter__',
    '__defineSetter__',
    'delete',
    'endsWith',
    'entries',
    'every',
    'exec',
    'fill',
    'filter',
    'find',
    'findIndex',
    'fixed',
    'flags',
    'fontcolor',
    'fontsize',
    'forEach',
    'get',
    'getDate',
    'getDay',
    'getFloat32',
    'getFloat64',
    'getFullYear',
    'getHours',
    'getInt16',
    'getInt32',
    'getInt8',
    'getMilliseconds',
    'getMinutes',
    'getMonth',
    'getSeconds',
    'getTime',
    'getTimezoneOffset',
    'getUint16',
    'getUint32',
    'getUint8',
    'getUTCDate',
    'getUTCDay',
    'getUTCFullYear',
    'getUTCHours',
    'getUTCMilliseconds',
    'getUTCMinutes',
    'getUTCMonth',
    'getUTCSeconds',
    'getYear',
    'global',
    'has',
    'hasInstance',
    'hasOwnProperty',
    'ignoreCase',
    'includes',
    'indexOf',
    'isConcatSpreadable',
    'isPrototypeOf',
    'italics',
    'iterator',
    'join',
    'keys',
    'lastIndexOf',
    'length',
    'link',
    'localeCompare',
    '__lookupGetter__',
    '__lookupSetter__',
    'map',
    'match',
    'match',
    'message',
    'multiline',
    'name',
    'next',
    'normalize',
    'padEnd',
    'padStart',
    'pop',
    'propertyIsEnumerable',
    '__proto__',
    'prototype',
    'push',
    'reduce',
    'reduceRight',
    'repeat',
    'replace',
    'replace',
    'return',
    'reverse',
    'search',
    'search',
    'set',
    'set',
    'setDate',
    'setFloat32',
    'setFloat64',
    'setFullYear',
    'setHours',
    'setInt16',
    'setInt32',
    'setInt8',
    'setMilliseconds',
    'setMinutes',
    'setMonth',
    'setSeconds',
    'setTime',
    'setUint16',
    'setUint32',
    'setUint8',
    'setUTCDate',
    'setUTCFullYear',
    'setUTCHours',
    'setUTCMilliseconds',
    'setUTCMinutes',
    'setUTCMonth',
    'setUTCSeconds',
    'setYear',
    'shift',
    'size',
    'slice',
    'slice',
    'small',
    'some',
    'sort',
    'source',
    'species',
    'splice',
    'split',
    'split',
    'startsWith',
    'sticky',
    'strike',
    'sub',
    'subarray',
    'substr',
    'substring',
    'sup',
    'test',
    'then',
    'throw',
    'toDateString',
    'toExponential',
    'toFixed',
    'toGMTString',
    'toISOString',
    'toJSON',
    'toLocaleDateString',
    'toLocaleLowerCase',
    'toLocaleString',
    'toLocaleTimeString',
    'toLocaleUpperCase',
    'toLowerCase',
    'toPrecision',
    'toPrimitive',
    'toString',
    'toStringTag',
    'toTimeString',
    'toUpperCase',
    'toUTCString',
    'trim',
    'unicode',
    'unscopables',
    'unshift',
    'valueOf',
    'values',
]);

const MAX_DEPENDENCIES = 2;

class Expression {
  constructor(type, source, isStatement, originalPath,
              dependencies, needsSuper) {
    this.type = type;
    this.source = source;
    this.isStatement = isStatement;
    this.originalPath = originalPath;
    this.dependencies = dependencies;
    this.needsSuper = needsSuper;
  }
}

function dedupKey(expression) {
  if (!expression.dependencies) {
    return expression.source;
  }

  let result = expression.source;
  for (let dependency of expression.dependencies) {
    result = result.replace(new RegExp(dependency, 'g'), 'ID');
  }

  return result;
}

function _markSkipped(path) {
  while (path) {
    path.node.__skipped = true;
    path = path.parentPath;
  }
}

class MutateDbWriter {
  constructor(outputDir) {
    this.seen = new Set();
    this.outputDir = fsPath.resolve(outputDir);
    this.index = {
      statements: [],
      superStatements: [],
      all: [],
    };
  }

  process(source) {
    let self = this;

    let varIndex = 0;

    // First pass to collect dependency information.
    babelTraverse(source.ast, {
      Super(path) {
        while (path) {
          path.node.__needsSuper = true;
          path = path.parentPath;
        }
      },

      YieldExpression(path) {
        // Don't include yield expressions in DB.
        _markSkipped(path);
      },

      Identifier(path) {
        if (globalIdentifiers.has(path.node.name) &&
            path.node.name != 'eval') {
          // Global name.
          return;
        }

        if (propertyNames.has(path.node.name) &&
            path.parentPath.isMemberExpression() &&
            path.parentKey !== 'object') {
          // Builtin property name.
          return;
        }

        let binding = path.scope.getBinding(path.node.name);
        if (!binding) {
          // Unknown dependency. Don't handle this.
          _markSkipped(path);
          return;
        }

        let newName;
        if (path.node.name.startsWith('VAR_')) {
          newName = path.node.name;
        } else if (babelTypes.isFunctionDeclaration(binding.path.node) ||
                   babelTypes.isFunctionExpression(binding.path.node) ||
                   babelTypes.isDeclaration(binding.path.node) ||
                   babelTypes.isFunctionExpression(binding.path.node)) {
          // Unknown dependency. Don't handle this.
          _markSkipped(path);
          return;
        } else {
          newName = 'VAR_' + varIndex++;
          path.scope.rename(path.node.name, newName);
        }

        // Mark all parents as having a dependency.
        while (path) {
          path.node.__idDependencies = path.node.__idDependencies || [];
          if (path.node.__idDependencies.length <= MAX_DEPENDENCIES) {
            path.node.__idDependencies.push(newName);
          }
          path = path.parentPath;
        }
      }
    });

    babelTraverse(source.ast, {
      Expression(path) {
        if (!path.parentPath.isExpressionStatement()) {
          return;
        }

        if (path.node.__skipped ||
            (path.node.__idDependencies &&
             path.node.__idDependencies.length > MAX_DEPENDENCIES)) {
          return;
        }

        if (path.isIdentifier() || path.isMemberExpression() ||
            path.isConditionalExpression() ||
            path.isBinaryExpression() || path.isDoExpression() ||
            path.isLiteral() ||
            path.isObjectExpression() || path.isArrayExpression()) {
          // Skip:
          //   - Identifiers.
          //   - Member expressions (too many and too context dependent).
          //   - Conditional expressions (too many and too context dependent).
          //   - Binary expressions (too many).
          //   - Literals (too many).
          //   - Object/array expressions (too many).
          return;
        }

        if (path.isAssignmentExpression()) {
          if (!babelTypes.isMemberExpression(path.node.left)) {
            // Skip assignments that aren't to properties.
            return;
          }

          if (babelTypes.isIdentifier(path.node.left.object)) {
            if (babelTypes.isNumericLiteral(path.node.left.property)) {
              // Skip VAR[\d+] = ...;
              // There are too many and they generally aren't very useful.
              return;
            }

            if (babelTypes.isStringLiteral(path.node.left.property) &&
                !propertyNames.has(path.node.left.property.value)) {
              // Skip custom properties. e.g.
              // VAR["abc"] = ...;
              // There are too many and they generally aren't very useful.
              return;
            }
          }
        }

        if (path.isCallExpression() &&
            babelTypes.isIdentifier(path.node.callee) &&
            !globalIdentifiers.has(path.node.callee.name)) {
          // Skip VAR(...) calls since there's too much context we're missing.
          return;
        }

        if (path.isUnaryExpression() && path.node.operator == '-') {
          // Skip -... since there are too many.
          return;
        }

        // Make the template.
        let generated = babelGenerator(path.node, { concise: true }).code;
        let expression = new Expression(
            path.node.type,
            generated,
            path.parentPath.isExpressionStatement(),
            source.relPath,
            path.node.__idDependencies,
            Boolean(path.node.__needsSuper));

        // Try to de-dupe similar expressions.
        let key = dedupKey(expression);
        if (self.seen.has(key)) {
          return;
        }

        // Write results.
        let dirPath = fsPath.join(self.outputDir, expression.type);
        if (!fs.existsSync(dirPath)) {
          fs.mkdirSync(dirPath);
        }

        let sha1sum = crypto.createHash('sha1');
        sha1sum.update(key);

        let filePath = fsPath.join(dirPath, sha1sum.digest('hex') + '.json');
        fs.writeFileSync(filePath, JSON.stringify(expression));

        let relPath = fsPath.relative(self.outputDir, filePath);

        // Update index.
        self.seen.add(key);
        self.index.all.push(relPath);

        if (expression.needsSuper) {
          self.index.superStatements.push(relPath);
        } else {
          self.index.statements.push(relPath);
        }
      }
    });
  }

  writeIndex() {
    fs.writeFileSync(
        fsPath.join(this.outputDir, 'index.json'),
        JSON.stringify(this.index));
  }
}

class MutateDb {
  constructor(outputDir) {
    this.outputDir = fsPath.resolve(outputDir);
    this.index = JSON.parse(
        fs.readFileSync(fsPath.join(outputDir, 'index.json'), 'utf-8'));
  }

  getRandomStatement({canHaveSuper=false} = {}) {
    let choices;
    if (canHaveSuper) {
      choices = random.randInt(0, 1) ?
          this.index.all : this.index.superStatements;
    } else {
      choices = this.index.statements;
    }

    let path = fsPath.join(
        this.outputDir, choices[random.randInt(0, choices.length - 1)]);
    return JSON.parse(fs.readFileSync(path), 'utf-8');
  }
}

module.exports = {
  MutateDb: MutateDb,
  MutateDbWriter: MutateDbWriter,
}