AssignmentNode.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.createAssignmentNode = void 0;
  7. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
  8. var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
  9. var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
  10. var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
  11. var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
  12. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  13. var _is = require("../../utils/is.js");
  14. var _customs = require("../../utils/customs.js");
  15. var _factory = require("../../utils/factory.js");
  16. var _access = require("./utils/access.js");
  17. var _assign = require("./utils/assign.js");
  18. var _operators = require("../operators.js");
  19. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
  20. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  21. var name = 'AssignmentNode';
  22. var dependencies = ['subset', '?matrix',
  23. // FIXME: should not be needed at all, should be handled by subset
  24. 'Node'];
  25. var createAssignmentNode = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  26. var subset = _ref.subset,
  27. matrix = _ref.matrix,
  28. Node = _ref.Node;
  29. var access = (0, _access.accessFactory)({
  30. subset: subset
  31. });
  32. var assign = (0, _assign.assignFactory)({
  33. subset: subset,
  34. matrix: matrix
  35. });
  36. /*
  37. * Is parenthesis needed?
  38. * @param {node} node
  39. * @param {string} [parenthesis='keep']
  40. * @param {string} implicit
  41. * @private
  42. */
  43. function needParenthesis(node, parenthesis, implicit) {
  44. if (!parenthesis) {
  45. parenthesis = 'keep';
  46. }
  47. var precedence = (0, _operators.getPrecedence)(node, parenthesis, implicit);
  48. var exprPrecedence = (0, _operators.getPrecedence)(node.value, parenthesis, implicit);
  49. return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence;
  50. }
  51. var AssignmentNode = /*#__PURE__*/function (_Node) {
  52. (0, _inherits2["default"])(AssignmentNode, _Node);
  53. var _super = _createSuper(AssignmentNode);
  54. /**
  55. * @constructor AssignmentNode
  56. * @extends {Node}
  57. *
  58. * Define a symbol, like `a=3.2`, update a property like `a.b=3.2`, or
  59. * replace a subset of a matrix like `A[2,2]=42`.
  60. *
  61. * Syntax:
  62. *
  63. * new AssignmentNode(symbol, value)
  64. * new AssignmentNode(object, index, value)
  65. *
  66. * Usage:
  67. *
  68. * new AssignmentNode(new SymbolNode('a'), new ConstantNode(2)) // a=2
  69. * new AssignmentNode(new SymbolNode('a'),
  70. * new IndexNode('b'),
  71. * new ConstantNode(2)) // a.b=2
  72. * new AssignmentNode(new SymbolNode('a'),
  73. * new IndexNode(1, 2),
  74. * new ConstantNode(3)) // a[1,2]=3
  75. *
  76. * @param {SymbolNode | AccessorNode} object
  77. * Object on which to assign a value
  78. * @param {IndexNode} [index=null]
  79. * Index, property name or matrix index. Optional. If not provided
  80. * and `object` is a SymbolNode, the property is assigned to the
  81. * global scope.
  82. * @param {Node} value
  83. * The value to be assigned
  84. */
  85. function AssignmentNode(object, index, value) {
  86. var _this;
  87. (0, _classCallCheck2["default"])(this, AssignmentNode);
  88. _this = _super.call(this);
  89. _this.object = object;
  90. _this.index = value ? index : null;
  91. _this.value = value || index;
  92. // validate input
  93. if (!(0, _is.isSymbolNode)(object) && !(0, _is.isAccessorNode)(object)) {
  94. throw new TypeError('SymbolNode or AccessorNode expected as "object"');
  95. }
  96. if ((0, _is.isSymbolNode)(object) && object.name === 'end') {
  97. throw new Error('Cannot assign to symbol "end"');
  98. }
  99. if (_this.index && !(0, _is.isIndexNode)(_this.index)) {
  100. // index is optional
  101. throw new TypeError('IndexNode expected as "index"');
  102. }
  103. if (!(0, _is.isNode)(_this.value)) {
  104. throw new TypeError('Node expected as "value"');
  105. }
  106. return _this;
  107. }
  108. // class name for typing purposes:
  109. (0, _createClass2["default"])(AssignmentNode, [{
  110. key: "name",
  111. get:
  112. // readonly property name
  113. function get() {
  114. if (this.index) {
  115. return this.index.isObjectProperty() ? this.index.getObjectProperty() : '';
  116. } else {
  117. return this.object.name || '';
  118. }
  119. }
  120. }, {
  121. key: "type",
  122. get: function get() {
  123. return name;
  124. }
  125. }, {
  126. key: "isAssignmentNode",
  127. get: function get() {
  128. return true;
  129. }
  130. /**
  131. * Compile a node into a JavaScript function.
  132. * This basically pre-calculates as much as possible and only leaves open
  133. * calculations which depend on a dynamic scope with variables.
  134. * @param {Object} math Math.js namespace with functions and constants.
  135. * @param {Object} argNames An object with argument names as key and `true`
  136. * as value. Used in the SymbolNode to optimize
  137. * for arguments from user assigned functions
  138. * (see FunctionAssignmentNode) or special symbols
  139. * like `end` (see IndexNode).
  140. * @return {function} Returns a function which can be called like:
  141. * evalNode(scope: Object, args: Object, context: *)
  142. */
  143. }, {
  144. key: "_compile",
  145. value: function _compile(math, argNames) {
  146. var evalObject = this.object._compile(math, argNames);
  147. var evalIndex = this.index ? this.index._compile(math, argNames) : null;
  148. var evalValue = this.value._compile(math, argNames);
  149. var name = this.object.name;
  150. if (!this.index) {
  151. // apply a variable to the scope, for example `a=2`
  152. if (!(0, _is.isSymbolNode)(this.object)) {
  153. throw new TypeError('SymbolNode expected as object');
  154. }
  155. return function evalAssignmentNode(scope, args, context) {
  156. var value = evalValue(scope, args, context);
  157. scope.set(name, value);
  158. return value;
  159. };
  160. } else if (this.index.isObjectProperty()) {
  161. // apply an object property for example `a.b=2`
  162. var prop = this.index.getObjectProperty();
  163. return function evalAssignmentNode(scope, args, context) {
  164. var object = evalObject(scope, args, context);
  165. var value = evalValue(scope, args, context);
  166. (0, _customs.setSafeProperty)(object, prop, value);
  167. return value;
  168. };
  169. } else if ((0, _is.isSymbolNode)(this.object)) {
  170. // update a matrix subset, for example `a[2]=3`
  171. return function evalAssignmentNode(scope, args, context) {
  172. var childObject = evalObject(scope, args, context);
  173. var value = evalValue(scope, args, context);
  174. // Important: we pass childObject instead of context:
  175. var index = evalIndex(scope, args, childObject);
  176. scope.set(name, assign(childObject, index, value));
  177. return value;
  178. };
  179. } else {
  180. // isAccessorNode(node.object) === true
  181. // update a matrix subset, for example `a.b[2]=3`
  182. // we will not use the compile function of the AccessorNode, but
  183. // compile it ourselves here as we need the parent object of the
  184. // AccessorNode:
  185. // wee need to apply the updated object to parent object
  186. var evalParentObject = this.object.object._compile(math, argNames);
  187. if (this.object.index.isObjectProperty()) {
  188. var parentProp = this.object.index.getObjectProperty();
  189. return function evalAssignmentNode(scope, args, context) {
  190. var parent = evalParentObject(scope, args, context);
  191. var childObject = (0, _customs.getSafeProperty)(parent, parentProp);
  192. // Important: we pass childObject instead of context:
  193. var index = evalIndex(scope, args, childObject);
  194. var value = evalValue(scope, args, context);
  195. (0, _customs.setSafeProperty)(parent, parentProp, assign(childObject, index, value));
  196. return value;
  197. };
  198. } else {
  199. // if some parameters use the 'end' parameter, we need to calculate
  200. // the size
  201. var evalParentIndex = this.object.index._compile(math, argNames);
  202. return function evalAssignmentNode(scope, args, context) {
  203. var parent = evalParentObject(scope, args, context);
  204. // Important: we pass parent instead of context:
  205. var parentIndex = evalParentIndex(scope, args, parent);
  206. var childObject = access(parent, parentIndex);
  207. // Important: we pass childObject instead of context
  208. var index = evalIndex(scope, args, childObject);
  209. var value = evalValue(scope, args, context);
  210. assign(parent, parentIndex, assign(childObject, index, value));
  211. return value;
  212. };
  213. }
  214. }
  215. }
  216. /**
  217. * Execute a callback for each of the child nodes of this node
  218. * @param {function(child: Node, path: string, parent: Node)} callback
  219. */
  220. }, {
  221. key: "forEach",
  222. value: function forEach(callback) {
  223. callback(this.object, 'object', this);
  224. if (this.index) {
  225. callback(this.index, 'index', this);
  226. }
  227. callback(this.value, 'value', this);
  228. }
  229. /**
  230. * Create a new AssignmentNode whose children are the results of calling
  231. * the provided callback function for each child of the original node.
  232. * @param {function(child: Node, path: string, parent: Node): Node} callback
  233. * @returns {AssignmentNode} Returns a transformed copy of the node
  234. */
  235. }, {
  236. key: "map",
  237. value: function map(callback) {
  238. var object = this._ifNode(callback(this.object, 'object', this));
  239. var index = this.index ? this._ifNode(callback(this.index, 'index', this)) : null;
  240. var value = this._ifNode(callback(this.value, 'value', this));
  241. return new AssignmentNode(object, index, value);
  242. }
  243. /**
  244. * Create a clone of this node, a shallow copy
  245. * @return {AssignmentNode}
  246. */
  247. }, {
  248. key: "clone",
  249. value: function clone() {
  250. return new AssignmentNode(this.object, this.index, this.value);
  251. }
  252. /**
  253. * Get string representation
  254. * @param {Object} options
  255. * @return {string}
  256. */
  257. }, {
  258. key: "_toString",
  259. value: function _toString(options) {
  260. var object = this.object.toString(options);
  261. var index = this.index ? this.index.toString(options) : '';
  262. var value = this.value.toString(options);
  263. if (needParenthesis(this, options && options.parenthesis, options && options.implicit)) {
  264. value = '(' + value + ')';
  265. }
  266. return object + index + ' = ' + value;
  267. }
  268. /**
  269. * Get a JSON representation of the node
  270. * @returns {Object}
  271. */
  272. }, {
  273. key: "toJSON",
  274. value: function toJSON() {
  275. return {
  276. mathjs: name,
  277. object: this.object,
  278. index: this.index,
  279. value: this.value
  280. };
  281. }
  282. /**
  283. * Instantiate an AssignmentNode from its JSON representation
  284. * @param {Object} json
  285. * An object structured like
  286. * `{"mathjs": "AssignmentNode", object: ..., index: ..., value: ...}`,
  287. * where mathjs is optional
  288. * @returns {AssignmentNode}
  289. */
  290. }, {
  291. key: "toHTML",
  292. value:
  293. /**
  294. * Get HTML representation
  295. * @param {Object} options
  296. * @return {string}
  297. */
  298. function toHTML(options) {
  299. var object = this.object.toHTML(options);
  300. var index = this.index ? this.index.toHTML(options) : '';
  301. var value = this.value.toHTML(options);
  302. if (needParenthesis(this, options && options.parenthesis, options && options.implicit)) {
  303. value = '<span class="math-paranthesis math-round-parenthesis">(</span>' + value + '<span class="math-paranthesis math-round-parenthesis">)</span>';
  304. }
  305. return object + index + '<span class="math-operator math-assignment-operator ' + 'math-variable-assignment-operator math-binary-operator">=</span>' + value;
  306. }
  307. /**
  308. * Get LaTeX representation
  309. * @param {Object} options
  310. * @return {string}
  311. */
  312. }, {
  313. key: "_toTex",
  314. value: function _toTex(options) {
  315. var object = this.object.toTex(options);
  316. var index = this.index ? this.index.toTex(options) : '';
  317. var value = this.value.toTex(options);
  318. if (needParenthesis(this, options && options.parenthesis, options && options.implicit)) {
  319. value = "\\left(".concat(value, "\\right)");
  320. }
  321. return object + index + ':=' + value;
  322. }
  323. }], [{
  324. key: "fromJSON",
  325. value: function fromJSON(json) {
  326. return new AssignmentNode(json.object, json.index, json.value);
  327. }
  328. }]);
  329. return AssignmentNode;
  330. }(Node);
  331. (0, _defineProperty2["default"])(AssignmentNode, "name", name);
  332. return AssignmentNode;
  333. }, {
  334. isClass: true,
  335. isNode: true
  336. });
  337. exports.createAssignmentNode = createAssignmentNode;