es6-object-concise-method-visitors.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Copyright 2013-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. */
  9. /*jslint node:true*/
  10. /**
  11. * Desugars concise methods of objects to function expressions.
  12. *
  13. * var foo = {
  14. * method(x, y) { ... }
  15. * };
  16. *
  17. * var foo = {
  18. * method: function(x, y) { ... }
  19. * };
  20. *
  21. */
  22. var Syntax = require('esprima-fb').Syntax;
  23. var utils = require('../src/utils');
  24. var reservedWordsHelper = require('./reserved-words-helper');
  25. function visitObjectConciseMethod(traverse, node, path, state) {
  26. var isGenerator = node.value.generator;
  27. if (isGenerator) {
  28. utils.catchupWhiteSpace(node.range[0] + 1, state);
  29. }
  30. if (reservedWordsHelper.isReservedWord(node.key.name)) {
  31. utils.catchup(node.key.range[0], state);
  32. utils.append('"', state);
  33. utils.catchup(node.key.range[1], state);
  34. utils.append('"', state);
  35. }
  36. utils.catchup(node.key.range[1], state);
  37. utils.append(':', state);
  38. renderConciseMethod(traverse, node, path, state);
  39. return false;
  40. }
  41. // This method is also used by es6-object-computed-property-visitor to render
  42. // the method for concise computed properties.
  43. function renderConciseMethod(traverse, property, path, state) {
  44. if (property.computed) {
  45. var closingSquareBracketIndex = state.g.source.indexOf(']', property.key.range[1]);
  46. utils.catchup(closingSquareBracketIndex, state);
  47. utils.move(closingSquareBracketIndex + 1, state);
  48. }
  49. utils.append("function" + (property.value.generator ? "*" : ""), state);
  50. path.unshift(property);
  51. traverse(property.value, path, state);
  52. path.shift();
  53. }
  54. visitObjectConciseMethod.test = function(node, path, state) {
  55. return node.type === Syntax.Property &&
  56. node.value.type === Syntax.FunctionExpression &&
  57. node.method === true;
  58. };
  59. exports.renderConciseMethod = renderConciseMethod;
  60. exports.visitorList = [
  61. visitObjectConciseMethod
  62. ];