AssignmentNode.js 11 KB

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