FunctionNode.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.createFunctionNode = void 0;
  7. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  8. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
  9. var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
  10. var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));
  11. var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
  12. var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
  13. var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
  14. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  15. var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
  16. var _is = require("../../utils/is.js");
  17. var _string = require("../../utils/string.js");
  18. var _object = require("../../utils/object.js");
  19. var _customs = require("../../utils/customs.js");
  20. var _scope = require("../../utils/scope.js");
  21. var _factory = require("../../utils/factory.js");
  22. var _latex = require("../../utils/latex.js");
  23. 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); }; }
  24. 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; } }
  25. var name = 'FunctionNode';
  26. var dependencies = ['math', 'Node', 'SymbolNode'];
  27. var createFunctionNode = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  28. var math = _ref.math,
  29. Node = _ref.Node,
  30. SymbolNode = _ref.SymbolNode;
  31. /* format to fixed length */
  32. var strin = function strin(entity) {
  33. return (0, _string.format)(entity, {
  34. truncate: 78
  35. });
  36. };
  37. /*
  38. * Expand a LaTeX template
  39. *
  40. * @param {string} template
  41. * @param {Node} node
  42. * @param {Object} options
  43. * @private
  44. **/
  45. function expandTemplate(template, node, options) {
  46. var latex = '';
  47. // Match everything of the form ${identifier} or ${identifier[2]} or $$
  48. // while submatching identifier and 2 (in the second case)
  49. var regex = /\$(?:\{([a-z_][a-z_0-9]*)(?:\[([0-9]+)\])?\}|\$)/gi;
  50. var inputPos = 0; // position in the input string
  51. var match;
  52. while ((match = regex.exec(template)) !== null) {
  53. // go through all matches
  54. // add everything in front of the match to the LaTeX string
  55. latex += template.substring(inputPos, match.index);
  56. inputPos = match.index;
  57. if (match[0] === '$$') {
  58. // escaped dollar sign
  59. latex += '$';
  60. inputPos++;
  61. } else {
  62. // template parameter
  63. inputPos += match[0].length;
  64. var property = node[match[1]];
  65. if (!property) {
  66. throw new ReferenceError('Template: Property ' + match[1] + ' does not exist.');
  67. }
  68. if (match[2] === undefined) {
  69. // no square brackets
  70. switch ((0, _typeof2["default"])(property)) {
  71. case 'string':
  72. latex += property;
  73. break;
  74. case 'object':
  75. if ((0, _is.isNode)(property)) {
  76. latex += property.toTex(options);
  77. } else if (Array.isArray(property)) {
  78. // make array of Nodes into comma separated list
  79. latex += property.map(function (arg, index) {
  80. if ((0, _is.isNode)(arg)) {
  81. return arg.toTex(options);
  82. }
  83. throw new TypeError('Template: ' + match[1] + '[' + index + '] is not a Node.');
  84. }).join(',');
  85. } else {
  86. throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes');
  87. }
  88. break;
  89. default:
  90. throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes');
  91. }
  92. } else {
  93. // with square brackets
  94. if ((0, _is.isNode)(property[match[2]] && property[match[2]])) {
  95. latex += property[match[2]].toTex(options);
  96. } else {
  97. throw new TypeError('Template: ' + match[1] + '[' + match[2] + '] is not a Node.');
  98. }
  99. }
  100. }
  101. }
  102. latex += template.slice(inputPos); // append rest of the template
  103. return latex;
  104. }
  105. var FunctionNode = /*#__PURE__*/function (_Node) {
  106. (0, _inherits2["default"])(FunctionNode, _Node);
  107. var _super = _createSuper(FunctionNode);
  108. /**
  109. * @constructor FunctionNode
  110. * @extends {./Node}
  111. * invoke a list with arguments on a node
  112. * @param {./Node | string} fn
  113. * Item resolving to a function on which to invoke
  114. * the arguments, typically a SymboNode or AccessorNode
  115. * @param {./Node[]} args
  116. */
  117. function FunctionNode(fn, args) {
  118. var _this;
  119. (0, _classCallCheck2["default"])(this, FunctionNode);
  120. _this = _super.call(this);
  121. if (typeof fn === 'string') {
  122. fn = new SymbolNode(fn);
  123. }
  124. // validate input
  125. if (!(0, _is.isNode)(fn)) throw new TypeError('Node expected as parameter "fn"');
  126. if (!Array.isArray(args) || !args.every(_is.isNode)) {
  127. throw new TypeError('Array containing Nodes expected for parameter "args"');
  128. }
  129. _this.fn = fn;
  130. _this.args = args || [];
  131. return _this;
  132. }
  133. // readonly property name
  134. (0, _createClass2["default"])(FunctionNode, [{
  135. key: "name",
  136. get: function get() {
  137. return this.fn.name || '';
  138. }
  139. }, {
  140. key: "type",
  141. get: function get() {
  142. return name;
  143. }
  144. }, {
  145. key: "isFunctionNode",
  146. get: function get() {
  147. return true;
  148. }
  149. /**
  150. * Compile a node into a JavaScript function.
  151. * This basically pre-calculates as much as possible and only leaves open
  152. * calculations which depend on a dynamic scope with variables.
  153. * @param {Object} math Math.js namespace with functions and constants.
  154. * @param {Object} argNames An object with argument names as key and `true`
  155. * as value. Used in the SymbolNode to optimize
  156. * for arguments from user assigned functions
  157. * (see FunctionAssignmentNode) or special symbols
  158. * like `end` (see IndexNode).
  159. * @return {function} Returns a function which can be called like:
  160. * evalNode(scope: Object, args: Object, context: *)
  161. */
  162. }, {
  163. key: "_compile",
  164. value: function _compile(math, argNames) {
  165. // compile arguments
  166. var evalArgs = this.args.map(function (arg) {
  167. return arg._compile(math, argNames);
  168. });
  169. if ((0, _is.isSymbolNode)(this.fn)) {
  170. var _name = this.fn.name;
  171. if (!argNames[_name]) {
  172. // we can statically determine whether the function
  173. // has the rawArgs property
  174. var fn = _name in math ? (0, _customs.getSafeProperty)(math, _name) : undefined;
  175. var isRaw = typeof fn === 'function' && fn.rawArgs === true;
  176. var resolveFn = function resolveFn(scope) {
  177. var value;
  178. if (scope.has(_name)) {
  179. value = scope.get(_name);
  180. } else if (_name in math) {
  181. value = (0, _customs.getSafeProperty)(math, _name);
  182. } else {
  183. return FunctionNode.onUndefinedFunction(_name);
  184. }
  185. if (typeof value === 'function') {
  186. return value;
  187. }
  188. throw new TypeError("'".concat(_name, "' is not a function; its value is:\n ").concat(strin(value)));
  189. };
  190. if (isRaw) {
  191. // pass unevaluated parameters (nodes) to the function
  192. // "raw" evaluation
  193. var rawArgs = this.args;
  194. return function evalFunctionNode(scope, args, context) {
  195. var fn = resolveFn(scope);
  196. return fn(rawArgs, math, (0, _scope.createSubScope)(scope, args), scope);
  197. };
  198. } else {
  199. // "regular" evaluation
  200. switch (evalArgs.length) {
  201. case 0:
  202. return function evalFunctionNode(scope, args, context) {
  203. var fn = resolveFn(scope);
  204. return fn();
  205. };
  206. case 1:
  207. return function evalFunctionNode(scope, args, context) {
  208. var fn = resolveFn(scope);
  209. var evalArg0 = evalArgs[0];
  210. return fn(evalArg0(scope, args, context));
  211. };
  212. case 2:
  213. return function evalFunctionNode(scope, args, context) {
  214. var fn = resolveFn(scope);
  215. var evalArg0 = evalArgs[0];
  216. var evalArg1 = evalArgs[1];
  217. return fn(evalArg0(scope, args, context), evalArg1(scope, args, context));
  218. };
  219. default:
  220. return function evalFunctionNode(scope, args, context) {
  221. var fn = resolveFn(scope);
  222. var values = evalArgs.map(function (evalArg) {
  223. return evalArg(scope, args, context);
  224. });
  225. return fn.apply(void 0, (0, _toConsumableArray2["default"])(values));
  226. };
  227. }
  228. }
  229. } else {
  230. // the function symbol is an argName
  231. var _rawArgs = this.args;
  232. return function evalFunctionNode(scope, args, context) {
  233. var fn = args[_name];
  234. if (typeof fn !== 'function') {
  235. throw new TypeError("Argument '".concat(_name, "' was not a function; received: ").concat(strin(fn)));
  236. }
  237. if (fn.rawArgs) {
  238. // "Raw" evaluation
  239. return fn(_rawArgs, math, (0, _scope.createSubScope)(scope, args), scope);
  240. } else {
  241. var values = evalArgs.map(function (evalArg) {
  242. return evalArg(scope, args, context);
  243. });
  244. return fn.apply(fn, values);
  245. }
  246. };
  247. }
  248. } else if ((0, _is.isAccessorNode)(this.fn) && (0, _is.isIndexNode)(this.fn.index) && this.fn.index.isObjectProperty()) {
  249. // execute the function with the right context:
  250. // the object of the AccessorNode
  251. var evalObject = this.fn.object._compile(math, argNames);
  252. var prop = this.fn.index.getObjectProperty();
  253. var _rawArgs2 = this.args;
  254. return function evalFunctionNode(scope, args, context) {
  255. var object = evalObject(scope, args, context);
  256. (0, _customs.validateSafeMethod)(object, prop);
  257. var isRaw = object[prop] && object[prop].rawArgs;
  258. if (isRaw) {
  259. // "Raw" evaluation
  260. return object[prop](_rawArgs2, math, (0, _scope.createSubScope)(scope, args), scope);
  261. } else {
  262. // "regular" evaluation
  263. var values = evalArgs.map(function (evalArg) {
  264. return evalArg(scope, args, context);
  265. });
  266. return object[prop].apply(object, values);
  267. }
  268. };
  269. } else {
  270. // node.fn.isAccessorNode && !node.fn.index.isObjectProperty()
  271. // we have to dynamically determine whether the function has the
  272. // rawArgs property
  273. var fnExpr = this.fn.toString();
  274. var evalFn = this.fn._compile(math, argNames);
  275. var _rawArgs3 = this.args;
  276. return function evalFunctionNode(scope, args, context) {
  277. var fn = evalFn(scope, args, context);
  278. if (typeof fn !== 'function') {
  279. throw new TypeError("Expression '".concat(fnExpr, "' did not evaluate to a function; value is:") + "\n ".concat(strin(fn)));
  280. }
  281. if (fn.rawArgs) {
  282. // "Raw" evaluation
  283. return fn(_rawArgs3, math, (0, _scope.createSubScope)(scope, args), scope);
  284. } else {
  285. // "regular" evaluation
  286. var values = evalArgs.map(function (evalArg) {
  287. return evalArg(scope, args, context);
  288. });
  289. return fn.apply(fn, values);
  290. }
  291. };
  292. }
  293. }
  294. /**
  295. * Execute a callback for each of the child nodes of this node
  296. * @param {function(child: Node, path: string, parent: Node)} callback
  297. */
  298. }, {
  299. key: "forEach",
  300. value: function forEach(callback) {
  301. callback(this.fn, 'fn', this);
  302. for (var i = 0; i < this.args.length; i++) {
  303. callback(this.args[i], 'args[' + i + ']', this);
  304. }
  305. }
  306. /**
  307. * Create a new FunctionNode whose children are the results of calling
  308. * the provided callback function for each child of the original node.
  309. * @param {function(child: Node, path: string, parent: Node): Node} callback
  310. * @returns {FunctionNode} Returns a transformed copy of the node
  311. */
  312. }, {
  313. key: "map",
  314. value: function map(callback) {
  315. var fn = this._ifNode(callback(this.fn, 'fn', this));
  316. var args = [];
  317. for (var i = 0; i < this.args.length; i++) {
  318. args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this));
  319. }
  320. return new FunctionNode(fn, args);
  321. }
  322. /**
  323. * Create a clone of this node, a shallow copy
  324. * @return {FunctionNode}
  325. */
  326. }, {
  327. key: "clone",
  328. value: function clone() {
  329. return new FunctionNode(this.fn, this.args.slice(0));
  330. }
  331. /**
  332. * Throws an error 'Undefined function {name}'
  333. * @param {string} name
  334. */
  335. }, {
  336. key: "toString",
  337. value:
  338. /**
  339. * Get string representation. (wrapper function)
  340. * This overrides parts of Node's toString function.
  341. * If callback is an object containing callbacks, it
  342. * calls the correct callback for the current node,
  343. * otherwise it falls back to calling Node's toString
  344. * function.
  345. *
  346. * @param {Object} options
  347. * @return {string} str
  348. * @override
  349. */
  350. function toString(options) {
  351. var customString;
  352. var name = this.fn.toString(options);
  353. if (options && (0, _typeof2["default"])(options.handler) === 'object' && (0, _object.hasOwnProperty)(options.handler, name)) {
  354. // callback is a map of callback functions
  355. customString = options.handler[name](this, options);
  356. }
  357. if (typeof customString !== 'undefined') {
  358. return customString;
  359. }
  360. // fall back to Node's toString
  361. return (0, _get2["default"])((0, _getPrototypeOf2["default"])(FunctionNode.prototype), "toString", this).call(this, options);
  362. }
  363. /**
  364. * Get string representation
  365. * @param {Object} options
  366. * @return {string} str
  367. */
  368. }, {
  369. key: "_toString",
  370. value: function _toString(options) {
  371. var args = this.args.map(function (arg) {
  372. return arg.toString(options);
  373. });
  374. var fn = (0, _is.isFunctionAssignmentNode)(this.fn) ? '(' + this.fn.toString(options) + ')' : this.fn.toString(options);
  375. // format the arguments like "add(2, 4.2)"
  376. return fn + '(' + args.join(', ') + ')';
  377. }
  378. /**
  379. * Get a JSON representation of the node
  380. * @returns {Object}
  381. */
  382. }, {
  383. key: "toJSON",
  384. value: function toJSON() {
  385. return {
  386. mathjs: name,
  387. fn: this.fn,
  388. args: this.args
  389. };
  390. }
  391. /**
  392. * Instantiate an AssignmentNode from its JSON representation
  393. * @param {Object} json An object structured like
  394. * `{"mathjs": "FunctionNode", fn: ..., args: ...}`,
  395. * where mathjs is optional
  396. * @returns {FunctionNode}
  397. */
  398. }, {
  399. key: "toHTML",
  400. value:
  401. /**
  402. * Get HTML representation
  403. * @param {Object} options
  404. * @return {string} str
  405. */
  406. function toHTML(options) {
  407. var args = this.args.map(function (arg) {
  408. return arg.toHTML(options);
  409. });
  410. // format the arguments like "add(2, 4.2)"
  411. return '<span class="math-function">' + (0, _string.escape)(this.fn) + '</span><span class="math-paranthesis math-round-parenthesis">(</span>' + args.join('<span class="math-separator">,</span>') + '<span class="math-paranthesis math-round-parenthesis">)</span>';
  412. }
  413. /**
  414. * Get LaTeX representation. (wrapper function)
  415. * This overrides parts of Node's toTex function.
  416. * If callback is an object containing callbacks, it
  417. * calls the correct callback for the current node,
  418. * otherwise it falls back to calling Node's toTex
  419. * function.
  420. *
  421. * @param {Object} options
  422. * @return {string}
  423. */
  424. }, {
  425. key: "toTex",
  426. value: function toTex(options) {
  427. var customTex;
  428. if (options && (0, _typeof2["default"])(options.handler) === 'object' && (0, _object.hasOwnProperty)(options.handler, this.name)) {
  429. // callback is a map of callback functions
  430. customTex = options.handler[this.name](this, options);
  431. }
  432. if (typeof customTex !== 'undefined') {
  433. return customTex;
  434. }
  435. // fall back to Node's toTex
  436. return (0, _get2["default"])((0, _getPrototypeOf2["default"])(FunctionNode.prototype), "toTex", this).call(this, options);
  437. }
  438. /**
  439. * Get LaTeX representation
  440. * @param {Object} options
  441. * @return {string} str
  442. */
  443. }, {
  444. key: "_toTex",
  445. value: function _toTex(options) {
  446. var args = this.args.map(function (arg) {
  447. // get LaTeX of the arguments
  448. return arg.toTex(options);
  449. });
  450. var latexConverter;
  451. if (_latex.latexFunctions[this.name]) {
  452. latexConverter = _latex.latexFunctions[this.name];
  453. }
  454. // toTex property on the function itself
  455. if (math[this.name] && (typeof math[this.name].toTex === 'function' || (0, _typeof2["default"])(math[this.name].toTex) === 'object' || typeof math[this.name].toTex === 'string')) {
  456. // .toTex is a callback function
  457. latexConverter = math[this.name].toTex;
  458. }
  459. var customToTex;
  460. switch ((0, _typeof2["default"])(latexConverter)) {
  461. case 'function':
  462. // a callback function
  463. customToTex = latexConverter(this, options);
  464. break;
  465. case 'string':
  466. // a template string
  467. customToTex = expandTemplate(latexConverter, this, options);
  468. break;
  469. case 'object':
  470. // an object with different "converters" for different
  471. // numbers of arguments
  472. switch ((0, _typeof2["default"])(latexConverter[args.length])) {
  473. case 'function':
  474. customToTex = latexConverter[args.length](this, options);
  475. break;
  476. case 'string':
  477. customToTex = expandTemplate(latexConverter[args.length], this, options);
  478. break;
  479. }
  480. }
  481. if (typeof customToTex !== 'undefined') {
  482. return customToTex;
  483. }
  484. return expandTemplate(_latex.defaultTemplate, this, options);
  485. }
  486. /**
  487. * Get identifier.
  488. * @return {string}
  489. */
  490. }, {
  491. key: "getIdentifier",
  492. value: function getIdentifier() {
  493. return this.type + ':' + this.name;
  494. }
  495. }]);
  496. return FunctionNode;
  497. }(Node);
  498. (0, _defineProperty2["default"])(FunctionNode, "name", name);
  499. (0, _defineProperty2["default"])(FunctionNode, "onUndefinedFunction", function (name) {
  500. throw new Error('Undefined function ' + name);
  501. });
  502. (0, _defineProperty2["default"])(FunctionNode, "fromJSON", function (json) {
  503. return new FunctionNode(json.fn, json.args);
  504. });
  505. return FunctionNode;
  506. }, {
  507. isClass: true,
  508. isNode: true
  509. });
  510. exports.createFunctionNode = createFunctionNode;