crossover_mutator.js 2.21 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
// 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 Expression mutator.
 */

'use strict';

const babelTemplate = require('@babel/template').default;

const common = require('./common.js');
const random = require('../random.js');
const mutator = require('./mutator.js');
const sourceHelpers = require('../source_helpers.js');

class CrossOverMutator extends mutator.Mutator {
  constructor(settings, db) {
    super();
    this.settings = settings;
    this.db = db;
  }

  get visitor() {
    const thisMutator = this;

    return [{
      ExpressionStatement(path) {
        if (!random.choose(thisMutator.settings.MUTATE_CROSSOVER_INSERT)) {
          return;
        }

        const canHaveSuper = Boolean(path.findParent(x => x.isClassMethod()));
        const randomExpression = thisMutator.db.getRandomStatement(
            {canHaveSuper: canHaveSuper});

        // Insert the statement.
        let toInsert = babelTemplate(
            randomExpression.source,
41
            sourceHelpers.BABYLON_REPLACE_VAR_OPTIONS);
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
        const dependencies = {};

        if (randomExpression.dependencies) {
          const variables = common.availableVariables(path);
          if (!variables.length) {
            return;
          }
          for (const dependency of randomExpression.dependencies) {
            dependencies[dependency] = random.single(variables);
          }
        }

        try {
          toInsert = toInsert(dependencies);
        } catch (e) {
          if (thisMutator.settings.testing) {
            // Fail early in tests.
            throw e;
          }
          console.log('ERROR: Failed to parse:', randomExpression.source);
          console.log(e);
          return;
        }

        thisMutator.annotate(
            toInsert,
            'Crossover from ' + randomExpression.originalPath);

        if (random.choose(0.5)) {
          thisMutator.insertBeforeSkip(path, toInsert);
        } else {
          thisMutator.insertAfterSkip(path, toInsert);
        }

        path.skip();
      },
    }, {
    }];
  }
}

module.exports = {
  CrossOverMutator: CrossOverMutator,
};