operators.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.getAssociativity = getAssociativity;
  6. exports.getOperator = getOperator;
  7. exports.getPrecedence = getPrecedence;
  8. exports.isAssociativeWith = isAssociativeWith;
  9. exports.properties = void 0;
  10. var _object = require("../utils/object.js");
  11. var _is = require("../utils/is.js");
  12. function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
  13. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  14. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } // list of identifiers of nodes in order of their precedence
  15. // also contains information about left/right associativity
  16. // and which other operator the operator is associative with
  17. // Example:
  18. // addition is associative with addition and subtraction, because:
  19. // (a+b)+c=a+(b+c)
  20. // (a+b)-c=a+(b-c)
  21. //
  22. // postfix operators are left associative, prefix operators
  23. // are right associative
  24. //
  25. // It's also possible to set the following properties:
  26. // latexParens: if set to false, this node doesn't need to be enclosed
  27. // in parentheses when using LaTeX
  28. // latexLeftParens: if set to false, this !OperatorNode's!
  29. // left argument doesn't need to be enclosed
  30. // in parentheses
  31. // latexRightParens: the same for the right argument
  32. var properties = [{
  33. // assignment
  34. AssignmentNode: {},
  35. FunctionAssignmentNode: {}
  36. }, {
  37. // conditional expression
  38. ConditionalNode: {
  39. latexLeftParens: false,
  40. latexRightParens: false,
  41. latexParens: false
  42. // conditionals don't need parentheses in LaTeX because
  43. // they are 2 dimensional
  44. }
  45. }, {
  46. // logical or
  47. 'OperatorNode:or': {
  48. op: 'or',
  49. associativity: 'left',
  50. associativeWith: []
  51. }
  52. }, {
  53. // logical xor
  54. 'OperatorNode:xor': {
  55. op: 'xor',
  56. associativity: 'left',
  57. associativeWith: []
  58. }
  59. }, {
  60. // logical and
  61. 'OperatorNode:and': {
  62. op: 'and',
  63. associativity: 'left',
  64. associativeWith: []
  65. }
  66. }, {
  67. // bitwise or
  68. 'OperatorNode:bitOr': {
  69. op: '|',
  70. associativity: 'left',
  71. associativeWith: []
  72. }
  73. }, {
  74. // bitwise xor
  75. 'OperatorNode:bitXor': {
  76. op: '^|',
  77. associativity: 'left',
  78. associativeWith: []
  79. }
  80. }, {
  81. // bitwise and
  82. 'OperatorNode:bitAnd': {
  83. op: '&',
  84. associativity: 'left',
  85. associativeWith: []
  86. }
  87. }, {
  88. // relational operators
  89. 'OperatorNode:equal': {
  90. op: '==',
  91. associativity: 'left',
  92. associativeWith: []
  93. },
  94. 'OperatorNode:unequal': {
  95. op: '!=',
  96. associativity: 'left',
  97. associativeWith: []
  98. },
  99. 'OperatorNode:smaller': {
  100. op: '<',
  101. associativity: 'left',
  102. associativeWith: []
  103. },
  104. 'OperatorNode:larger': {
  105. op: '>',
  106. associativity: 'left',
  107. associativeWith: []
  108. },
  109. 'OperatorNode:smallerEq': {
  110. op: '<=',
  111. associativity: 'left',
  112. associativeWith: []
  113. },
  114. 'OperatorNode:largerEq': {
  115. op: '>=',
  116. associativity: 'left',
  117. associativeWith: []
  118. },
  119. RelationalNode: {
  120. associativity: 'left',
  121. associativeWith: []
  122. }
  123. }, {
  124. // bitshift operators
  125. 'OperatorNode:leftShift': {
  126. op: '<<',
  127. associativity: 'left',
  128. associativeWith: []
  129. },
  130. 'OperatorNode:rightArithShift': {
  131. op: '>>',
  132. associativity: 'left',
  133. associativeWith: []
  134. },
  135. 'OperatorNode:rightLogShift': {
  136. op: '>>>',
  137. associativity: 'left',
  138. associativeWith: []
  139. }
  140. }, {
  141. // unit conversion
  142. 'OperatorNode:to': {
  143. op: 'to',
  144. associativity: 'left',
  145. associativeWith: []
  146. }
  147. }, {
  148. // range
  149. RangeNode: {}
  150. }, {
  151. // addition, subtraction
  152. 'OperatorNode:add': {
  153. op: '+',
  154. associativity: 'left',
  155. associativeWith: ['OperatorNode:add', 'OperatorNode:subtract']
  156. },
  157. 'OperatorNode:subtract': {
  158. op: '-',
  159. associativity: 'left',
  160. associativeWith: []
  161. }
  162. }, {
  163. // multiply, divide, modulus
  164. 'OperatorNode:multiply': {
  165. op: '*',
  166. associativity: 'left',
  167. associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'Operator:dotMultiply', 'Operator:dotDivide']
  168. },
  169. 'OperatorNode:divide': {
  170. op: '/',
  171. associativity: 'left',
  172. associativeWith: [],
  173. latexLeftParens: false,
  174. latexRightParens: false,
  175. latexParens: false
  176. // fractions don't require parentheses because
  177. // they're 2 dimensional, so parens aren't needed
  178. // in LaTeX
  179. },
  180. 'OperatorNode:dotMultiply': {
  181. op: '.*',
  182. associativity: 'left',
  183. associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'OperatorNode:dotMultiply', 'OperatorNode:doDivide']
  184. },
  185. 'OperatorNode:dotDivide': {
  186. op: './',
  187. associativity: 'left',
  188. associativeWith: []
  189. },
  190. 'OperatorNode:mod': {
  191. op: 'mod',
  192. associativity: 'left',
  193. associativeWith: []
  194. }
  195. }, {
  196. // Repeat multiplication for implicit multiplication
  197. 'OperatorNode:multiply': {
  198. associativity: 'left',
  199. associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'Operator:dotMultiply', 'Operator:dotDivide']
  200. }
  201. }, {
  202. // unary prefix operators
  203. 'OperatorNode:unaryPlus': {
  204. op: '+',
  205. associativity: 'right'
  206. },
  207. 'OperatorNode:unaryMinus': {
  208. op: '-',
  209. associativity: 'right'
  210. },
  211. 'OperatorNode:bitNot': {
  212. op: '~',
  213. associativity: 'right'
  214. },
  215. 'OperatorNode:not': {
  216. op: 'not',
  217. associativity: 'right'
  218. }
  219. }, {
  220. // exponentiation
  221. 'OperatorNode:pow': {
  222. op: '^',
  223. associativity: 'right',
  224. associativeWith: [],
  225. latexRightParens: false
  226. // the exponent doesn't need parentheses in
  227. // LaTeX because it's 2 dimensional
  228. // (it's on top)
  229. },
  230. 'OperatorNode:dotPow': {
  231. op: '.^',
  232. associativity: 'right',
  233. associativeWith: []
  234. }
  235. }, {
  236. // factorial
  237. 'OperatorNode:factorial': {
  238. op: '!',
  239. associativity: 'left'
  240. }
  241. }, {
  242. // matrix transpose
  243. 'OperatorNode:ctranspose': {
  244. op: "'",
  245. associativity: 'left'
  246. }
  247. }];
  248. /**
  249. * Returns the first non-parenthesis internal node, but only
  250. * when the 'parenthesis' option is unset or auto.
  251. * @param {Node} _node
  252. * @param {string} parenthesis
  253. * @return {Node}
  254. */
  255. exports.properties = properties;
  256. function unwrapParen(_node, parenthesis) {
  257. if (!parenthesis || parenthesis !== 'auto') return _node;
  258. var node = _node;
  259. while ((0, _is.isParenthesisNode)(node)) node = node.content;
  260. return node;
  261. }
  262. /**
  263. * Get the precedence of a Node.
  264. * Higher number for higher precedence, starting with 0.
  265. * Returns null if the precedence is undefined.
  266. *
  267. * @param {Node} _node
  268. * @param {string} parenthesis
  269. * @param {string} implicit
  270. * @param {Node} parent (for determining context for implicit multiplication)
  271. * @return {number | null}
  272. */
  273. function getPrecedence(_node, parenthesis, implicit, parent) {
  274. var node = _node;
  275. if (parenthesis !== 'keep') {
  276. // ParenthesisNodes are only ignored when not in 'keep' mode
  277. node = _node.getContent();
  278. }
  279. var identifier = node.getIdentifier();
  280. var precedence = null;
  281. for (var i = 0; i < properties.length; i++) {
  282. if (identifier in properties[i]) {
  283. precedence = i;
  284. break;
  285. }
  286. }
  287. // Bump up precedence of implicit multiplication, except when preceded
  288. // by a "Rule 2" fraction ( [unaryOp]constant / constant )
  289. if (identifier === 'OperatorNode:multiply' && node.implicit && implicit !== 'show') {
  290. var leftArg = unwrapParen(node.args[0], parenthesis);
  291. if (!((0, _is.isConstantNode)(leftArg) && parent && parent.getIdentifier() === 'OperatorNode:divide' && (0, _is.rule2Node)(unwrapParen(parent.args[0], parenthesis))) && !(leftArg.getIdentifier() === 'OperatorNode:divide' && (0, _is.rule2Node)(unwrapParen(leftArg.args[0], parenthesis)) && (0, _is.isConstantNode)(unwrapParen(leftArg.args[1])))) {
  292. precedence += 1;
  293. }
  294. }
  295. return precedence;
  296. }
  297. /**
  298. * Get the associativity of an operator (left or right).
  299. * Returns a string containing 'left' or 'right' or null if
  300. * the associativity is not defined.
  301. *
  302. * @param {Node} _node
  303. * @param {string} parenthesis
  304. * @return {string|null}
  305. * @throws {Error}
  306. */
  307. function getAssociativity(_node, parenthesis) {
  308. var node = _node;
  309. if (parenthesis !== 'keep') {
  310. // ParenthesisNodes are only ignored when not in 'keep' mode
  311. node = _node.getContent();
  312. }
  313. var identifier = node.getIdentifier();
  314. var index = getPrecedence(node, parenthesis);
  315. if (index === null) {
  316. // node isn't in the list
  317. return null;
  318. }
  319. var property = properties[index][identifier];
  320. if ((0, _object.hasOwnProperty)(property, 'associativity')) {
  321. if (property.associativity === 'left') {
  322. return 'left';
  323. }
  324. if (property.associativity === 'right') {
  325. return 'right';
  326. }
  327. // associativity is invalid
  328. throw Error('\'' + identifier + '\' has the invalid associativity \'' + property.associativity + '\'.');
  329. }
  330. // associativity is undefined
  331. return null;
  332. }
  333. /**
  334. * Check if an operator is associative with another operator.
  335. * Returns either true or false or null if not defined.
  336. *
  337. * @param {Node} nodeA
  338. * @param {Node} nodeB
  339. * @param {string} parenthesis
  340. * @return {boolean | null}
  341. */
  342. function isAssociativeWith(nodeA, nodeB, parenthesis) {
  343. // ParenthesisNodes are only ignored when not in 'keep' mode
  344. var a = parenthesis !== 'keep' ? nodeA.getContent() : nodeA;
  345. var b = parenthesis !== 'keep' ? nodeA.getContent() : nodeB;
  346. var identifierA = a.getIdentifier();
  347. var identifierB = b.getIdentifier();
  348. var index = getPrecedence(a, parenthesis);
  349. if (index === null) {
  350. // node isn't in the list
  351. return null;
  352. }
  353. var property = properties[index][identifierA];
  354. if ((0, _object.hasOwnProperty)(property, 'associativeWith') && property.associativeWith instanceof Array) {
  355. for (var i = 0; i < property.associativeWith.length; i++) {
  356. if (property.associativeWith[i] === identifierB) {
  357. return true;
  358. }
  359. }
  360. return false;
  361. }
  362. // associativeWith is not defined
  363. return null;
  364. }
  365. /**
  366. * Get the operator associated with a function name.
  367. * Returns a string with the operator symbol, or null if the
  368. * input is not the name of a function associated with an
  369. * operator.
  370. *
  371. * @param {string} Function name
  372. * @return {string | null} Associated operator symbol, if any
  373. */
  374. function getOperator(fn) {
  375. var identifier = 'OperatorNode:' + fn;
  376. var _iterator = _createForOfIteratorHelper(properties),
  377. _step;
  378. try {
  379. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  380. var group = _step.value;
  381. if (identifier in group) {
  382. return group[identifier].op;
  383. }
  384. }
  385. } catch (err) {
  386. _iterator.e(err);
  387. } finally {
  388. _iterator.f();
  389. }
  390. return null;
  391. }