semantic_processor.js 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  1. import * as DomUtil from '../common/dom_util.js';
  2. import { NamedSymbol, SemanticMap } from './semantic_attr.js';
  3. import { SemanticFont, SemanticRole, SemanticType, SemanticSecondary } from './semantic_meaning.js';
  4. import { SemanticHeuristics } from './semantic_heuristic_factory.js';
  5. import { SemanticNodeFactory } from './semantic_node_factory.js';
  6. import * as SemanticPred from './semantic_pred.js';
  7. import * as SemanticUtil from './semantic_util.js';
  8. import { MMLTAGS } from '../semantic_tree/semantic_util.js';
  9. export class SemanticProcessor {
  10. static getInstance() {
  11. SemanticProcessor.instance =
  12. SemanticProcessor.instance || new SemanticProcessor();
  13. return SemanticProcessor.instance;
  14. }
  15. static tableToMultiline(table) {
  16. if (!SemanticPred.tableIsMultiline(table)) {
  17. return SemanticHeuristics.run('rewrite_subcases', table, SemanticProcessor.classifyTable);
  18. }
  19. table.type = SemanticType.MULTILINE;
  20. for (let i = 0, row; (row = table.childNodes[i]); i++) {
  21. SemanticProcessor.rowToLine_(row, SemanticRole.MULTILINE);
  22. }
  23. if (table.childNodes.length === 1 &&
  24. !SemanticPred.lineIsLabelled(table.childNodes[0]) &&
  25. SemanticPred.isFencedElement(table.childNodes[0].childNodes[0])) {
  26. SemanticProcessor.tableToMatrixOrVector_(SemanticProcessor.rewriteFencedLine_(table));
  27. }
  28. SemanticProcessor.binomialForm_(table);
  29. SemanticProcessor.classifyMultiline(table);
  30. return table;
  31. }
  32. static number(node) {
  33. if (node.type === SemanticType.UNKNOWN ||
  34. node.type === SemanticType.IDENTIFIER) {
  35. node.type = SemanticType.NUMBER;
  36. }
  37. SemanticProcessor.meaningFromContent(node, SemanticProcessor.numberRole_);
  38. SemanticProcessor.exprFont_(node);
  39. }
  40. static classifyMultiline(multiline) {
  41. let index = 0;
  42. const length = multiline.childNodes.length;
  43. let line;
  44. while (index < length &&
  45. (!(line = multiline.childNodes[index]) || !line.childNodes.length)) {
  46. index++;
  47. }
  48. if (index >= length) {
  49. return;
  50. }
  51. const firstRole = line.childNodes[0].role;
  52. if (firstRole !== SemanticRole.UNKNOWN &&
  53. multiline.childNodes.every(function (x) {
  54. const cell = x.childNodes[0];
  55. return (!cell ||
  56. (cell.role === firstRole &&
  57. (SemanticPred.isType(cell, SemanticType.RELATION) ||
  58. SemanticPred.isType(cell, SemanticType.RELSEQ))));
  59. })) {
  60. multiline.role = firstRole;
  61. }
  62. }
  63. static classifyTable(table) {
  64. const columns = SemanticProcessor.computeColumns_(table);
  65. SemanticProcessor.classifyByColumns_(table, columns, SemanticRole.EQUALITY) ||
  66. SemanticProcessor.classifyByColumns_(table, columns, SemanticRole.INEQUALITY, [SemanticRole.EQUALITY]) ||
  67. SemanticProcessor.classifyByColumns_(table, columns, SemanticRole.ARROW) ||
  68. SemanticProcessor.detectCaleyTable(table);
  69. return table;
  70. }
  71. static detectCaleyTable(table) {
  72. if (!table.mathmlTree) {
  73. return false;
  74. }
  75. const tree = table.mathmlTree;
  76. const cl = tree.getAttribute('columnlines');
  77. const rl = tree.getAttribute('rowlines');
  78. if (!cl || !rl) {
  79. return false;
  80. }
  81. if (SemanticProcessor.cayleySpacing(cl) &&
  82. SemanticProcessor.cayleySpacing(rl)) {
  83. table.role = SemanticRole.CAYLEY;
  84. return true;
  85. }
  86. return false;
  87. }
  88. static cayleySpacing(lines) {
  89. const list = lines.split(' ');
  90. return ((list[0] === 'solid' || list[0] === 'dashed') &&
  91. list.slice(1).every((x) => x === 'none'));
  92. }
  93. static proof(node, semantics, parse) {
  94. const attrs = SemanticProcessor.separateSemantics(semantics);
  95. return SemanticProcessor.getInstance().proof(node, attrs, parse);
  96. }
  97. static findSemantics(node, attr, opt_value) {
  98. const value = opt_value == null ? null : opt_value;
  99. const semantics = SemanticProcessor.getSemantics(node);
  100. if (!semantics) {
  101. return false;
  102. }
  103. if (!semantics[attr]) {
  104. return false;
  105. }
  106. return value == null ? true : semantics[attr] === value;
  107. }
  108. static getSemantics(node) {
  109. const semantics = node.getAttribute('semantics');
  110. if (!semantics) {
  111. return null;
  112. }
  113. return SemanticProcessor.separateSemantics(semantics);
  114. }
  115. static removePrefix(name) {
  116. const [, ...rest] = name.split('_');
  117. return rest.join('_');
  118. }
  119. static separateSemantics(attr) {
  120. const result = {};
  121. attr.split(';').forEach(function (x) {
  122. const [name, value] = x.split(':');
  123. result[SemanticProcessor.removePrefix(name)] = value;
  124. });
  125. return result;
  126. }
  127. static matchSpaces_(nodes, ops) {
  128. for (let i = 0, op; (op = ops[i]); i++) {
  129. const node = nodes[i];
  130. const mt1 = node.mathmlTree;
  131. const mt2 = nodes[i + 1].mathmlTree;
  132. if (!mt1 || !mt2) {
  133. continue;
  134. }
  135. const sibling = mt1.nextSibling;
  136. if (!sibling || sibling === mt2) {
  137. continue;
  138. }
  139. const spacer = SemanticProcessor.getSpacer_(sibling);
  140. if (spacer) {
  141. op.mathml.push(spacer);
  142. op.mathmlTree = spacer;
  143. op.role = SemanticRole.SPACE;
  144. }
  145. }
  146. }
  147. static getSpacer_(node) {
  148. if (DomUtil.tagName(node) === MMLTAGS.MSPACE) {
  149. return node;
  150. }
  151. while (SemanticUtil.hasEmptyTag(node) && node.childNodes.length === 1) {
  152. node = node.childNodes[0];
  153. if (DomUtil.tagName(node) === MMLTAGS.MSPACE) {
  154. return node;
  155. }
  156. }
  157. return null;
  158. }
  159. static fenceToPunct_(fence) {
  160. const newRole = SemanticProcessor.FENCE_TO_PUNCT_[fence.role];
  161. if (!newRole) {
  162. return;
  163. }
  164. while (fence.embellished) {
  165. fence.embellished = SemanticType.PUNCTUATION;
  166. if (!(SemanticPred.isRole(fence, SemanticRole.SUBSUP) ||
  167. SemanticPred.isRole(fence, SemanticRole.UNDEROVER))) {
  168. fence.role = newRole;
  169. }
  170. fence = fence.childNodes[0];
  171. }
  172. fence.type = SemanticType.PUNCTUATION;
  173. fence.role = newRole;
  174. }
  175. static classifyFunction_(funcNode, restNodes) {
  176. if (funcNode.type === SemanticType.APPL ||
  177. funcNode.type === SemanticType.BIGOP ||
  178. funcNode.type === SemanticType.INTEGRAL) {
  179. return '';
  180. }
  181. if (restNodes[0] &&
  182. restNodes[0].textContent === NamedSymbol.functionApplication) {
  183. SemanticProcessor.getInstance().funcAppls[funcNode.id] =
  184. restNodes.shift();
  185. let role = SemanticRole.SIMPLEFUNC;
  186. SemanticHeuristics.run('simple2prefix', funcNode);
  187. if (funcNode.role === SemanticRole.PREFIXFUNC ||
  188. funcNode.role === SemanticRole.LIMFUNC) {
  189. role = funcNode.role;
  190. }
  191. SemanticProcessor.propagateFunctionRole_(funcNode, role);
  192. return 'prefix';
  193. }
  194. const kind = SemanticProcessor.CLASSIFY_FUNCTION_[funcNode.role];
  195. return kind
  196. ? kind
  197. : SemanticPred.isSimpleFunctionHead(funcNode)
  198. ? 'simple'
  199. : '';
  200. }
  201. static propagateFunctionRole_(funcNode, tag) {
  202. if (funcNode) {
  203. if (funcNode.type === SemanticType.INFIXOP) {
  204. return;
  205. }
  206. if (!(SemanticPred.isRole(funcNode, SemanticRole.SUBSUP) ||
  207. SemanticPred.isRole(funcNode, SemanticRole.UNDEROVER))) {
  208. funcNode.role = tag;
  209. }
  210. SemanticProcessor.propagateFunctionRole_(funcNode.childNodes[0], tag);
  211. }
  212. }
  213. static getFunctionOp_(tree, pred) {
  214. if (pred(tree)) {
  215. return tree;
  216. }
  217. for (let i = 0, child; (child = tree.childNodes[i]); i++) {
  218. const op = SemanticProcessor.getFunctionOp_(child, pred);
  219. if (op) {
  220. return op;
  221. }
  222. }
  223. return null;
  224. }
  225. static tableToMatrixOrVector_(node) {
  226. const matrix = node.childNodes[0];
  227. SemanticPred.isType(matrix, SemanticType.MULTILINE)
  228. ? SemanticProcessor.tableToVector_(node)
  229. : SemanticProcessor.tableToMatrix_(node);
  230. node.contentNodes.forEach(matrix.appendContentNode.bind(matrix));
  231. for (let i = 0, row; (row = matrix.childNodes[i]); i++) {
  232. SemanticProcessor.assignRoleToRow_(row, SemanticProcessor.getComponentRoles_(matrix));
  233. }
  234. matrix.parent = null;
  235. return matrix;
  236. }
  237. static tableToVector_(node) {
  238. const vector = node.childNodes[0];
  239. vector.type = SemanticType.VECTOR;
  240. if (vector.childNodes.length === 1) {
  241. SemanticProcessor.tableToSquare_(node);
  242. return;
  243. }
  244. SemanticProcessor.binomialForm_(vector);
  245. }
  246. static binomialForm_(node) {
  247. if (!SemanticPred.isRole(node, SemanticRole.UNKNOWN)) {
  248. return;
  249. }
  250. if (SemanticPred.isBinomial(node)) {
  251. node.role = SemanticRole.BINOMIAL;
  252. node.childNodes[0].role = SemanticRole.BINOMIAL;
  253. node.childNodes[1].role = SemanticRole.BINOMIAL;
  254. }
  255. }
  256. static tableToMatrix_(node) {
  257. const matrix = node.childNodes[0];
  258. matrix.type = SemanticType.MATRIX;
  259. if (matrix.childNodes &&
  260. matrix.childNodes.length > 0 &&
  261. matrix.childNodes[0].childNodes &&
  262. matrix.childNodes.length === matrix.childNodes[0].childNodes.length) {
  263. SemanticProcessor.tableToSquare_(node);
  264. return;
  265. }
  266. if (matrix.childNodes && matrix.childNodes.length === 1) {
  267. matrix.role = SemanticRole.ROWVECTOR;
  268. }
  269. }
  270. static tableToSquare_(node) {
  271. const matrix = node.childNodes[0];
  272. if (!SemanticPred.isRole(matrix, SemanticRole.UNKNOWN)) {
  273. return;
  274. }
  275. if (SemanticPred.isNeutralFence(node)) {
  276. matrix.role = SemanticRole.DETERMINANT;
  277. return;
  278. }
  279. matrix.role = SemanticRole.SQUAREMATRIX;
  280. }
  281. static getComponentRoles_(node) {
  282. const role = node.role;
  283. if (role && role !== SemanticRole.UNKNOWN) {
  284. return role;
  285. }
  286. return node.type.toLowerCase() || SemanticRole.UNKNOWN;
  287. }
  288. static tableToCases_(table, openFence) {
  289. for (let i = 0, row; (row = table.childNodes[i]); i++) {
  290. SemanticProcessor.assignRoleToRow_(row, SemanticRole.CASES);
  291. }
  292. table.type = SemanticType.CASES;
  293. table.appendContentNode(openFence);
  294. if (SemanticPred.tableIsMultiline(table)) {
  295. SemanticProcessor.binomialForm_(table);
  296. }
  297. return table;
  298. }
  299. static rewriteFencedLine_(table) {
  300. const line = table.childNodes[0];
  301. const fenced = table.childNodes[0].childNodes[0];
  302. const element = table.childNodes[0].childNodes[0].childNodes[0];
  303. fenced.parent = table.parent;
  304. table.parent = fenced;
  305. element.parent = line;
  306. fenced.childNodes = [table];
  307. line.childNodes = [element];
  308. return fenced;
  309. }
  310. static rowToLine_(row, opt_role) {
  311. const role = opt_role || SemanticRole.UNKNOWN;
  312. if (SemanticPred.isType(row, SemanticType.ROW)) {
  313. row.type = SemanticType.LINE;
  314. row.role = role;
  315. if (row.childNodes.length === 1 &&
  316. SemanticPred.isType(row.childNodes[0], SemanticType.CELL)) {
  317. row.childNodes = row.childNodes[0].childNodes;
  318. row.childNodes.forEach(function (x) {
  319. x.parent = row;
  320. });
  321. }
  322. }
  323. }
  324. static assignRoleToRow_(row, role) {
  325. if (SemanticPred.isType(row, SemanticType.LINE)) {
  326. row.role = role;
  327. return;
  328. }
  329. if (SemanticPred.isType(row, SemanticType.ROW)) {
  330. row.role = role;
  331. row.childNodes.forEach(function (cell) {
  332. if (SemanticPred.isType(cell, SemanticType.CELL)) {
  333. cell.role = role;
  334. }
  335. });
  336. }
  337. }
  338. static nextSeparatorFunction_(separators) {
  339. let sepList;
  340. if (separators) {
  341. if (separators.match(/^\s+$/)) {
  342. return null;
  343. }
  344. else {
  345. sepList = separators
  346. .replace(/\s/g, '')
  347. .split('')
  348. .filter(function (x) {
  349. return x;
  350. });
  351. }
  352. }
  353. else {
  354. sepList = [','];
  355. }
  356. return function () {
  357. if (sepList.length > 1) {
  358. return sepList.shift();
  359. }
  360. return sepList[0];
  361. };
  362. }
  363. static meaningFromContent(node, func) {
  364. const content = [...node.textContent].filter((x) => x.match(/[^\s]/));
  365. const meaning = content.map((x) => SemanticMap.Meaning.get(x));
  366. func(node, content, meaning);
  367. }
  368. static numberRole_(node, content, meaning) {
  369. if (node.role !== SemanticRole.UNKNOWN) {
  370. return;
  371. }
  372. if (meaning.every(function (x) {
  373. return ((x.type === SemanticType.NUMBER && x.role === SemanticRole.INTEGER) ||
  374. (x.type === SemanticType.PUNCTUATION && x.role === SemanticRole.COMMA));
  375. })) {
  376. node.role = SemanticRole.INTEGER;
  377. if (content[0] === '0') {
  378. node.addAnnotation('general', 'basenumber');
  379. }
  380. return;
  381. }
  382. if (meaning.every(function (x) {
  383. return ((x.type === SemanticType.NUMBER && x.role === SemanticRole.INTEGER) ||
  384. x.type === SemanticType.PUNCTUATION);
  385. })) {
  386. node.role = SemanticRole.FLOAT;
  387. return;
  388. }
  389. node.role = SemanticRole.OTHERNUMBER;
  390. }
  391. static exprFont_(node) {
  392. if (node.font !== SemanticFont.UNKNOWN) {
  393. return;
  394. }
  395. SemanticProcessor.compSemantics(node, 'font', SemanticFont);
  396. }
  397. static compSemantics(node, field, sem) {
  398. const content = [...node.textContent];
  399. const meaning = content.map((x) => SemanticMap.Meaning.get(x));
  400. const single = meaning.reduce(function (prev, curr) {
  401. if (!prev ||
  402. !curr[field] ||
  403. curr[field] === sem.UNKNOWN ||
  404. curr[field] === prev) {
  405. return prev;
  406. }
  407. if (prev === sem.UNKNOWN) {
  408. return curr[field];
  409. }
  410. return null;
  411. }, sem.UNKNOWN);
  412. if (single) {
  413. node[field] = single;
  414. }
  415. }
  416. static purgeFences_(partition) {
  417. const rel = partition.rel;
  418. const comp = partition.comp;
  419. const newRel = [];
  420. const newComp = [];
  421. while (rel.length > 0) {
  422. const currentRel = rel.shift();
  423. let currentComp = comp.shift();
  424. if (SemanticPred.isElligibleEmbellishedFence(currentRel)) {
  425. newRel.push(currentRel);
  426. newComp.push(currentComp);
  427. continue;
  428. }
  429. SemanticProcessor.fenceToPunct_(currentRel);
  430. currentComp.push(currentRel);
  431. currentComp = currentComp.concat(comp.shift());
  432. comp.unshift(currentComp);
  433. }
  434. newComp.push(comp.shift());
  435. return { rel: newRel, comp: newComp };
  436. }
  437. static rewriteFencedNode_(fenced) {
  438. const ofence = fenced.contentNodes[0];
  439. const cfence = fenced.contentNodes[1];
  440. let rewritten = SemanticProcessor.rewriteFence_(fenced, ofence);
  441. fenced.contentNodes[0] = rewritten.fence;
  442. rewritten = SemanticProcessor.rewriteFence_(rewritten.node, cfence);
  443. fenced.contentNodes[1] = rewritten.fence;
  444. fenced.contentNodes[0].parent = fenced;
  445. fenced.contentNodes[1].parent = fenced;
  446. rewritten.node.parent = null;
  447. return rewritten.node;
  448. }
  449. static rewriteFence_(node, fence) {
  450. if (!fence.embellished) {
  451. return { node: node, fence: fence };
  452. }
  453. const newFence = fence.childNodes[0];
  454. const rewritten = SemanticProcessor.rewriteFence_(node, newFence);
  455. if (SemanticPred.isType(fence, SemanticType.SUPERSCRIPT) ||
  456. SemanticPred.isType(fence, SemanticType.SUBSCRIPT) ||
  457. SemanticPred.isType(fence, SemanticType.TENSOR)) {
  458. if (!SemanticPred.isRole(fence, SemanticRole.SUBSUP)) {
  459. fence.role = node.role;
  460. }
  461. if (newFence !== rewritten.node) {
  462. fence.replaceChild(newFence, rewritten.node);
  463. newFence.parent = node;
  464. }
  465. SemanticProcessor.propagateFencePointer_(fence, newFence);
  466. return { node: fence, fence: rewritten.fence };
  467. }
  468. fence.replaceChild(newFence, rewritten.fence);
  469. if (fence.mathmlTree && fence.mathml.indexOf(fence.mathmlTree) === -1) {
  470. fence.mathml.push(fence.mathmlTree);
  471. }
  472. return { node: rewritten.node, fence: fence };
  473. }
  474. static propagateFencePointer_(oldNode, newNode) {
  475. oldNode.fencePointer = newNode.fencePointer || newNode.id.toString();
  476. oldNode.embellished = null;
  477. }
  478. static classifyByColumns_(table, columns, relation, alternatives = []) {
  479. const relations = [relation].concat(alternatives);
  480. const test1 = (x) => SemanticProcessor.isPureRelation_(x, relations);
  481. const test2 = (x) => SemanticProcessor.isEndRelation_(x, relations) ||
  482. SemanticProcessor.isPureRelation_(x, relations);
  483. const test3 = (x) => SemanticProcessor.isEndRelation_(x, relations, true) ||
  484. SemanticProcessor.isPureRelation_(x, relations);
  485. if ((columns.length === 3 &&
  486. SemanticProcessor.testColumns_(columns, 1, test1)) ||
  487. (columns.length === 2 &&
  488. (SemanticProcessor.testColumns_(columns, 1, test2) ||
  489. SemanticProcessor.testColumns_(columns, 0, test3)))) {
  490. table.role = relation;
  491. return true;
  492. }
  493. return false;
  494. }
  495. static isEndRelation_(node, relations, opt_right) {
  496. const position = opt_right ? node.childNodes.length - 1 : 0;
  497. return (SemanticPred.isType(node, SemanticType.RELSEQ) &&
  498. relations.some((relation) => SemanticPred.isRole(node, relation)) &&
  499. SemanticPred.isType(node.childNodes[position], SemanticType.EMPTY));
  500. }
  501. static isPureRelation_(node, relations) {
  502. return (SemanticPred.isType(node, SemanticType.RELATION) &&
  503. relations.some((relation) => SemanticPred.isRole(node, relation)));
  504. }
  505. static computeColumns_(table) {
  506. const columns = [];
  507. for (let i = 0, row; (row = table.childNodes[i]); i++) {
  508. for (let j = 0, cell; (cell = row.childNodes[j]); j++) {
  509. const column = columns[j];
  510. column ? columns[j].push(cell) : (columns[j] = [cell]);
  511. }
  512. }
  513. return columns;
  514. }
  515. static testColumns_(columns, index, pred) {
  516. const column = columns[index];
  517. return column
  518. ? column.some(function (cell) {
  519. return (cell.childNodes.length && pred(cell.childNodes[0]));
  520. }) &&
  521. column.every(function (cell) {
  522. return (!cell.childNodes.length ||
  523. pred(cell.childNodes[0]));
  524. })
  525. : false;
  526. }
  527. setNodeFactory(factory) {
  528. SemanticProcessor.getInstance().factory_ = factory;
  529. SemanticHeuristics.updateFactory(SemanticProcessor.getInstance().factory_);
  530. }
  531. getNodeFactory() {
  532. return SemanticProcessor.getInstance().factory_;
  533. }
  534. identifierNode(leaf, font, unit) {
  535. if (unit === 'MathML-Unit') {
  536. leaf.type = SemanticType.IDENTIFIER;
  537. leaf.role = SemanticRole.UNIT;
  538. }
  539. else if (!font &&
  540. leaf.textContent.length === 1 &&
  541. (leaf.role === SemanticRole.INTEGER ||
  542. leaf.role === SemanticRole.LATINLETTER ||
  543. leaf.role === SemanticRole.GREEKLETTER) &&
  544. leaf.font === SemanticFont.NORMAL) {
  545. leaf.font = SemanticFont.ITALIC;
  546. return SemanticHeuristics.run('simpleNamedFunction', leaf);
  547. }
  548. if (leaf.type === SemanticType.UNKNOWN) {
  549. leaf.type = SemanticType.IDENTIFIER;
  550. }
  551. SemanticProcessor.exprFont_(leaf);
  552. return SemanticHeuristics.run('simpleNamedFunction', leaf);
  553. }
  554. implicitNode(nodes) {
  555. nodes = SemanticProcessor.getInstance().getMixedNumbers_(nodes);
  556. nodes = SemanticProcessor.getInstance().combineUnits_(nodes);
  557. if (nodes.length === 1) {
  558. return nodes[0];
  559. }
  560. const node = SemanticProcessor.getInstance().implicitNode_(nodes);
  561. return SemanticHeuristics.run('combine_juxtaposition', node);
  562. }
  563. text(leaf, type) {
  564. SemanticProcessor.exprFont_(leaf);
  565. leaf.type = SemanticType.TEXT;
  566. if (type === MMLTAGS.ANNOTATIONXML) {
  567. leaf.role = SemanticRole.ANNOTATION;
  568. return leaf;
  569. }
  570. if (type === MMLTAGS.MS) {
  571. leaf.role = SemanticRole.STRING;
  572. return leaf;
  573. }
  574. if (type === MMLTAGS.MSPACE || leaf.textContent.match(/^\s*$/)) {
  575. leaf.role = SemanticRole.SPACE;
  576. return leaf;
  577. }
  578. if (/\s/.exec(leaf.textContent)) {
  579. leaf.role = SemanticRole.TEXT;
  580. return leaf;
  581. }
  582. leaf.role = SemanticRole.UNKNOWN;
  583. return leaf;
  584. }
  585. row(nodes) {
  586. nodes = nodes.filter(function (x) {
  587. return !SemanticPred.isType(x, SemanticType.EMPTY);
  588. });
  589. if (nodes.length === 0) {
  590. return SemanticProcessor.getInstance().factory_.makeEmptyNode();
  591. }
  592. nodes = SemanticProcessor.getInstance().getFencesInRow_(nodes);
  593. nodes = SemanticProcessor.getInstance().tablesInRow(nodes);
  594. nodes = SemanticProcessor.getInstance().getPunctuationInRow_(nodes);
  595. nodes = SemanticProcessor.getInstance().getTextInRow_(nodes);
  596. nodes = SemanticProcessor.getInstance().getFunctionsInRow_(nodes);
  597. return SemanticProcessor.getInstance().relationsInRow_(nodes);
  598. }
  599. limitNode(mmlTag, children) {
  600. if (!children.length) {
  601. return SemanticProcessor.getInstance().factory_.makeEmptyNode();
  602. }
  603. let center = children[0];
  604. let type = SemanticType.UNKNOWN;
  605. if (!children[1]) {
  606. return center;
  607. }
  608. let result;
  609. SemanticHeuristics.run('op_with_limits', children);
  610. if (SemanticPred.isLimitBase(center)) {
  611. result = SemanticProcessor.MML_TO_LIMIT_[mmlTag];
  612. const length = result.length;
  613. type = result.type;
  614. children = children.slice(0, result.length + 1);
  615. if ((length === 1 && SemanticPred.isAccent(children[1])) ||
  616. (length === 2 &&
  617. SemanticPred.isAccent(children[1]) &&
  618. SemanticPred.isAccent(children[2]))) {
  619. result = SemanticProcessor.MML_TO_BOUNDS_[mmlTag];
  620. return SemanticProcessor.getInstance().accentNode_(center, children, result.type, result.length, result.accent);
  621. }
  622. if (length === 2) {
  623. if (SemanticPred.isAccent(children[1])) {
  624. center = SemanticProcessor.getInstance().accentNode_(center, [center, children[1]], {
  625. MSUBSUP: SemanticType.SUBSCRIPT,
  626. MUNDEROVER: SemanticType.UNDERSCORE
  627. }[mmlTag], 1, true);
  628. return !children[2]
  629. ? center
  630. : SemanticProcessor.getInstance().makeLimitNode_(center, [center, children[2]], null, SemanticType.LIMUPPER);
  631. }
  632. if (children[2] && SemanticPred.isAccent(children[2])) {
  633. center = SemanticProcessor.getInstance().accentNode_(center, [center, children[2]], {
  634. MSUBSUP: SemanticType.SUPERSCRIPT,
  635. MUNDEROVER: SemanticType.OVERSCORE
  636. }[mmlTag], 1, true);
  637. return SemanticProcessor.getInstance().makeLimitNode_(center, [center, children[1]], null, SemanticType.LIMLOWER);
  638. }
  639. if (!children[length]) {
  640. type = SemanticType.LIMLOWER;
  641. }
  642. }
  643. return SemanticProcessor.getInstance().makeLimitNode_(center, children, null, type);
  644. }
  645. result = SemanticProcessor.MML_TO_BOUNDS_[mmlTag];
  646. return SemanticProcessor.getInstance().accentNode_(center, children, result.type, result.length, result.accent);
  647. }
  648. tablesInRow(nodes) {
  649. let partition = SemanticUtil.partitionNodes(nodes, SemanticPred.tableIsMatrixOrVector);
  650. let result = [];
  651. for (let i = 0, matrix; (matrix = partition.rel[i]); i++) {
  652. result = result.concat(partition.comp.shift());
  653. result.push(SemanticProcessor.tableToMatrixOrVector_(matrix));
  654. }
  655. result = result.concat(partition.comp.shift());
  656. partition = SemanticUtil.partitionNodes(result, SemanticPred.isTableOrMultiline);
  657. result = [];
  658. for (let i = 0, table; (table = partition.rel[i]); i++) {
  659. const prevNodes = partition.comp.shift();
  660. if (SemanticPred.tableIsCases(table, prevNodes)) {
  661. SemanticProcessor.tableToCases_(table, prevNodes.pop());
  662. }
  663. result = result.concat(prevNodes);
  664. result.push(table);
  665. }
  666. return result.concat(partition.comp.shift());
  667. }
  668. mfenced(open, close, sepValue, children) {
  669. if (sepValue && children.length > 0) {
  670. const separators = SemanticProcessor.nextSeparatorFunction_(sepValue);
  671. const newChildren = [children.shift()];
  672. children.forEach((child) => {
  673. newChildren.push(SemanticProcessor.getInstance().factory_.makeContentNode(separators()));
  674. newChildren.push(child);
  675. });
  676. children = newChildren;
  677. }
  678. if (open && close) {
  679. return SemanticProcessor.getInstance().horizontalFencedNode_(SemanticProcessor.getInstance().factory_.makeContentNode(open), SemanticProcessor.getInstance().factory_.makeContentNode(close), children);
  680. }
  681. if (open) {
  682. children.unshift(SemanticProcessor.getInstance().factory_.makeContentNode(open));
  683. }
  684. if (close) {
  685. children.push(SemanticProcessor.getInstance().factory_.makeContentNode(close));
  686. }
  687. return SemanticProcessor.getInstance().row(children);
  688. }
  689. fractionLikeNode(denom, enume, linethickness, bevelled) {
  690. let node;
  691. if (!bevelled && SemanticUtil.isZeroLength(linethickness)) {
  692. const child0 = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.LINE, [denom], []);
  693. const child1 = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.LINE, [enume], []);
  694. node = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.MULTILINE, [child0, child1], []);
  695. SemanticProcessor.binomialForm_(node);
  696. SemanticProcessor.classifyMultiline(node);
  697. return node;
  698. }
  699. else {
  700. node = SemanticProcessor.getInstance().fractionNode_(denom, enume);
  701. if (bevelled) {
  702. node.addAnnotation('general', 'bevelled');
  703. }
  704. return node;
  705. }
  706. }
  707. tensor(base, lsub, lsup, rsub, rsup) {
  708. const newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.TENSOR, [
  709. base,
  710. SemanticProcessor.getInstance().scriptNode_(lsub, SemanticRole.LEFTSUB),
  711. SemanticProcessor.getInstance().scriptNode_(lsup, SemanticRole.LEFTSUPER),
  712. SemanticProcessor.getInstance().scriptNode_(rsub, SemanticRole.RIGHTSUB),
  713. SemanticProcessor.getInstance().scriptNode_(rsup, SemanticRole.RIGHTSUPER)
  714. ], []);
  715. newNode.role = base.role;
  716. newNode.embellished = SemanticPred.isEmbellished(base);
  717. return newNode;
  718. }
  719. pseudoTensor(base, sub, sup) {
  720. const isEmpty = (x) => !SemanticPred.isType(x, SemanticType.EMPTY);
  721. const nonEmptySub = sub.filter(isEmpty).length;
  722. const nonEmptySup = sup.filter(isEmpty).length;
  723. if (!nonEmptySub && !nonEmptySup) {
  724. return base;
  725. }
  726. const mmlTag = nonEmptySub
  727. ? nonEmptySup
  728. ? MMLTAGS.MSUBSUP
  729. : MMLTAGS.MSUB
  730. : MMLTAGS.MSUP;
  731. const mmlchild = [base];
  732. if (nonEmptySub) {
  733. mmlchild.push(SemanticProcessor.getInstance().scriptNode_(sub, SemanticRole.RIGHTSUB, true));
  734. }
  735. if (nonEmptySup) {
  736. mmlchild.push(SemanticProcessor.getInstance().scriptNode_(sup, SemanticRole.RIGHTSUPER, true));
  737. }
  738. return SemanticProcessor.getInstance().limitNode(mmlTag, mmlchild);
  739. }
  740. font(font) {
  741. const mathjaxFont = SemanticProcessor.MATHJAX_FONTS[font];
  742. return mathjaxFont ? mathjaxFont : font;
  743. }
  744. proof(node, semantics, parse) {
  745. if (!semantics['inference'] && !semantics['axiom']) {
  746. console.log('Noise');
  747. }
  748. if (semantics['axiom']) {
  749. const cleaned = SemanticProcessor.getInstance().cleanInference(node.childNodes);
  750. const axiom = cleaned.length
  751. ? SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.INFERENCE, parse(cleaned), [])
  752. : SemanticProcessor.getInstance().factory_.makeEmptyNode();
  753. axiom.role = SemanticRole.AXIOM;
  754. axiom.mathmlTree = node;
  755. return axiom;
  756. }
  757. const inference = SemanticProcessor.getInstance().inference(node, semantics, parse);
  758. if (semantics['proof']) {
  759. inference.role = SemanticRole.PROOF;
  760. inference.childNodes[0].role = SemanticRole.FINAL;
  761. }
  762. return inference;
  763. }
  764. inference(node, semantics, parse) {
  765. if (semantics['inferenceRule']) {
  766. const formulas = SemanticProcessor.getInstance().getFormulas(node, [], parse);
  767. const inference = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.INFERENCE, [formulas.conclusion, formulas.premises], []);
  768. return inference;
  769. }
  770. const label = semantics['labelledRule'];
  771. const children = DomUtil.toArray(node.childNodes);
  772. const content = [];
  773. if (label === 'left' || label === 'both') {
  774. content.push(SemanticProcessor.getInstance().getLabel(node, children, parse, SemanticRole.LEFT));
  775. }
  776. if (label === 'right' || label === 'both') {
  777. content.push(SemanticProcessor.getInstance().getLabel(node, children, parse, SemanticRole.RIGHT));
  778. }
  779. const formulas = SemanticProcessor.getInstance().getFormulas(node, children, parse);
  780. const inference = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.INFERENCE, [formulas.conclusion, formulas.premises], content);
  781. inference.mathmlTree = node;
  782. return inference;
  783. }
  784. getLabel(_node, children, parse, side) {
  785. const label = SemanticProcessor.getInstance().findNestedRow(children, 'prooflabel', side);
  786. const sem = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.RULELABEL, parse(DomUtil.toArray(label.childNodes)), []);
  787. sem.role = side;
  788. sem.mathmlTree = label;
  789. return sem;
  790. }
  791. getFormulas(node, children, parse) {
  792. const inf = children.length
  793. ? SemanticProcessor.getInstance().findNestedRow(children, 'inferenceRule')
  794. : node;
  795. const up = SemanticProcessor.getSemantics(inf)['inferenceRule'] === 'up';
  796. const premRow = up ? inf.childNodes[1] : inf.childNodes[0];
  797. const concRow = up ? inf.childNodes[0] : inf.childNodes[1];
  798. const premTable = premRow.childNodes[0].childNodes[0];
  799. const topRow = DomUtil.toArray(premTable.childNodes[0].childNodes);
  800. const premNodes = [];
  801. let i = 1;
  802. for (const cell of topRow) {
  803. if (i % 2) {
  804. premNodes.push(cell.childNodes[0]);
  805. }
  806. i++;
  807. }
  808. const premises = parse(premNodes);
  809. const conclusion = parse(DomUtil.toArray(concRow.childNodes[0].childNodes))[0];
  810. const prem = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.PREMISES, premises, []);
  811. prem.mathmlTree = premTable;
  812. const conc = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.CONCLUSION, [conclusion], []);
  813. conc.mathmlTree = concRow.childNodes[0].childNodes[0];
  814. return { conclusion: conc, premises: prem };
  815. }
  816. findNestedRow(nodes, semantic, opt_value) {
  817. return SemanticProcessor.getInstance().findNestedRow_(nodes, semantic, 0, opt_value);
  818. }
  819. cleanInference(nodes) {
  820. return DomUtil.toArray(nodes).filter(function (x) {
  821. return DomUtil.tagName(x) !== 'MSPACE';
  822. });
  823. }
  824. operatorNode(node) {
  825. if (node.type === SemanticType.UNKNOWN) {
  826. node.type = SemanticType.OPERATOR;
  827. }
  828. return SemanticHeuristics.run('multioperator', node);
  829. }
  830. constructor() {
  831. this.funcAppls = {};
  832. this.splitRoles = new Map([
  833. [SemanticRole.SUBTRACTION, SemanticRole.NEGATIVE],
  834. [SemanticRole.ADDITION, SemanticRole.POSITIVE]
  835. ]);
  836. this.splitOps = ['−', '-', '‐', '‑', '+'];
  837. this.factory_ = new SemanticNodeFactory();
  838. SemanticHeuristics.updateFactory(this.factory_);
  839. }
  840. implicitNode_(nodes) {
  841. const operators = SemanticProcessor.getInstance().factory_.makeMultipleContentNodes(nodes.length - 1, NamedSymbol.invisibleTimes);
  842. SemanticProcessor.matchSpaces_(nodes, operators);
  843. const newNode = SemanticProcessor.getInstance().infixNode_(nodes, operators[0]);
  844. newNode.role = SemanticRole.IMPLICIT;
  845. operators.forEach(function (op) {
  846. op.parent = newNode;
  847. });
  848. newNode.contentNodes = operators;
  849. return newNode;
  850. }
  851. infixNode_(children, opNode) {
  852. const node = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.INFIXOP, children, [opNode], SemanticUtil.getEmbellishedInner(opNode).textContent);
  853. node.role = opNode.role;
  854. return SemanticHeuristics.run('propagateSimpleFunction', node);
  855. }
  856. explicitMixed_(nodes) {
  857. const partition = SemanticUtil.partitionNodes(nodes, function (x) {
  858. return x.textContent === NamedSymbol.invisiblePlus;
  859. });
  860. if (!partition.rel.length) {
  861. return nodes;
  862. }
  863. let result = [];
  864. for (let i = 0, rel; (rel = partition.rel[i]); i++) {
  865. const prev = partition.comp[i];
  866. const next = partition.comp[i + 1];
  867. const last = prev.length - 1;
  868. if (prev[last] &&
  869. next[0] &&
  870. SemanticPred.isType(prev[last], SemanticType.NUMBER) &&
  871. !SemanticPred.isRole(prev[last], SemanticRole.MIXED) &&
  872. SemanticPred.isType(next[0], SemanticType.FRACTION)) {
  873. const newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.NUMBER, [prev[last], next[0]], []);
  874. newNode.role = SemanticRole.MIXED;
  875. result = result.concat(prev.slice(0, last));
  876. result.push(newNode);
  877. next.shift();
  878. }
  879. else {
  880. result = result.concat(prev);
  881. result.push(rel);
  882. }
  883. }
  884. return result.concat(partition.comp[partition.comp.length - 1]);
  885. }
  886. concatNode_(inner, nodeList, type) {
  887. if (nodeList.length === 0) {
  888. return inner;
  889. }
  890. const content = nodeList
  891. .map(function (x) {
  892. return SemanticUtil.getEmbellishedInner(x).textContent;
  893. })
  894. .join(' ');
  895. const newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(type, [inner], nodeList, content);
  896. if (nodeList.length > 1) {
  897. newNode.role = SemanticRole.MULTIOP;
  898. }
  899. return newNode;
  900. }
  901. prefixNode_(node, prefixes) {
  902. const newPrefixes = this.splitSingles(prefixes);
  903. let newNode = node;
  904. while (newPrefixes.length > 0) {
  905. const op = newPrefixes.pop();
  906. newNode = SemanticProcessor.getInstance().concatNode_(newNode, op, SemanticType.PREFIXOP);
  907. if (op.length === 1 && this.splitOps.indexOf(op[0].textContent) !== -1) {
  908. newNode.role = this.splitRoles.get(op[0].role);
  909. }
  910. }
  911. return newNode;
  912. }
  913. splitSingles(prefixes) {
  914. let lastOp = 0;
  915. const result = [];
  916. let i = 0;
  917. while (i < prefixes.length) {
  918. const op = prefixes[i];
  919. if (this.splitRoles.has(op.role) &&
  920. (!prefixes[i - 1] || prefixes[i - 1].role !== op.role) &&
  921. (!prefixes[i + 1] || prefixes[i + 1].role !== op.role) &&
  922. this.splitOps.indexOf(op.textContent) !== -1) {
  923. result.push(prefixes.slice(lastOp, i));
  924. result.push(prefixes.slice(i, i + 1));
  925. lastOp = i + 1;
  926. }
  927. i++;
  928. }
  929. if (lastOp < i) {
  930. result.push(prefixes.slice(lastOp, i));
  931. }
  932. return result;
  933. }
  934. postfixNode_(node, postfixes) {
  935. if (!postfixes.length) {
  936. return node;
  937. }
  938. return SemanticProcessor.getInstance().concatNode_(node, postfixes, SemanticType.POSTFIXOP);
  939. }
  940. combineUnits_(nodes) {
  941. const partition = SemanticUtil.partitionNodes(nodes, function (x) {
  942. return !SemanticPred.isRole(x, SemanticRole.UNIT);
  943. });
  944. if (nodes.length === partition.rel.length) {
  945. return partition.rel;
  946. }
  947. const result = [];
  948. let rel;
  949. let last;
  950. do {
  951. const comp = partition.comp.shift();
  952. rel = partition.rel.shift();
  953. let unitNode = null;
  954. last = result.pop();
  955. if (last) {
  956. if (!comp.length || !SemanticPred.isUnitCounter(last)) {
  957. result.push(last);
  958. }
  959. else {
  960. comp.unshift(last);
  961. }
  962. }
  963. if (comp.length === 1) {
  964. unitNode = comp.pop();
  965. }
  966. if (comp.length > 1) {
  967. unitNode = SemanticProcessor.getInstance().implicitNode_(comp);
  968. unitNode.role = SemanticRole.UNIT;
  969. }
  970. if (unitNode) {
  971. result.push(unitNode);
  972. }
  973. if (rel) {
  974. result.push(rel);
  975. }
  976. } while (rel);
  977. return result;
  978. }
  979. getMixedNumbers_(nodes) {
  980. const partition = SemanticUtil.partitionNodes(nodes, function (x) {
  981. return (SemanticPred.isType(x, SemanticType.FRACTION) &&
  982. SemanticPred.isRole(x, SemanticRole.VULGAR));
  983. });
  984. if (!partition.rel.length) {
  985. return nodes;
  986. }
  987. let result = [];
  988. for (let i = 0, rel; (rel = partition.rel[i]); i++) {
  989. const comp = partition.comp[i];
  990. const last = comp.length - 1;
  991. if (comp[last] &&
  992. SemanticPred.isType(comp[last], SemanticType.NUMBER) &&
  993. (SemanticPred.isRole(comp[last], SemanticRole.INTEGER) ||
  994. SemanticPred.isRole(comp[last], SemanticRole.FLOAT))) {
  995. const newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.NUMBER, [comp[last], rel], []);
  996. newNode.role = SemanticRole.MIXED;
  997. result = result.concat(comp.slice(0, last));
  998. result.push(newNode);
  999. }
  1000. else {
  1001. result = result.concat(comp);
  1002. result.push(rel);
  1003. }
  1004. }
  1005. return result.concat(partition.comp[partition.comp.length - 1]);
  1006. }
  1007. getTextInRow_(nodes) {
  1008. if (nodes.length === 0) {
  1009. return nodes;
  1010. }
  1011. if (nodes.length === 1) {
  1012. if (nodes[0].type === SemanticType.TEXT &&
  1013. nodes[0].role === SemanticRole.UNKNOWN) {
  1014. nodes[0].role = SemanticRole.ANNOTATION;
  1015. }
  1016. return nodes;
  1017. }
  1018. const { rel: rel, comp: comp } = SemanticUtil.partitionNodes(nodes, (x) => SemanticPred.isType(x, SemanticType.TEXT));
  1019. if (rel.length === 0) {
  1020. return nodes;
  1021. }
  1022. const result = [];
  1023. let prevComp = comp.shift();
  1024. while (rel.length > 0) {
  1025. let currentRel = rel.shift();
  1026. let nextComp = comp.shift();
  1027. const text = [];
  1028. while (!nextComp.length &&
  1029. rel.length &&
  1030. currentRel.role !== SemanticRole.SPACE &&
  1031. rel[0].role !== SemanticRole.SPACE) {
  1032. text.push(currentRel);
  1033. currentRel = rel.shift();
  1034. nextComp = comp.shift();
  1035. }
  1036. if (text.length) {
  1037. if (prevComp.length) {
  1038. result.push(SemanticProcessor.getInstance().row(prevComp));
  1039. }
  1040. text.push(currentRel);
  1041. const dummy = SemanticProcessor.getInstance().dummyNode_(text);
  1042. result.push(dummy);
  1043. prevComp = nextComp;
  1044. continue;
  1045. }
  1046. if (currentRel.role !== SemanticRole.UNKNOWN) {
  1047. if (prevComp.length) {
  1048. result.push(SemanticProcessor.getInstance().row(prevComp));
  1049. }
  1050. result.push(currentRel);
  1051. prevComp = nextComp;
  1052. continue;
  1053. }
  1054. const meaning = SemanticMap.Meaning.get(currentRel.textContent);
  1055. if (meaning.type === SemanticType.PUNCTUATION) {
  1056. currentRel.role = meaning.role;
  1057. currentRel.font = meaning.font;
  1058. if (prevComp.length) {
  1059. result.push(SemanticProcessor.getInstance().row(prevComp));
  1060. }
  1061. result.push(currentRel);
  1062. prevComp = nextComp;
  1063. continue;
  1064. }
  1065. if (meaning.type !== SemanticType.UNKNOWN) {
  1066. currentRel.type = meaning.type;
  1067. currentRel.role = meaning.role;
  1068. currentRel.font = meaning.font;
  1069. currentRel.addAnnotation('general', 'text');
  1070. prevComp.push(currentRel);
  1071. prevComp = prevComp.concat(nextComp);
  1072. continue;
  1073. }
  1074. SemanticProcessor.meaningFromContent(currentRel, (n, c, m) => {
  1075. if (n.role !== SemanticRole.UNKNOWN) {
  1076. return;
  1077. }
  1078. SemanticProcessor.numberRole_(n, c, m);
  1079. if (n.role !== SemanticRole.OTHERNUMBER) {
  1080. n.type = SemanticType.NUMBER;
  1081. return;
  1082. }
  1083. if (m.some((x) => x.type !== SemanticType.NUMBER &&
  1084. x.type !== SemanticType.IDENTIFIER)) {
  1085. n.type = SemanticType.TEXT;
  1086. n.role = SemanticRole.ANNOTATION;
  1087. return;
  1088. }
  1089. n.role = SemanticRole.UNKNOWN;
  1090. });
  1091. if (currentRel.type === SemanticType.TEXT &&
  1092. currentRel.role !== SemanticRole.UNKNOWN) {
  1093. if (prevComp.length) {
  1094. result.push(SemanticProcessor.getInstance().row(prevComp));
  1095. }
  1096. result.push(currentRel);
  1097. prevComp = nextComp;
  1098. continue;
  1099. }
  1100. if (currentRel.role === SemanticRole.UNKNOWN) {
  1101. if (rel.length || nextComp.length) {
  1102. if (nextComp.length && nextComp[0].type === SemanticType.FENCED) {
  1103. currentRel.type = SemanticType.FUNCTION;
  1104. currentRel.role = SemanticRole.PREFIXFUNC;
  1105. }
  1106. else {
  1107. currentRel.role = SemanticRole.TEXT;
  1108. }
  1109. }
  1110. else {
  1111. currentRel.type = SemanticType.IDENTIFIER;
  1112. currentRel.role = SemanticRole.UNIT;
  1113. }
  1114. }
  1115. prevComp.push(currentRel);
  1116. prevComp = prevComp.concat(nextComp);
  1117. }
  1118. if (prevComp.length > 0) {
  1119. result.push(SemanticProcessor.getInstance().row(prevComp));
  1120. }
  1121. return result.length > 1
  1122. ? [SemanticProcessor.getInstance().dummyNode_(result)]
  1123. : result;
  1124. }
  1125. relationsInRow_(nodes) {
  1126. const partition = SemanticUtil.partitionNodes(nodes, SemanticPred.isRelation);
  1127. const firstRel = partition.rel[0];
  1128. if (!firstRel) {
  1129. return SemanticProcessor.getInstance().operationsInRow_(nodes);
  1130. }
  1131. if (nodes.length === 1) {
  1132. return nodes[0];
  1133. }
  1134. const children = partition.comp.map(SemanticProcessor.getInstance().operationsInRow_);
  1135. let node;
  1136. if (partition.rel.some(function (x) {
  1137. return !x.equals(firstRel);
  1138. })) {
  1139. node = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.MULTIREL, children, partition.rel);
  1140. if (partition.rel.every(function (x) {
  1141. return x.role === firstRel.role;
  1142. })) {
  1143. node.role = firstRel.role;
  1144. }
  1145. return node;
  1146. }
  1147. node = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.RELSEQ, children, partition.rel, SemanticUtil.getEmbellishedInner(firstRel).textContent);
  1148. node.role = firstRel.role;
  1149. return node;
  1150. }
  1151. operationsInRow_(nodes) {
  1152. if (nodes.length === 0) {
  1153. return SemanticProcessor.getInstance().factory_.makeEmptyNode();
  1154. }
  1155. nodes = SemanticProcessor.getInstance().explicitMixed_(nodes);
  1156. if (nodes.length === 1) {
  1157. return nodes[0];
  1158. }
  1159. const prefix = [];
  1160. while (nodes.length > 0 && SemanticPred.isOperator(nodes[0])) {
  1161. prefix.push(nodes.shift());
  1162. }
  1163. if (nodes.length === 0) {
  1164. return SemanticProcessor.getInstance().prefixNode_(prefix.pop(), prefix);
  1165. }
  1166. if (nodes.length === 1) {
  1167. return SemanticProcessor.getInstance().prefixNode_(nodes[0], prefix);
  1168. }
  1169. nodes = SemanticHeuristics.run('convert_juxtaposition', nodes);
  1170. const split = SemanticUtil.sliceNodes(nodes, SemanticPred.isOperator);
  1171. const node = SemanticProcessor.getInstance().wrapFactor(prefix, split);
  1172. return SemanticProcessor.getInstance().addFactor(node, split);
  1173. }
  1174. wrapPostfix(split) {
  1175. var _a;
  1176. if (((_a = split.div) === null || _a === void 0 ? void 0 : _a.role) === SemanticRole.POSTFIXOP) {
  1177. if (!split.tail.length || split.tail[0].type === SemanticType.OPERATOR) {
  1178. split.head = [
  1179. SemanticProcessor.getInstance().postfixNode_(SemanticProcessor.getInstance().implicitNode(split.head), [split.div])
  1180. ];
  1181. split.div = split.tail.shift();
  1182. SemanticProcessor.getInstance().wrapPostfix(split);
  1183. }
  1184. else {
  1185. split.div.role = SemanticRole.DIVISION;
  1186. }
  1187. }
  1188. }
  1189. wrapFactor(prefix, split) {
  1190. SemanticProcessor.getInstance().wrapPostfix(split);
  1191. return SemanticProcessor.getInstance().prefixNode_(SemanticProcessor.getInstance().implicitNode(split.head), prefix);
  1192. }
  1193. addFactor(node, split) {
  1194. if (!split.div) {
  1195. if (SemanticPred.isUnitProduct(node)) {
  1196. node.role = SemanticRole.UNIT;
  1197. }
  1198. return node;
  1199. }
  1200. return SemanticProcessor.getInstance().operationsTree_(split.tail, node, split.div);
  1201. }
  1202. operationsTree_(nodes, root, lastop, prefix = []) {
  1203. if (nodes.length === 0) {
  1204. prefix.unshift(lastop);
  1205. if (root.type === SemanticType.INFIXOP) {
  1206. const node = SemanticProcessor.getInstance().postfixNode_(root.childNodes.pop(), prefix);
  1207. root.appendChild(node);
  1208. return root;
  1209. }
  1210. return SemanticProcessor.getInstance().postfixNode_(root, prefix);
  1211. }
  1212. const split = SemanticUtil.sliceNodes(nodes, SemanticPred.isOperator);
  1213. if (split.head.length === 0) {
  1214. prefix.push(split.div);
  1215. return SemanticProcessor.getInstance().operationsTree_(split.tail, root, lastop, prefix);
  1216. }
  1217. const node = SemanticProcessor.getInstance().wrapFactor(prefix, split);
  1218. const newNode = SemanticProcessor.getInstance().appendOperand_(root, lastop, node);
  1219. return SemanticProcessor.getInstance().addFactor(newNode, split);
  1220. }
  1221. appendOperand_(root, op, node) {
  1222. if (root.type !== SemanticType.INFIXOP) {
  1223. return SemanticProcessor.getInstance().infixNode_([root, node], op);
  1224. }
  1225. const division = SemanticProcessor.getInstance().appendDivisionOp_(root, op, node);
  1226. if (division) {
  1227. return division;
  1228. }
  1229. if (SemanticProcessor.getInstance().appendExistingOperator_(root, op, node)) {
  1230. return root;
  1231. }
  1232. return op.role === SemanticRole.MULTIPLICATION
  1233. ? SemanticProcessor.getInstance().appendMultiplicativeOp_(root, op, node)
  1234. : SemanticProcessor.getInstance().appendAdditiveOp_(root, op, node);
  1235. }
  1236. appendDivisionOp_(root, op, node) {
  1237. if (op.role === SemanticRole.DIVISION) {
  1238. if (SemanticPred.isImplicit(root)) {
  1239. return SemanticProcessor.getInstance().infixNode_([root, node], op);
  1240. }
  1241. return SemanticProcessor.getInstance().appendLastOperand_(root, op, node);
  1242. }
  1243. return root.role === SemanticRole.DIVISION
  1244. ? SemanticProcessor.getInstance().infixNode_([root, node], op)
  1245. : null;
  1246. }
  1247. appendLastOperand_(root, op, node) {
  1248. let lastRoot = root;
  1249. let lastChild = root.childNodes[root.childNodes.length - 1];
  1250. while (lastChild &&
  1251. lastChild.type === SemanticType.INFIXOP &&
  1252. !SemanticPred.isImplicit(lastChild)) {
  1253. lastRoot = lastChild;
  1254. lastChild = lastRoot.childNodes[root.childNodes.length - 1];
  1255. }
  1256. const newNode = SemanticProcessor.getInstance().infixNode_([lastRoot.childNodes.pop(), node], op);
  1257. lastRoot.appendChild(newNode);
  1258. return root;
  1259. }
  1260. appendMultiplicativeOp_(root, op, node) {
  1261. if (SemanticPred.isImplicit(root)) {
  1262. return SemanticProcessor.getInstance().infixNode_([root, node], op);
  1263. }
  1264. let lastRoot = root;
  1265. let lastChild = root.childNodes[root.childNodes.length - 1];
  1266. while (lastChild &&
  1267. lastChild.type === SemanticType.INFIXOP &&
  1268. !SemanticPred.isImplicit(lastChild)) {
  1269. lastRoot = lastChild;
  1270. lastChild = lastRoot.childNodes[root.childNodes.length - 1];
  1271. }
  1272. const newNode = SemanticProcessor.getInstance().infixNode_([lastRoot.childNodes.pop(), node], op);
  1273. lastRoot.appendChild(newNode);
  1274. return root;
  1275. }
  1276. appendAdditiveOp_(root, op, node) {
  1277. return SemanticProcessor.getInstance().infixNode_([root, node], op);
  1278. }
  1279. appendExistingOperator_(root, op, node) {
  1280. if (!root ||
  1281. root.type !== SemanticType.INFIXOP ||
  1282. SemanticPred.isImplicit(root)) {
  1283. return false;
  1284. }
  1285. if (root.contentNodes[0].equals(op)) {
  1286. root.appendContentNode(op);
  1287. root.appendChild(node);
  1288. return true;
  1289. }
  1290. return SemanticProcessor.getInstance().appendExistingOperator_(root.childNodes[root.childNodes.length - 1], op, node);
  1291. }
  1292. getFencesInRow_(nodes) {
  1293. let partition = SemanticUtil.partitionNodes(nodes, SemanticPred.isFence);
  1294. partition = SemanticProcessor.purgeFences_(partition);
  1295. const felem = partition.comp.shift();
  1296. return SemanticProcessor.getInstance().fences_(partition.rel, partition.comp, [], [felem]);
  1297. }
  1298. fences_(fences, content, openStack, contentStack) {
  1299. if (fences.length === 0 && openStack.length === 0) {
  1300. return contentStack[0];
  1301. }
  1302. const interval = SemanticHeuristics.run('bracketed_interval', [fences[0], fences[1], ...(content[0] || [])], () => null);
  1303. if (interval) {
  1304. fences.shift();
  1305. fences.shift();
  1306. content.shift();
  1307. const stack = contentStack.pop() || [];
  1308. contentStack.push([...stack, interval, ...content.shift()]);
  1309. return SemanticProcessor.getInstance().fences_(fences, content, openStack, contentStack);
  1310. }
  1311. const openPred = (x) => SemanticPred.isRole(x, SemanticRole.OPEN);
  1312. if (fences.length === 0) {
  1313. const result = contentStack.shift();
  1314. while (openStack.length > 0) {
  1315. if (openPred(openStack[0])) {
  1316. const firstOpen = openStack.shift();
  1317. SemanticProcessor.fenceToPunct_(firstOpen);
  1318. result.push(firstOpen);
  1319. }
  1320. else {
  1321. const split = SemanticUtil.sliceNodes(openStack, openPred);
  1322. const cutLength = split.head.length - 1;
  1323. const innerNodes = SemanticProcessor.getInstance().neutralFences_(split.head, contentStack.slice(0, cutLength));
  1324. contentStack = contentStack.slice(cutLength);
  1325. result.push(...innerNodes);
  1326. if (split.div) {
  1327. split.tail.unshift(split.div);
  1328. }
  1329. openStack = split.tail;
  1330. }
  1331. result.push(...contentStack.shift());
  1332. }
  1333. return result;
  1334. }
  1335. const lastOpen = openStack[openStack.length - 1];
  1336. const firstRole = fences[0].role;
  1337. if (firstRole === SemanticRole.OPEN ||
  1338. (SemanticPred.isNeutralFence(fences[0]) &&
  1339. !(lastOpen && SemanticPred.compareNeutralFences(fences[0], lastOpen)))) {
  1340. openStack.push(fences.shift());
  1341. const cont = content.shift();
  1342. if (cont) {
  1343. contentStack.push(cont);
  1344. }
  1345. return SemanticProcessor.getInstance().fences_(fences, content, openStack, contentStack);
  1346. }
  1347. if (lastOpen &&
  1348. firstRole === SemanticRole.CLOSE &&
  1349. lastOpen.role === SemanticRole.OPEN) {
  1350. const fenced = SemanticProcessor.getInstance().horizontalFencedNode_(openStack.pop(), fences.shift(), contentStack.pop());
  1351. contentStack.push(contentStack.pop().concat([fenced], content.shift()));
  1352. return SemanticProcessor.getInstance().fences_(fences, content, openStack, contentStack);
  1353. }
  1354. if (lastOpen &&
  1355. SemanticPred.compareNeutralFences(fences[0], lastOpen)) {
  1356. if (!SemanticPred.elligibleLeftNeutral(lastOpen) ||
  1357. !SemanticPred.elligibleRightNeutral(fences[0])) {
  1358. openStack.push(fences.shift());
  1359. const cont = content.shift();
  1360. if (cont) {
  1361. contentStack.push(cont);
  1362. }
  1363. return SemanticProcessor.getInstance().fences_(fences, content, openStack, contentStack);
  1364. }
  1365. const fenced = SemanticProcessor.getInstance().horizontalFencedNode_(openStack.pop(), fences.shift(), contentStack.pop());
  1366. contentStack.push(contentStack.pop().concat([fenced], content.shift()));
  1367. return SemanticProcessor.getInstance().fences_(fences, content, openStack, contentStack);
  1368. }
  1369. if (lastOpen &&
  1370. firstRole === SemanticRole.CLOSE &&
  1371. SemanticPred.isNeutralFence(lastOpen) &&
  1372. openStack.some(openPred)) {
  1373. const split = SemanticUtil.sliceNodes(openStack, openPred, true);
  1374. const rightContent = contentStack.pop();
  1375. const cutLength = contentStack.length - split.tail.length + 1;
  1376. const innerNodes = SemanticProcessor.getInstance().neutralFences_(split.tail, contentStack.slice(cutLength));
  1377. contentStack = contentStack.slice(0, cutLength);
  1378. const fenced = SemanticProcessor.getInstance().horizontalFencedNode_(split.div, fences.shift(), contentStack.pop().concat(innerNodes, rightContent));
  1379. contentStack.push(contentStack.pop().concat([fenced], content.shift()));
  1380. return SemanticProcessor.getInstance().fences_(fences, content, split.head, contentStack);
  1381. }
  1382. const fenced = fences.shift();
  1383. SemanticProcessor.fenceToPunct_(fenced);
  1384. contentStack.push(contentStack.pop().concat([fenced], content.shift()));
  1385. return SemanticProcessor.getInstance().fences_(fences, content, openStack, contentStack);
  1386. }
  1387. neutralFences_(fences, content) {
  1388. if (fences.length === 0) {
  1389. return fences;
  1390. }
  1391. if (fences.length === 1) {
  1392. SemanticProcessor.fenceToPunct_(fences[0]);
  1393. return fences;
  1394. }
  1395. const firstFence = fences.shift();
  1396. if (!SemanticPred.elligibleLeftNeutral(firstFence)) {
  1397. SemanticProcessor.fenceToPunct_(firstFence);
  1398. const restContent = content.shift();
  1399. restContent.unshift(firstFence);
  1400. return restContent.concat(SemanticProcessor.getInstance().neutralFences_(fences, content));
  1401. }
  1402. const split = SemanticUtil.sliceNodes(fences, function (x) {
  1403. return SemanticPred.compareNeutralFences(x, firstFence);
  1404. });
  1405. if (!split.div) {
  1406. SemanticProcessor.fenceToPunct_(firstFence);
  1407. const restContent = content.shift();
  1408. restContent.unshift(firstFence);
  1409. return restContent.concat(SemanticProcessor.getInstance().neutralFences_(fences, content));
  1410. }
  1411. if (!SemanticPred.elligibleRightNeutral(split.div)) {
  1412. SemanticProcessor.fenceToPunct_(split.div);
  1413. fences.unshift(firstFence);
  1414. return SemanticProcessor.getInstance().neutralFences_(fences, content);
  1415. }
  1416. const newContent = SemanticProcessor.getInstance().combineFencedContent_(firstFence, split.div, split.head, content);
  1417. if (split.tail.length > 0) {
  1418. const leftContent = newContent.shift();
  1419. const result = SemanticProcessor.getInstance().neutralFences_(split.tail, newContent);
  1420. return leftContent.concat(result);
  1421. }
  1422. return newContent[0];
  1423. }
  1424. combineFencedContent_(leftFence, rightFence, midFences, content) {
  1425. if (midFences.length === 0) {
  1426. const fenced = SemanticProcessor.getInstance().horizontalFencedNode_(leftFence, rightFence, content.shift());
  1427. if (content.length > 0) {
  1428. content[0].unshift(fenced);
  1429. }
  1430. else {
  1431. content = [[fenced]];
  1432. }
  1433. return content;
  1434. }
  1435. const leftContent = content.shift();
  1436. const cutLength = midFences.length - 1;
  1437. const midContent = content.slice(0, cutLength);
  1438. content = content.slice(cutLength);
  1439. const rightContent = content.shift();
  1440. const innerNodes = SemanticProcessor.getInstance().neutralFences_(midFences, midContent);
  1441. leftContent.push(...innerNodes);
  1442. leftContent.push(...rightContent);
  1443. const fenced = SemanticProcessor.getInstance().horizontalFencedNode_(leftFence, rightFence, leftContent);
  1444. if (content.length > 0) {
  1445. content[0].unshift(fenced);
  1446. }
  1447. else {
  1448. content = [[fenced]];
  1449. }
  1450. return content;
  1451. }
  1452. horizontalFencedNode_(ofence, cfence, content) {
  1453. const childNode = SemanticProcessor.getInstance().row(content);
  1454. let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.FENCED, [childNode], [ofence, cfence]);
  1455. if (ofence.role === SemanticRole.OPEN) {
  1456. SemanticProcessor.getInstance().classifyHorizontalFence_(newNode);
  1457. newNode = SemanticHeuristics.run('propagateComposedFunction', newNode);
  1458. }
  1459. else {
  1460. newNode.role = ofence.role;
  1461. }
  1462. newNode = SemanticHeuristics.run('detect_cycle', newNode);
  1463. return SemanticProcessor.rewriteFencedNode_(newNode);
  1464. }
  1465. classifyHorizontalFence_(node) {
  1466. node.role = SemanticRole.LEFTRIGHT;
  1467. const children = node.childNodes;
  1468. if (!SemanticPred.isSetNode(node) || children.length > 1) {
  1469. return;
  1470. }
  1471. if (children.length === 0 || children[0].type === SemanticType.EMPTY) {
  1472. node.role = SemanticRole.SETEMPTY;
  1473. return;
  1474. }
  1475. const type = children[0].type;
  1476. if (children.length === 1 &&
  1477. SemanticPred.isSingletonSetContent(children[0])) {
  1478. node.role = SemanticRole.SETSINGLE;
  1479. return;
  1480. }
  1481. const role = children[0].role;
  1482. if (type !== SemanticType.PUNCTUATED || role !== SemanticRole.SEQUENCE) {
  1483. return;
  1484. }
  1485. if (children[0].contentNodes[0].role === SemanticRole.COMMA) {
  1486. node.role = SemanticRole.SETCOLLECT;
  1487. return;
  1488. }
  1489. if (children[0].contentNodes.length === 1 &&
  1490. (children[0].contentNodes[0].role === SemanticRole.VBAR ||
  1491. children[0].contentNodes[0].role === SemanticRole.COLON)) {
  1492. node.role = SemanticRole.SETEXT;
  1493. SemanticProcessor.getInstance().setExtension_(node);
  1494. return;
  1495. }
  1496. }
  1497. setExtension_(set) {
  1498. const extender = set.childNodes[0].childNodes[0];
  1499. if (extender &&
  1500. extender.type === SemanticType.INFIXOP &&
  1501. extender.contentNodes.length === 1 &&
  1502. SemanticPred.isMembership(extender.contentNodes[0])) {
  1503. extender.addAnnotation('set', 'intensional');
  1504. extender.contentNodes[0].addAnnotation('set', 'intensional');
  1505. }
  1506. }
  1507. getPunctuationInRow_(nodes) {
  1508. if (nodes.length <= 1) {
  1509. return nodes;
  1510. }
  1511. const allowedType = (x) => {
  1512. const type = x.type;
  1513. return (type === 'punctuation' ||
  1514. type === 'text' ||
  1515. type === 'operator' ||
  1516. type === 'relation');
  1517. };
  1518. const partition = SemanticUtil.partitionNodes(nodes, function (x) {
  1519. if (!SemanticPred.isPunctuation(x)) {
  1520. return false;
  1521. }
  1522. if (SemanticPred.isPunctuation(x) &&
  1523. !SemanticPred.isRole(x, SemanticRole.ELLIPSIS)) {
  1524. return true;
  1525. }
  1526. const index = nodes.indexOf(x);
  1527. if (index === 0) {
  1528. if (nodes[1] && allowedType(nodes[1])) {
  1529. return false;
  1530. }
  1531. return true;
  1532. }
  1533. const prev = nodes[index - 1];
  1534. if (index === nodes.length - 1) {
  1535. if (allowedType(prev)) {
  1536. return false;
  1537. }
  1538. return true;
  1539. }
  1540. const next = nodes[index + 1];
  1541. if (allowedType(prev) && allowedType(next)) {
  1542. return false;
  1543. }
  1544. return true;
  1545. });
  1546. if (partition.rel.length === 0) {
  1547. return nodes;
  1548. }
  1549. let newNodes = [];
  1550. let firstComp = partition.comp.shift();
  1551. if (firstComp.length > 0) {
  1552. newNodes.push(SemanticProcessor.getInstance().row(firstComp));
  1553. }
  1554. let relCounter = 0;
  1555. while (partition.comp.length > 0) {
  1556. let puncts = [];
  1557. const saveCount = relCounter;
  1558. do {
  1559. puncts.push(partition.rel[relCounter++]);
  1560. firstComp = partition.comp.shift();
  1561. } while (partition.rel[relCounter] &&
  1562. firstComp &&
  1563. firstComp.length === 0);
  1564. puncts = SemanticHeuristics.run('ellipses', puncts);
  1565. partition.rel.splice(saveCount, relCounter - saveCount, ...puncts);
  1566. relCounter = saveCount + puncts.length;
  1567. newNodes = newNodes.concat(puncts);
  1568. if (firstComp && firstComp.length > 0) {
  1569. newNodes.push(SemanticProcessor.getInstance().row(firstComp));
  1570. }
  1571. }
  1572. return newNodes.length === 1 && partition.rel.length === 1
  1573. ? newNodes
  1574. : [
  1575. SemanticProcessor.getInstance().punctuatedNode_(newNodes, partition.rel)
  1576. ];
  1577. }
  1578. punctuatedNode_(nodes, punctuations) {
  1579. const newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.PUNCTUATED, nodes, punctuations);
  1580. if (punctuations.length === nodes.length) {
  1581. const firstRole = punctuations[0].role;
  1582. if (firstRole !== SemanticRole.UNKNOWN &&
  1583. punctuations.every(function (punct) {
  1584. return punct.role === firstRole;
  1585. })) {
  1586. newNode.role = firstRole;
  1587. return newNode;
  1588. }
  1589. }
  1590. const fpunct = punctuations[0];
  1591. if (SemanticPred.singlePunctAtPosition(nodes, punctuations, 0)) {
  1592. newNode.role =
  1593. fpunct.childNodes.length && !fpunct.embellished
  1594. ? fpunct.role
  1595. : SemanticRole.STARTPUNCT;
  1596. }
  1597. else if (SemanticPred.singlePunctAtPosition(nodes, punctuations, nodes.length - 1)) {
  1598. newNode.role =
  1599. fpunct.childNodes.length && !fpunct.embellished
  1600. ? fpunct.role
  1601. : SemanticRole.ENDPUNCT;
  1602. }
  1603. else if (punctuations.every((x) => SemanticPred.isRole(x, SemanticRole.DUMMY))) {
  1604. newNode.role = SemanticRole.TEXT;
  1605. }
  1606. else if (punctuations.every((x) => SemanticPred.isRole(x, SemanticRole.SPACE))) {
  1607. newNode.role = SemanticRole.SPACE;
  1608. }
  1609. else {
  1610. newNode.role = SemanticRole.SEQUENCE;
  1611. }
  1612. return newNode;
  1613. }
  1614. dummyNode_(children) {
  1615. const commata = SemanticProcessor.getInstance().factory_.makeMultipleContentNodes(children.length - 1, NamedSymbol.invisibleComma);
  1616. commata.forEach(function (comma) {
  1617. comma.role = SemanticRole.DUMMY;
  1618. });
  1619. return SemanticProcessor.getInstance().punctuatedNode_(children, commata);
  1620. }
  1621. accentRole_(node, type) {
  1622. if (!SemanticPred.isAccent(node)) {
  1623. return false;
  1624. }
  1625. const content = node.textContent;
  1626. const role = SemanticMap.Secondary.get(content, SemanticSecondary.BAR) ||
  1627. SemanticMap.Secondary.get(content, SemanticSecondary.TILDE) ||
  1628. node.role;
  1629. node.role =
  1630. type === SemanticType.UNDERSCORE
  1631. ? SemanticRole.UNDERACCENT
  1632. : SemanticRole.OVERACCENT;
  1633. node.addAnnotation('accent', role);
  1634. return true;
  1635. }
  1636. accentNode_(center, children, type, length, accent) {
  1637. children = children.slice(0, length + 1);
  1638. const child1 = children[1];
  1639. const child2 = children[2];
  1640. let innerNode;
  1641. if (!accent && child2) {
  1642. innerNode = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.SUBSCRIPT, [center, child1], []);
  1643. innerNode.role = SemanticRole.SUBSUP;
  1644. children = [innerNode, child2];
  1645. type = SemanticType.SUPERSCRIPT;
  1646. }
  1647. if (accent) {
  1648. const underAccent = SemanticProcessor.getInstance().accentRole_(child1, type);
  1649. if (child2) {
  1650. const overAccent = SemanticProcessor.getInstance().accentRole_(child2, SemanticType.OVERSCORE);
  1651. if (overAccent && !underAccent) {
  1652. innerNode = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.OVERSCORE, [center, child2], []);
  1653. children = [innerNode, child1];
  1654. type = SemanticType.UNDERSCORE;
  1655. }
  1656. else {
  1657. innerNode = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.UNDERSCORE, [center, child1], []);
  1658. children = [innerNode, child2];
  1659. type = SemanticType.OVERSCORE;
  1660. }
  1661. innerNode.role = SemanticRole.UNDEROVER;
  1662. }
  1663. }
  1664. return SemanticProcessor.getInstance().makeLimitNode_(center, children, innerNode, type);
  1665. }
  1666. makeLimitNode_(center, children, innerNode, type) {
  1667. if (type === SemanticType.LIMUPPER &&
  1668. center.type === SemanticType.LIMLOWER) {
  1669. center.childNodes.push(children[1]);
  1670. children[1].parent = center;
  1671. center.type = SemanticType.LIMBOTH;
  1672. return center;
  1673. }
  1674. if (type === SemanticType.LIMLOWER &&
  1675. center.type === SemanticType.LIMUPPER) {
  1676. center.childNodes.splice(1, -1, children[1]);
  1677. children[1].parent = center;
  1678. center.type = SemanticType.LIMBOTH;
  1679. return center;
  1680. }
  1681. const newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(type, children, []);
  1682. const embellished = SemanticPred.isEmbellished(center);
  1683. if (innerNode) {
  1684. innerNode.embellished = embellished;
  1685. }
  1686. newNode.embellished = embellished;
  1687. newNode.role = center.role;
  1688. return newNode;
  1689. }
  1690. getFunctionsInRow_(restNodes, opt_result) {
  1691. const result = opt_result || [];
  1692. if (restNodes.length === 0) {
  1693. return result;
  1694. }
  1695. const firstNode = restNodes.shift();
  1696. const heuristic = SemanticProcessor.classifyFunction_(firstNode, restNodes);
  1697. if (!heuristic) {
  1698. result.push(firstNode);
  1699. return SemanticProcessor.getInstance().getFunctionsInRow_(restNodes, result);
  1700. }
  1701. const processedRest = SemanticProcessor.getInstance().getFunctionsInRow_(restNodes, []);
  1702. const newRest = SemanticProcessor.getInstance().getFunctionArgs_(firstNode, processedRest, heuristic);
  1703. return result.concat(newRest);
  1704. }
  1705. getFunctionArgs_(func, rest, heuristic) {
  1706. let partition, arg, funcNode;
  1707. switch (heuristic) {
  1708. case 'integral': {
  1709. const components = SemanticProcessor.getInstance().getIntegralArgs_(rest);
  1710. if (!components.intvar && !components.integrand.length) {
  1711. components.rest.unshift(func);
  1712. return components.rest;
  1713. }
  1714. const integrand = SemanticProcessor.getInstance().row(components.integrand);
  1715. funcNode = SemanticProcessor.getInstance().integralNode_(func, integrand, components.intvar);
  1716. SemanticHeuristics.run('intvar_from_fraction', funcNode);
  1717. components.rest.unshift(funcNode);
  1718. return components.rest;
  1719. }
  1720. case 'prefix': {
  1721. if (rest[0] && rest[0].type === SemanticType.FENCED) {
  1722. const arg = rest.shift();
  1723. if (!SemanticPred.isNeutralFence(arg)) {
  1724. arg.role = SemanticRole.LEFTRIGHT;
  1725. }
  1726. funcNode = SemanticProcessor.getInstance().functionNode_(func, arg);
  1727. rest.unshift(funcNode);
  1728. return rest;
  1729. }
  1730. partition = SemanticUtil.sliceNodes(rest, SemanticPred.isPrefixFunctionBoundary);
  1731. if (!partition.head.length) {
  1732. if (!partition.div ||
  1733. !SemanticPred.isType(partition.div, SemanticType.APPL)) {
  1734. rest.unshift(func);
  1735. return rest;
  1736. }
  1737. arg = partition.div;
  1738. }
  1739. else {
  1740. arg = SemanticProcessor.getInstance().row(partition.head);
  1741. if (partition.div) {
  1742. partition.tail.unshift(partition.div);
  1743. }
  1744. }
  1745. funcNode = SemanticProcessor.getInstance().functionNode_(func, arg);
  1746. partition.tail.unshift(funcNode);
  1747. return partition.tail;
  1748. }
  1749. case 'bigop': {
  1750. partition = SemanticUtil.sliceNodes(rest, SemanticPred.isBigOpBoundary);
  1751. if (!partition.head.length) {
  1752. rest.unshift(func);
  1753. return rest;
  1754. }
  1755. arg = SemanticProcessor.getInstance().row(partition.head);
  1756. funcNode = SemanticProcessor.getInstance().bigOpNode_(func, arg);
  1757. if (partition.div) {
  1758. partition.tail.unshift(partition.div);
  1759. }
  1760. partition.tail.unshift(funcNode);
  1761. return partition.tail;
  1762. }
  1763. case 'simple':
  1764. default: {
  1765. if (rest.length === 0) {
  1766. return [func];
  1767. }
  1768. const firstArg = rest[0];
  1769. if (firstArg.type === SemanticType.FENCED &&
  1770. !SemanticPred.isNeutralFence(firstArg) &&
  1771. SemanticPred.isSimpleFunctionScope(firstArg)) {
  1772. firstArg.role = SemanticRole.LEFTRIGHT;
  1773. SemanticProcessor.propagateFunctionRole_(func, SemanticRole.SIMPLEFUNC);
  1774. funcNode = SemanticProcessor.getInstance().functionNode_(func, rest.shift());
  1775. rest.unshift(funcNode);
  1776. return rest;
  1777. }
  1778. rest.unshift(func);
  1779. return rest;
  1780. }
  1781. }
  1782. }
  1783. getIntegralArgs_(nodes, args = []) {
  1784. if (nodes.length === 0) {
  1785. const partition = SemanticUtil.sliceNodes(args, SemanticPred.isBigOpBoundary);
  1786. if (partition.div) {
  1787. partition.tail.unshift(partition.div);
  1788. }
  1789. return { integrand: partition.head, intvar: null, rest: partition.tail };
  1790. }
  1791. SemanticHeuristics.run('intvar_from_implicit', nodes);
  1792. const firstNode = nodes[0];
  1793. if (SemanticPred.isGeneralFunctionBoundary(firstNode)) {
  1794. const { integrand: args2, rest: rest2 } = SemanticProcessor.getInstance().getIntegralArgs_(args);
  1795. return { integrand: args2, intvar: null, rest: rest2.concat(nodes) };
  1796. }
  1797. if (SemanticPred.isIntegralDxBoundarySingle(firstNode)) {
  1798. firstNode.role = SemanticRole.INTEGRAL;
  1799. return { integrand: args, intvar: firstNode, rest: nodes.slice(1) };
  1800. }
  1801. if (nodes[1] && SemanticPred.isIntegralDxBoundary(firstNode, nodes[1])) {
  1802. const intvar = SemanticProcessor.getInstance().prefixNode_(nodes[1], [firstNode]);
  1803. intvar.role = SemanticRole.INTEGRAL;
  1804. return { integrand: args, intvar: intvar, rest: nodes.slice(2) };
  1805. }
  1806. args.push(nodes.shift());
  1807. return SemanticProcessor.getInstance().getIntegralArgs_(nodes, args);
  1808. }
  1809. functionNode_(func, arg) {
  1810. const applNode = SemanticProcessor.getInstance().factory_.makeContentNode(NamedSymbol.functionApplication);
  1811. const appl = SemanticProcessor.getInstance().funcAppls[func.id];
  1812. if (appl) {
  1813. applNode.mathmlTree = appl.mathmlTree;
  1814. applNode.mathml = appl.mathml;
  1815. applNode.annotation = appl.annotation;
  1816. applNode.attributes = appl.attributes;
  1817. delete SemanticProcessor.getInstance().funcAppls[func.id];
  1818. }
  1819. applNode.type = SemanticType.PUNCTUATION;
  1820. applNode.role = SemanticRole.APPLICATION;
  1821. const funcop = SemanticProcessor.getFunctionOp_(func, function (node) {
  1822. return (SemanticPred.isType(node, SemanticType.FUNCTION) ||
  1823. (SemanticPred.isType(node, SemanticType.IDENTIFIER) &&
  1824. SemanticPred.isRole(node, SemanticRole.SIMPLEFUNC)));
  1825. });
  1826. return SemanticProcessor.getInstance().functionalNode_(SemanticType.APPL, [func, arg], funcop, [applNode]);
  1827. }
  1828. bigOpNode_(bigOp, arg) {
  1829. const largeop = SemanticProcessor.getFunctionOp_(bigOp, (x) => SemanticPred.isType(x, SemanticType.LARGEOP));
  1830. return SemanticProcessor.getInstance().functionalNode_(SemanticType.BIGOP, [bigOp, arg], largeop, []);
  1831. }
  1832. integralNode_(integral, integrand, intvar) {
  1833. integrand =
  1834. integrand || SemanticProcessor.getInstance().factory_.makeEmptyNode();
  1835. intvar = intvar || SemanticProcessor.getInstance().factory_.makeEmptyNode();
  1836. const largeop = SemanticProcessor.getFunctionOp_(integral, (x) => SemanticPred.isType(x, SemanticType.LARGEOP));
  1837. return SemanticProcessor.getInstance().functionalNode_(SemanticType.INTEGRAL, [integral, integrand, intvar], largeop, []);
  1838. }
  1839. functionalNode_(type, children, operator, content) {
  1840. const funcop = children[0];
  1841. let oldParent;
  1842. if (operator) {
  1843. oldParent = operator.parent;
  1844. content.push(operator);
  1845. }
  1846. const newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(type, children, content);
  1847. newNode.role = funcop.role;
  1848. if (oldParent) {
  1849. operator.parent = oldParent;
  1850. }
  1851. return newNode;
  1852. }
  1853. fractionNode_(denom, enume) {
  1854. const newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.FRACTION, [denom, enume], []);
  1855. newNode.role = newNode.childNodes.every(function (x) {
  1856. return (SemanticPred.isType(x, SemanticType.NUMBER) &&
  1857. SemanticPred.isRole(x, SemanticRole.INTEGER));
  1858. })
  1859. ? SemanticRole.VULGAR
  1860. : newNode.childNodes.every(SemanticPred.isPureUnit)
  1861. ? SemanticRole.UNIT
  1862. : SemanticRole.DIVISION;
  1863. return SemanticHeuristics.run('propagateSimpleFunction', newNode);
  1864. }
  1865. scriptNode_(nodes, role, opt_noSingle) {
  1866. let newNode;
  1867. switch (nodes.length) {
  1868. case 0:
  1869. newNode = SemanticProcessor.getInstance().factory_.makeEmptyNode();
  1870. break;
  1871. case 1:
  1872. newNode = nodes[0];
  1873. if (opt_noSingle) {
  1874. return newNode;
  1875. }
  1876. break;
  1877. default:
  1878. newNode = SemanticProcessor.getInstance().dummyNode_(nodes);
  1879. }
  1880. newNode.role = role;
  1881. return newNode;
  1882. }
  1883. findNestedRow_(nodes, semantic, level, value) {
  1884. if (level > 3) {
  1885. return null;
  1886. }
  1887. for (let i = 0, node; (node = nodes[i]); i++) {
  1888. const tag = DomUtil.tagName(node);
  1889. if (tag !== MMLTAGS.MSPACE) {
  1890. if (tag === MMLTAGS.MROW) {
  1891. return SemanticProcessor.getInstance().findNestedRow_(DomUtil.toArray(node.childNodes), semantic, level + 1, value);
  1892. }
  1893. if (SemanticProcessor.findSemantics(node, semantic, value)) {
  1894. return node;
  1895. }
  1896. }
  1897. }
  1898. return null;
  1899. }
  1900. }
  1901. SemanticProcessor.FENCE_TO_PUNCT_ = {
  1902. [SemanticRole.METRIC]: SemanticRole.METRIC,
  1903. [SemanticRole.NEUTRAL]: SemanticRole.VBAR,
  1904. [SemanticRole.OPEN]: SemanticRole.OPENFENCE,
  1905. [SemanticRole.CLOSE]: SemanticRole.CLOSEFENCE
  1906. };
  1907. SemanticProcessor.MML_TO_LIMIT_ = {
  1908. [MMLTAGS.MSUB]: { type: SemanticType.LIMLOWER, length: 1 },
  1909. [MMLTAGS.MUNDER]: { type: SemanticType.LIMLOWER, length: 1 },
  1910. [MMLTAGS.MSUP]: { type: SemanticType.LIMUPPER, length: 1 },
  1911. [MMLTAGS.MOVER]: { type: SemanticType.LIMUPPER, length: 1 },
  1912. [MMLTAGS.MSUBSUP]: { type: SemanticType.LIMBOTH, length: 2 },
  1913. [MMLTAGS.MUNDEROVER]: { type: SemanticType.LIMBOTH, length: 2 }
  1914. };
  1915. SemanticProcessor.MML_TO_BOUNDS_ = {
  1916. [MMLTAGS.MSUB]: { type: SemanticType.SUBSCRIPT, length: 1, accent: false },
  1917. [MMLTAGS.MSUP]: {
  1918. type: SemanticType.SUPERSCRIPT,
  1919. length: 1,
  1920. accent: false
  1921. },
  1922. [MMLTAGS.MSUBSUP]: {
  1923. type: SemanticType.SUBSCRIPT,
  1924. length: 2,
  1925. accent: false
  1926. },
  1927. [MMLTAGS.MUNDER]: {
  1928. type: SemanticType.UNDERSCORE,
  1929. length: 1,
  1930. accent: true
  1931. },
  1932. [MMLTAGS.MOVER]: { type: SemanticType.OVERSCORE, length: 1, accent: true },
  1933. [MMLTAGS.MUNDEROVER]: {
  1934. type: SemanticType.UNDERSCORE,
  1935. length: 2,
  1936. accent: true
  1937. }
  1938. };
  1939. SemanticProcessor.CLASSIFY_FUNCTION_ = {
  1940. [SemanticRole.INTEGRAL]: 'integral',
  1941. [SemanticRole.SUM]: 'bigop',
  1942. [SemanticRole.PREFIXFUNC]: 'prefix',
  1943. [SemanticRole.LIMFUNC]: 'prefix',
  1944. [SemanticRole.SIMPLEFUNC]: 'prefix',
  1945. [SemanticRole.COMPFUNC]: 'prefix'
  1946. };
  1947. SemanticProcessor.MATHJAX_FONTS = {
  1948. '-tex-caligraphic': SemanticFont.CALIGRAPHIC,
  1949. '-tex-caligraphic-bold': SemanticFont.CALIGRAPHICBOLD,
  1950. '-tex-calligraphic': SemanticFont.CALIGRAPHIC,
  1951. '-tex-calligraphic-bold': SemanticFont.CALIGRAPHICBOLD,
  1952. '-tex-oldstyle': SemanticFont.OLDSTYLE,
  1953. '-tex-oldstyle-bold': SemanticFont.OLDSTYLEBOLD,
  1954. '-tex-mathit': SemanticFont.ITALIC
  1955. };