PHP and Javascript implementations of a simple markdown parser
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077
  1. /**
  2. * Base spreadsheet calculation error class.
  3. */
  4. class CellException extends Error {
  5. /**
  6. * Brief symbol to show in the cell to signify an error occurred during
  7. * evaluation.
  8. *
  9. * @type {string}
  10. */
  11. errorSymbol;
  12. /**
  13. * @param {string} message - error message
  14. * @param {string} errorSymbol - symbol to show in the cell to indicate an error
  15. */
  16. constructor(message, errorSymbol='#ERROR') {
  17. super(message);
  18. this.errorSymbol = errorSymbol;
  19. }
  20. }
  21. /**
  22. * Exception thrown when a spreadsheet expression is invalid.
  23. */
  24. class CellSyntaxException extends CellException {
  25. constructor(message, errorSymbol='#SYNTAX') {
  26. super(message, errorSymbol);
  27. }
  28. }
  29. /**
  30. * Exception thrown when a problem occurrs during evaluation.
  31. */
  32. class CellEvaluationException extends CellException {}
  33. /**
  34. * Exception thrown when cell dependencies cannot be resolved.
  35. */
  36. class CellDependencyException extends CellException {
  37. constructor(message, errorSymbol='#REF') {
  38. super(message, errorSymbol);
  39. }
  40. }
  41. /**
  42. * Expression parsing token types.
  43. */
  44. class CellExpressionTokenType {
  45. static Name = new this('Name');
  46. static Address = new this('Address');
  47. static NameOrAddress = new this('NameOrAddress');
  48. static String = new this('String');
  49. static Number = new this('Number');
  50. static OpenParen = new this('OpenParen');
  51. static CloseParen = new this('CloseParen');
  52. static Colon = new this('Colon');
  53. static Plus = new this('Plus');
  54. static Minus = new this('Minus');
  55. static Multiply = new this('Multiply');
  56. static Divide = new this('Divide');
  57. static Comma = new this('Comma');
  58. static Semicolon = new this('Semicolon');
  59. static Ampersand = new this('Ampersand');
  60. static LessThan = new this('LessThan');
  61. static LessThanEqual = new this('LessThanEqual');
  62. static GreaterThan = new this('GreaterThan');
  63. static GreaterThanEqual = new this('GreaterThanEqual');
  64. static Equal = new this('Equal');
  65. static Unequal = new this('Unequal');
  66. static Not = new this('Not');
  67. /** @type {string} */
  68. name;
  69. constructor(name) {
  70. this.name = name;
  71. }
  72. /**
  73. * @returns {boolean}
  74. */
  75. isPotentialName() {
  76. return this === CellExpressionTokenType.Name || this === CellExpressionTokenType.NameOrAddress;
  77. }
  78. /**
  79. * @returns {boolean}
  80. */
  81. isPotentialAddress() {
  82. return this === CellExpressionTokenType.Address || this === CellExpressionTokenType.NameOrAddress;
  83. }
  84. toString() {
  85. return this.name;
  86. }
  87. equals(other) {
  88. if (!(other instanceof CellExpressionTokenType)) return false;
  89. return other.name === this.name;
  90. }
  91. }
  92. /**
  93. * Type of operation for a `CellExpression`. Named functions all fall under
  94. * `Function`.
  95. */
  96. class CellExpressionOperation {
  97. /** Arg is `number` */
  98. static Number = new this('Number');
  99. /** Arg is `string` without quotes */
  100. static String = new this('String');
  101. /** Arg is `boolean` */
  102. static Boolean = new this('Boolean');
  103. /** Arg is `CellAddress` */
  104. static Reference = new this('Reference');
  105. /** Args are start and end `CellAddress`es (e.g. "A5", "C7") */
  106. static Range = new this('Range');
  107. /** Args are two operand `CellExpression`s. */
  108. static Add = new this('Add');
  109. /** Args are two operand `CellExpression`s */
  110. static Subtract = new this('Subtract');
  111. /** Args are two operand `CellExpression`s */
  112. static Multiply = new this('Multiply');
  113. /** Args are two operand `CellExpression`s */
  114. static Divide = new this('Divide');
  115. /** Args are two operand `CellExpression`s. */
  116. static Concatenate = new this('Concatenate');
  117. /** Arg is operand `CellExpression` */
  118. static UnaryMinus = new this('UnaryMinus');
  119. /** Args are two operand `CellExpression`s. */
  120. static GreaterThan = new this('GreaterThan');
  121. /** Args are two operand `CellExpression`s. */
  122. static GreaterThanEqual = new this('GreaterThanEqual');
  123. /** Args are two operand `CellExpression`s. */
  124. static LessThan = new this('LessThan');
  125. /** Args are two operand `CellExpression`s. */
  126. static LessThanEqual = new this('LessThanEqual');
  127. /** Args are two operand `CellExpression`s. */
  128. static Equal = new this('Equal');
  129. /** Args are two operand `CellExpression`s. */
  130. static Unequal = new this('Unequal');
  131. /** Arg is operand `CellExpression`. */
  132. static UnaryNot = new this('UnaryNot');
  133. /** Args are 0+ `CellExpression`s */
  134. static Function = new this('Function');
  135. /** @type {string} */
  136. name;
  137. constructor(name) {
  138. this.name = name;
  139. }
  140. toString() {
  141. return `${this.constructor.name}.${this.name}`;
  142. }
  143. equals(other) {
  144. if (!(other instanceof CellExpressionOperation)) return false;
  145. return other.name == this.name;
  146. }
  147. }
  148. /**
  149. * Collection of all calculated cells in a table. Evaluates formulas.
  150. */
  151. class CellExpressionSet {
  152. /** @type {SpreadsheetGrid} */
  153. #grid;
  154. /**
  155. * @param {SpreadsheetGrid} grid
  156. */
  157. constructor(grid) {
  158. this.#grid = grid;
  159. }
  160. /**
  161. * Populates the `outputValue` fields of every cell in the table. Cells
  162. * with formulas will attempt to be calculated or populated with error
  163. * values.
  164. */
  165. calculateCells() {
  166. const rowCount = this.#grid.rowCount;
  167. const colCount = this.#grid.columnCount;
  168. // Make queue of cell addresses with expressions in them
  169. /** @type {CellAddress[]} */
  170. var expressionAddressQueue = [];
  171. var range = new CellAddressRange(new CellAddress(0, 0), new CellAddress(colCount - 1, rowCount - 1));
  172. for (const address of range.cellsIn(this.#grid)) {
  173. const cell = this.#grid.cellAt(address);
  174. const value = cell.originalValue;
  175. if (value.type != CellValue.TYPE_FORMULA) {
  176. cell.outputValue = value;
  177. cell.isCalculated = false;
  178. continue;
  179. }
  180. try {
  181. const expression = CellExpression.parse(value.formattedValue, address);
  182. if (!expression) {
  183. throw new CellSyntaxException("Invalid expression");
  184. }
  185. cell.parsedExpression = expression;
  186. cell.isCalculated = true;
  187. expressionAddressQueue.push(address);
  188. this.#enqueueFilledBlanks(expression, expressionAddressQueue);
  189. } catch (e) {
  190. if (e instanceof CellSyntaxException || e instanceof CellEvaluationException) {
  191. cell.outputValue = CellValue.fromValue(e);
  192. } else {
  193. throw e;
  194. }
  195. }
  196. }
  197. // Try to evaluate each cell. If one depends on cells not yet calculated,
  198. // move it to the back of the queue and try again later.
  199. this.#processExpressionQueue(expressionAddressQueue);
  200. // Anything left in the queue is a circular reference.
  201. this.#processCircularReferences(expressionAddressQueue);
  202. }
  203. /**
  204. * Attempts to evaluate expressions at the given `addresses`. If an
  205. * expression has unevaluated references, the expression is moved to the
  206. * end of the queue and tried again later. When this method returns, any
  207. * elements left in `addresses` can be considered circular references.
  208. *
  209. * @param {CellAddress[]} addresses - mutable queue of formula addresses
  210. */
  211. #processExpressionQueue(addresses) {
  212. var requeueCount = 0;
  213. while (addresses.length > 0 && requeueCount < addresses.length) {
  214. const address = addresses[0];
  215. addresses.splice(0, 1);
  216. const cell = this.#grid.cellAt(address);
  217. try {
  218. const result = this.#evaluate(cell.parsedExpression, address);
  219. cell.isCalculated = true;
  220. if (result instanceof CellValue) {
  221. cell.outputValue = result;
  222. requeueCount = 0;
  223. } else if (Array.isArray(result)) {
  224. if (result.length == 1) {
  225. cell.outputValue = result[0];
  226. requeueCount = 0;
  227. } else {
  228. throw new CellEvaluationException(`Expression resolved to ${result.length} values, single value expected`);
  229. }
  230. } else {
  231. throw new CellEvaluationException(`Expression resolved to ${result && result.constructor ? result.constructor.name : typeof result}, expected CellValue`);
  232. }
  233. } catch (e) {
  234. if (e instanceof CellDependencyException) {
  235. // Depends on a value that hasn't been calculated yet
  236. addresses.push(address);
  237. requeueCount++;
  238. } else if (e instanceof CellSyntaxException || e instanceof CellEvaluationException) {
  239. cell.outputValue = CellValue.fromValue(e);
  240. requeueCount = 0;
  241. } else {
  242. throw e;
  243. }
  244. }
  245. }
  246. }
  247. /**
  248. * Autofills a formula, transposing the formula to each affected cell and
  249. * stored in `parsedExpression`, and each address is queued in `addresses`
  250. * for evaluation.
  251. *
  252. * @param {CellExpression} expression - autofilled formula
  253. * @param {CellAddress[]} addresses - mutable address queue
  254. */
  255. #enqueueFilledBlanks(expression, addresses) {
  256. for (const range of expression.fillRanges ?? []) {
  257. for (const filledAddress of range.cellsIn(this.#grid)) {
  258. const filledCell = this.#grid.cellAt(filledAddress);
  259. if (filledCell.originalValue.type == CellValue.TYPE_BLANK &&
  260. (!filledCell.outputValue ||
  261. filledCell.outputValue.type == CellValue.TYPE_BLANK)) {
  262. filledCell.parsedExpression = expression.transpose(expression.location, filledAddress);
  263. filledCell.isCalculated = true;
  264. addresses.push(filledAddress);
  265. }
  266. }
  267. }
  268. }
  269. /**
  270. * Marks all cells at the given addresses as circular references.
  271. *
  272. * @param {CellAddress[]} addresses - mutable address queue
  273. */
  274. #processCircularReferences(addresses) {
  275. for (const address of addresses) {
  276. const cell = this.#grid.cellAt(address);
  277. cell.outputValue = CellValue.fromValue(new CellDependencyException(`Circular reference at ${address.name}`));
  278. }
  279. }
  280. /**
  281. * Evaluates an expression if possible.
  282. *
  283. * @param {CellExpression} expr - expression to evaluate
  284. * @param {CellAddress} address - location of expression
  285. * @returns {CellValue|CellValue[]} - results
  286. */
  287. #evaluate(expr, address) {
  288. const result = this.#preevaluate(expr, address);
  289. if (result instanceof CellValue) {
  290. // Expression included formatting override. Apply it to value.
  291. if (expr.outputType !== null) {
  292. return CellValue.fromValue(result.value, expr.outputType ?? result.type, expr.outputDecimals);
  293. }
  294. }
  295. return result;
  296. }
  297. /**
  298. * Evaluates an expression if possible. No custom formatting is applied to
  299. * result.
  300. *
  301. * @param {CellExpression} expr - expression to evaluate
  302. * @param {CellAddress} address - location of expression
  303. * @returns {CellValue|CellValue[]} - results
  304. * @throws {CellException} if evaluation fails for any reason
  305. */
  306. #preevaluate(expr, address) {
  307. switch (expr.op) {
  308. case CellExpressionOperation.Number:
  309. case CellExpressionOperation.String:
  310. case CellExpressionOperation.Boolean:
  311. return expr.arguments[0];
  312. case CellExpressionOperation.Reference: {
  313. const refAddress = expr.arguments[0];
  314. if (refAddress === null) {
  315. throw new CellEvaluationException(`Invalid cell address`, '#REF');
  316. }
  317. const cell = this.#grid.cellAt(refAddress);
  318. if (cell === null) {
  319. throw new CellEvaluationException(`No cell at ${refAddress.name}`, '#REF');
  320. }
  321. if (cell.outputValue === null) {
  322. throw new CellDependencyException(`Need calculated value for ${refAddress} to evaluate`);
  323. }
  324. return cell.outputValue;
  325. }
  326. case CellExpressionOperation.Range: {
  327. const range = expr.arguments[0];
  328. var values = [];
  329. for (const rAddress of range.cellsIn(this.#grid)) {
  330. const cell = this.#grid.cellAt(rAddress);
  331. if (rAddress.equals(address)) continue;
  332. const val = this.#grid.outputValueAt(rAddress);
  333. if (val === null) {
  334. throw new CellDependencyException(`Need calculated value for ${rAddress.name} to evaluate`);
  335. }
  336. values.push(val);
  337. }
  338. return values;
  339. }
  340. case CellExpressionOperation.Add: {
  341. const op1 = this.#evaluate(expr.arguments[0], address);
  342. const op2 = this.#evaluate(expr.arguments[1], address);
  343. return op1.add(op2);
  344. }
  345. case CellExpressionOperation.Subtract: {
  346. const op1 = this.#evaluate(expr.arguments[0], address);
  347. const op2 = this.#evaluate(expr.arguments[1], address);
  348. return op1.subtract(op2);
  349. }
  350. case CellExpressionOperation.Multiply: {
  351. const op1 = this.#evaluate(expr.arguments[0], address);
  352. const op2 = this.#evaluate(expr.arguments[1], address);
  353. return op1.multiply(op2);
  354. }
  355. case CellExpressionOperation.Divide: {
  356. const op1 = this.#evaluate(expr.arguments[0], address);
  357. const op2 = this.#evaluate(expr.arguments[1], address);
  358. return op1.divide(op2);
  359. }
  360. case CellExpressionOperation.UnaryMinus: {
  361. const op = this.#evaluate(expr.arguments[0], address);
  362. return CellValue.fromValue(0).subtract(op);
  363. }
  364. case CellExpressionOperation.GreaterThan: {
  365. const op1 = this.#evaluate(expr.arguments[0], address);
  366. const op2 = this.#evaluate(expr.arguments[1], address);
  367. return op1.gt(op2);
  368. }
  369. case CellExpressionOperation.GreaterThanEqual: {
  370. const op1 = this.#evaluate(expr.arguments[0], address);
  371. const op2 = this.#evaluate(expr.arguments[1], address);
  372. return op1.gte(op2);
  373. }
  374. case CellExpressionOperation.LessThan: {
  375. const op1 = this.#evaluate(expr.arguments[0], address);
  376. const op2 = this.#evaluate(expr.arguments[1], address);
  377. return op1.lt(op2);
  378. }
  379. case CellExpressionOperation.LessThanEqual: {
  380. const op1 = this.#evaluate(expr.arguments[0], address);
  381. const op2 = this.#evaluate(expr.arguments[1], address);
  382. return op1.lte(op2);
  383. }
  384. case CellExpressionOperation.Equal: {
  385. const op1 = this.#evaluate(expr.arguments[0], address);
  386. const op2 = this.#evaluate(expr.arguments[1], address);
  387. return op1.eq(op2);
  388. }
  389. case CellExpressionOperation.Unequal: {
  390. const op1 = this.#evaluate(expr.arguments[0], address);
  391. const op2 = this.#evaluate(expr.arguments[1], address);
  392. return op1.neq(op2);
  393. }
  394. case CellExpressionOperation.UnaryNot: {
  395. const op = this.#evaluate(expr.arguments[0], address);
  396. return op.not();
  397. }
  398. case CellExpressionOperation.Concatenate: {
  399. const op1 = this.#evaluate(expr.arguments[0], address);
  400. const op2 = this.#evaluate(expr.arguments[1], address);
  401. return op1.concatenate(op2);
  402. }
  403. case CellExpressionOperation.Function:
  404. return this.#callFunction(expr.qualifier, expr.arguments, address);
  405. }
  406. throw new CellSyntaxException(`Unhandled operation ${expr.op.name}`);
  407. }
  408. /**
  409. * Evaluates a named function, e.g. `ABS`, `SUM`, etc.
  410. *
  411. * @param {string} functionName - function name
  412. * @param {Array} args - raw arguments
  413. * @param {CellAddress} address - location of the expression
  414. * @returns {CellValue} - result
  415. * @throws {CellException} if evaluation fails for any reason
  416. */
  417. #callFunction(functionName, args, address) {
  418. switch (functionName.toUpperCase()) {
  419. case 'ABS': return this.#funcAbs(args, address);
  420. case 'AND': return this.#funcAnd(args, address);
  421. case 'AVERAGE': return this.#funcAverage(args, address);
  422. case 'CEILING': return this.#funcCeiling(args, address);
  423. case 'EXP': return this.#funcExp(args, address);
  424. case 'FLOOR': return this.#funcFloor(args, address);
  425. case 'IF': return this.#funcIf(args, address);
  426. case 'IFS': return this.#funcIfs(args, address);
  427. case 'ISBLANK': return this.#funcIsBlank(args, address);
  428. case 'LN': return this.#funcLn(args, address);
  429. case 'LOG': return this.#funcLog(args, address);
  430. case 'LOWER': return this.#funcLower(args, address);
  431. case 'MAX': return this.#funcMax(args, address);
  432. case 'MIN': return this.#funcMin(args, address);
  433. case 'MOD': return this.#funcMod(args, address);
  434. case 'NOT': return this.#funcNot(args, address);
  435. case 'OR': return this.#funcOr(args, address);
  436. case 'POWER': return this.#funcPower(args, address);
  437. case 'ROUND': return this.#funcRound(args, address);
  438. case 'SQRT': return this.#funcSqrt(args, address);
  439. case 'SUBSTITUTE': return this.#funcSubstitute(args, address);
  440. case 'SUM': return this.#funcSum(args, address);
  441. case 'UPPER': return this.#funcUpper(args, address);
  442. case 'XOR': return this.#funcXor(args, address);
  443. default:
  444. throw new CellSyntaxException(`Unknown function "${functionName}"`);
  445. }
  446. }
  447. /**
  448. * Checks and evaluates arguments for a numeric function. If successful,
  449. * an array of `CellValue`s with numeric values is returned.
  450. *
  451. * @param {string} functionName - name of the function (for debugging)
  452. * @param {number} minArgs - minimum required arguments
  453. * @param {number} maxArgs - maximum required arguments
  454. * @param {Array} args - raw arguments
  455. * @param {CellAddress} address - address of the formula
  456. * @returns {CellValue[]} numeric arguments
  457. * @throws {CellSyntaxException} if wrong number of arguments is passed
  458. * @throws {CellEvaluationException} if an argument does not resolve to a numeric value
  459. */
  460. #assertNumericArguments(functionName, minArgs, maxArgs, args, address) {
  461. const argCount = args.length;
  462. if (argCount < minArgs || argCount > maxArgs) {
  463. if (minArgs == maxArgs) {
  464. throw new CellSyntaxException(`${functionName}() expects ${minArgs} arguments, got ${argCount}`);
  465. }
  466. throw new CellSyntaxException(`${functionName}() expects between ${minArgs} and ${maxArgs} arguments, got ${argCount}`);
  467. }
  468. var out = [];
  469. for (const argument of args) {
  470. const evaled = this.#evaluate(argument, address);
  471. if (!(evaled instanceof CellValue) || !evaled.isNumeric()) {
  472. throw new CellEvaluationException(`${functionName}() expects numeric arguments`);
  473. }
  474. out.push(evaled);
  475. }
  476. return out;
  477. }
  478. /**
  479. * Evaluates and flattens numeric arguments. For functions that can take
  480. * arbitrary numbers of values including whole cell ranges.
  481. *
  482. * @param {string} functionName - function name (for debugging)
  483. * @param {Array} args - raw arguments
  484. * @param {CellAddress} address - location of expression
  485. * @param {boolean} errorOnNonnumeric - whether to throw an exception if
  486. * non-numeric arguments are encountered, otherwise they're skipped silently
  487. * @returns {CellValue[]} flattened array of numeric values
  488. */
  489. #flattenedNumericArguments(functionName, args, address, errorOnNonnumeric=true) {
  490. var flattened = [];
  491. for (const argument of args) {
  492. const evaled = this.#evaluate(argument, address);
  493. if (evaled instanceof CellValue) {
  494. if (!evaled.isNumeric()) {
  495. if (errorOnNonnumeric) {
  496. throw new CellEvaluationException(`${functionName} requires numeric arguments`);
  497. }
  498. continue;
  499. }
  500. flattened.push(evaled);
  501. } else if (Array.isArray(evaled)) {
  502. const arr = evaled;
  503. for (const arrayArgument of arr) {
  504. if (arrayArgument instanceof CellValue) {
  505. if (!arrayArgument.isNumeric()) {
  506. if (errorOnNonnumeric) {
  507. throw new CellEvaluationException(`${functionName} requires numeric arguments`);
  508. }
  509. continue;
  510. }
  511. flattened.push(arrayArgument);
  512. }
  513. }
  514. }
  515. }
  516. return flattened;
  517. }
  518. /**
  519. * `ABS(value)` - absolute value of a numeric argument
  520. *
  521. * @param {Array} args - raw arguments
  522. * @param {CellAddress} address - expression location
  523. * @returns {CellValue} - result
  524. */
  525. #funcAbs(args, address) {
  526. const arg = this.#assertNumericArguments('ABS', 1, 1, args, address)[0];
  527. if (arg.value < 0.0) {
  528. return CellValue.fromValue(0).subtract(arg);
  529. }
  530. return arg;
  531. }
  532. /**
  533. * `AND(arg, arg, ..., arg)` - Boolean AND of any number of Boolean arguments
  534. *
  535. * @param {Array} args - raw arguments
  536. * @param {CellAddress} address - expression location
  537. * @returns {CellValue} - result
  538. */
  539. #funcAnd(args, address) {
  540. if (args.length == 0) {
  541. throw new CellEvaluationException("AND requires one or more arguments");
  542. }
  543. const values = this.#flattenedNumericArguments('AND', args, address, false);
  544. for (const value of values) {
  545. const result = value.booleanValue();
  546. if (result === null) {
  547. throw new CellEvaluationException("AND requires boolean arguments");
  548. }
  549. if (!result) return CellValue.fromValue(false);
  550. }
  551. return CellValue.fromValue(true);
  552. }
  553. /**
  554. * `AVERAGE(arg, arg, ..., arg)` - Averages values. Non-numeric values are
  555. * omitted from the calculation.
  556. *
  557. * @param {Array} args - raw arguments
  558. * @param {CellAddress} address - expression location
  559. * @returns {CellValue} - result
  560. */
  561. #funcAverage(args, address) {
  562. var sum = CellValue.fromValue(0);
  563. var count = 0;
  564. for (const arg of args) {
  565. const val = this.#evaluate(arg, address);
  566. if (Array.isArray(val)) {
  567. for (const elem of val) {
  568. if (!elem.isNumeric()) continue;
  569. sum = sum.add(elem);
  570. count++;
  571. }
  572. } else if (val.isNumeric()) {
  573. sum = sum.add(val);
  574. count++;
  575. }
  576. }
  577. return (count > 0) ? sum.divide(CellValue.fromValue(count)) : CellValue.fromValue(0);
  578. }
  579. /**
  580. * `CEILING(value)` - Ceiling of a numeric value.
  581. *
  582. * @param {Array} args - raw arguments
  583. * @param {CellAddress} address - expression location
  584. * @returns {CellValue} - result
  585. */
  586. #funcCeiling(args, address) {
  587. const arg = this.#assertNumericArguments('CEILING', 1, 1, args, address)[0];
  588. const newValue = Math.ceil(arg.value);
  589. return CellValue.fromValue(newValue, arg.type);
  590. }
  591. /**
  592. * `EXP(value)` - Computes _e_ raised to the given exponent.
  593. *
  594. * @param {Array} args - raw arguments
  595. * @param {CellAddress} address - expression location
  596. * @returns {CellValue} - result
  597. */
  598. #funcExp(args, address) {
  599. const arg = this.#assertNumericArguments('EXP', 1, 1, args, address)[0];
  600. const newValue = Math.exp(arg.value);
  601. return CellValue.fromValue(newValue, arg.type);
  602. }
  603. /**
  604. * `FLOOR(value)` - Numeric value rounded down.
  605. *
  606. * @param {Array} args - raw arguments
  607. * @param {CellAddress} address - expression location
  608. * @returns {CellValue} - result
  609. */
  610. #funcFloor(args, address) {
  611. const arg = this.#assertNumericArguments('FLOOR', 1, 1, args, address)[0];
  612. const newValue = Math.floor(arg.value);
  613. return CellValue.fromValue(newValue, arg.type);
  614. }
  615. /**
  616. * `IF(test, trueVal, falseVal)` - Conditional test.
  617. *
  618. * @param {Array} args - raw arguments
  619. * @param {CellAddress} address - expression location
  620. * @returns {CellValue} - result
  621. */
  622. #funcIf(args, address) {
  623. if (args.length != 3) {
  624. throw new CellEvaluationException("IF expects three arguments");
  625. }
  626. const evaled = args.map((arg) => this.#evaluate(arg, address));
  627. const test = evaled[0].booleanValue();
  628. if (test === null) {
  629. throw new CellEvaluationException("IF expects a boolean for the first argument");
  630. }
  631. if (test) {
  632. return evaled[1];
  633. } else {
  634. return evaled[2];
  635. }
  636. }
  637. /**
  638. * `IFS(test1, result1, test2, result2, ..., fallbackResult)` - Multiple if
  639. * statement. Takes 3 or more arguments of an odd number consisting of pairs
  640. * of a Boolean test followed by the value to return if true. The very last
  641. * value is the fallback value to return if none of the Boolean tests are true.
  642. *
  643. * @param {Array} args - raw arguments
  644. * @param {CellAddress} address - expression location
  645. * @returns {CellValue} - result
  646. */
  647. #funcIfs(args, address) {
  648. if (args.length < 3) {
  649. throw new CellEvaluationException("IFS expects at least 3 arguments");
  650. }
  651. if ((args.length % 2) != 1) {
  652. throw new CellEvaluationException("IFS expects an odd number of arguments");
  653. }
  654. const evaled = args.map((arg) => this.#evaluate(arg, address));
  655. for (var i = 0; i < evaled.length - 1; i += 2) {
  656. const test = evaled[i].booleanValue();
  657. if (test === null) {
  658. throw new CellEvaluationException(`IFS expects a boolean for argument ${i + 1}`);
  659. }
  660. if (test) {
  661. return evaled[i + 1];
  662. }
  663. }
  664. return evaled[evaled.length - 1];
  665. }
  666. /**
  667. * `IFBLANK(value)` - Returns `TRUE` if the given value is blank, otherwise
  668. * `FALSE`.
  669. *
  670. * @param {Array} args - raw arguments
  671. * @param {CellAddress} address - expression location
  672. * @returns {CellValue} - result
  673. */
  674. #funcIsBlank(args, address) {
  675. if (args.length !== 1) {
  676. throw new CellEvaluationException("IFBLANK expects 1 argument");
  677. }
  678. const arg = this.#evaluate(args[0], address);
  679. if (!(arg instanceof CellValue)) {
  680. throw new CellEvaluationException("IFBLANK expcts 1 argument");
  681. }
  682. return CellValue.fromValue(arg.type === CellValue.TYPE_BLANK);
  683. }
  684. /**
  685. * `LN(value)` - Natural log.
  686. *
  687. * @param {Array} args - raw arguments
  688. * @param {CellAddress} address - expression location
  689. * @returns {CellValue} - result
  690. */
  691. #funcLn(args, address) {
  692. const arg = this.#assertNumericArguments('LN', 1, 1, args, address)[0];
  693. const newValue = Math.log(arg.value);
  694. return CellValue.fromValue(newValue, arg.type);
  695. }
  696. /**
  697. * `LOG(value, [base])` - Logarithm. Base is 10 if not provided.
  698. *
  699. * @param {Array} args - raw arguments
  700. * @param {CellAddress} address - expression location
  701. * @returns {CellValue} - result
  702. */
  703. #funcLog(args, address) {
  704. const evaled = this.#assertNumericArguments('LOG', 1, 2, args, address);
  705. const exponent = evaled[0];
  706. const base = (evaled.length > 1) ? evaled[1].value : 10.0;
  707. const newValue = Math.log(exponent.value) / Math.log(base);
  708. return CellValue.fromValue(newValue, exponent.type);
  709. }
  710. /**
  711. * `LOWER(text)` - Lowercase version of a string.
  712. *
  713. * @param {Array} args - raw arguments
  714. * @param {CellAddress} address - expression location
  715. * @returns {CellValue} - result
  716. */
  717. #funcLower(args, address) {
  718. if (args.length != 1) {
  719. throw new CellEvaluationException("LOWER requires one argument");
  720. }
  721. const evaled = args.map((arg) => this.#evaluate(arg, address));
  722. const s = evaled[0].stringValue(true);
  723. if (s === null) {
  724. throw new CellEvaluationException("LOWER requires one string argument");
  725. }
  726. return CellValue.fromValue(s.toLowerCase());
  727. }
  728. /**
  729. * `MAX(arg, arg, ... arg)` - Returns the maximum numeric value.
  730. *
  731. * @param {Array} args - raw arguments
  732. * @param {CellAddress} address - expression location
  733. * @returns {CellValue} - result
  734. */
  735. #funcMax(args, address) {
  736. var maxValue = null;
  737. const flattened = this.#flattenedNumericArguments('MAX', args, address);
  738. if (flattened.length == 0) {
  739. throw new CellEvaluationException("MAX requires at least one numeric argument");
  740. }
  741. for (const argument of flattened) {
  742. if (maxValue === null || argument.value > maxValue.value) {
  743. maxValue = argument;
  744. }
  745. }
  746. return maxValue ?? CellValue.fromValue(0);
  747. }
  748. /**
  749. * `MIN(arg, arg, ... arg)` - Returns the minimum numeric value.
  750. *
  751. * @param {Array} args - raw arguments
  752. * @param {CellAddress} address - expression location
  753. * @returns {CellValue} - result
  754. */
  755. #funcMin(args, address) {
  756. var minValue = null;
  757. const flattened = this.#flattenedNumericArguments('MIN', args, address);
  758. if (flattened.length == 0) {
  759. throw new CellEvaluationException("MIN requires at least one numeric argument");
  760. }
  761. for (const argument of flattened) {
  762. if (minValue === null || argument.value < minValue.value) {
  763. minValue = argument;
  764. }
  765. }
  766. return minValue ?? CellValue.fromValue(0);
  767. }
  768. /**
  769. * `MOD(value, divisor)` - Returns the remainder after a division.
  770. *
  771. * @param {Array} args - raw arguments
  772. * @param {CellAddress} address - expression location
  773. * @returns {CellValue} - result
  774. */
  775. #funcMod(args, address) {
  776. if (args.length != 2) {
  777. throw new CellEvaluationException("MOD requires two numeric arguments");
  778. }
  779. const values = args.map((arg) => this.#evaluate(arg, address));
  780. return values[0].modulo(values[1]);
  781. }
  782. /**
  783. * `NOT(value)` - Boolean NOT of a Boolean value.
  784. *
  785. * @param {Array} args - raw arguments
  786. * @param {CellAddress} address - expression location
  787. * @returns {CellValue} - result
  788. */
  789. #funcNot(args, address) {
  790. if (args.length != 1) {
  791. throw new CellEvaluationException("NOT expects one argument");
  792. }
  793. const evaled = args.map((arg) => this.#evaluate(arg, address));
  794. const b = evaled[0].booleanValue();
  795. if (b === null) {
  796. throw new CellEvaluationException("NOT expects boolean argument");
  797. }
  798. return CellValue.fromValue(!b);
  799. }
  800. /**
  801. * `OR(arg, arg, ... arg)` - Boolean OR of one or more Boolean arguments.
  802. *
  803. * @param {Array} args - raw arguments
  804. * @param {CellAddress} address - expression location
  805. * @returns {CellValue} - result
  806. */
  807. #funcOr(args, address) {
  808. if (args.length == 0) {
  809. throw new CellEvaluationException("OR requires one or more arguments");
  810. }
  811. const values = this.#flattenedNumericArguments('OR', args, address, false);
  812. for (const value of values) {
  813. const result = value.booleanValue();
  814. if (result === null) {
  815. throw new CellEvaluationException("OR requires boolean arguments");
  816. }
  817. if (result) return CellValue.fromValue(true);
  818. }
  819. return CellValue.fromValue(false);
  820. }
  821. /**
  822. * `POWER(base, exponent)` - Raises a base to an exponent.
  823. *
  824. * @param {Array} args - raw arguments
  825. * @param {CellAddress} address - expression location
  826. * @returns {CellValue} - result
  827. */
  828. #funcPower(args, address) {
  829. const evaled = this.#assertNumericArguments('POWER', 2, 2, args, address);
  830. const base = evaled[0];
  831. const exp = evaled[1];
  832. const val = Math.pow(base.value, exp.value);
  833. return CellValue.fromValue(val, base.type);
  834. }
  835. /**
  836. * `ROUND(value, [places])` - Rounds a number, optionally to the given number
  837. * of digits after the decimal place. Negative places round to the nearest
  838. * 10, 100, 1000, etc.
  839. *
  840. * @param {Array} args - raw arguments
  841. * @param {CellAddress} address - expression location
  842. * @returns {CellValue} - result
  843. */
  844. #funcRound(args, address) {
  845. const evaled = this.#assertNumericArguments('ROUND', 1, 2, args, address);
  846. const val = evaled[0];
  847. const places = evaled.length > 1 ? evaled[1].value : 0;
  848. const divider = Math.pow(10.0, places);
  849. const newValue = Math.round(val.value * divider) / divider;
  850. return CellValue.fromValue(newValue, val.type);
  851. }
  852. /**
  853. * `SQRT(value)` - Square root.
  854. *
  855. * @param {Array} args - raw arguments
  856. * @param {CellAddress} address - expression location
  857. * @returns {CellValue} - result
  858. */
  859. #funcSqrt(args, address) {
  860. const arg = this.#assertNumericArguments('SQRT', 1, 1, args, address)[0];
  861. const val = arg.numericValue();
  862. return CellValue.fromValue(Math.sqrt(val));
  863. }
  864. /**
  865. * `SUBSTITUTE(text, pattern, replacement)` - Substitutes all occurrences of
  866. * `pattern` within `text` with `replacement`.
  867. *
  868. * @param {Array} args - raw arguments
  869. * @param {CellAddress} address - expression location
  870. * @returns {CellValue} - result
  871. */
  872. #funcSubstitute(args, address) {
  873. if (args.length != 3) {
  874. throw new CellEvaluationException("SUBSTITUTE expects 3 string arguments");
  875. }
  876. const values = args.map((arg) => this.#evaluate(arg, address));
  877. const text = values[0].stringValue();
  878. const search = values[1].stringValue();
  879. const replace = values[2].stringValue();
  880. if (text === null || search === null || replace === null) {
  881. throw new CellEvaluationException("SUBSTITUTE expects 3 string arguments");
  882. }
  883. const result = text.replace(new RegExp(MDUtils.escapeRegex(search), 'gi'), replace);
  884. return CellValue.fromValue(result);
  885. }
  886. /**
  887. * `SUM(arg, arg, ... arg)` - Calculates the sum of numeric arguments.
  888. *
  889. * @param {Array} args - raw arguments
  890. * @param {CellAddress} address - expression location
  891. * @returns {CellValue} - result
  892. */
  893. #funcSum(args, address) {
  894. var sum = CellValue.fromValue(0);
  895. for (const arg of args) {
  896. const val = this.#evaluate(arg, address);
  897. if (Array.isArray(val)) {
  898. for (const elem of val) {
  899. if (elem.isNumeric()) sum = sum.add(elem);
  900. }
  901. } else if (val.isNumeric()) {
  902. sum = sum.add(val);
  903. }
  904. }
  905. return sum;
  906. }
  907. /**
  908. * `UPPER(text)` - Uppercase of a text argument.
  909. *
  910. * @param {Array} args - raw arguments
  911. * @param {CellAddress} address - expression location
  912. * @returns {CellValue} - result
  913. */
  914. #funcUpper(args, address) {
  915. if (args.length != 1) {
  916. throw new CellEvaluationException("UPPER requires one argument");
  917. }
  918. const evaled = args.map((arg) => this.#evaluate(arg, address));
  919. const s = evaled[0].stringValue(true);
  920. if (s === null) {
  921. throw new CellEvaluationException("UPPER requires one string argument");
  922. }
  923. return CellValue.fromValue(s.toUpperCase());
  924. }
  925. /**
  926. * `XOR(arg, arg, ... arg)` - Boolean XOR of one or more Boolean arguments.
  927. *
  928. * @param {Array} args - raw arguments
  929. * @param {CellAddress} address - expression location
  930. * @returns {CellValue} - result
  931. */
  932. #funcXor(args, address) {
  933. if (args.length == 0) {
  934. throw new CellEvaluationException("XOR requires one or more arguments");
  935. }
  936. const values = this.#flattenedNumericArguments('XOR', args, address, false);
  937. var result = null;
  938. for (const value of values) {
  939. const b = value.booleanValue();
  940. if (b === null) {
  941. throw new CellEvaluationException("XOR requires boolean arguments");
  942. }
  943. result = (result === null) ? b : (result ^ b);
  944. }
  945. return CellValue.fromValue(result != 0);
  946. }
  947. }
  948. /**
  949. * A spreadsheet formula expression. Evaluation is done by `CellExpressionSet`.
  950. */
  951. class CellExpression {
  952. /**
  953. * Operation.
  954. * @type {CellExpressionOperation}
  955. */
  956. op;
  957. /**
  958. * Mixed array of `CellValue`, `CellAddress`, `CellAddressRange`,
  959. * `CellExpression`, perhaps more.
  960. * @type {Array}
  961. */
  962. arguments;
  963. /**
  964. * For `Function`, the function name.
  965. * @type {string|null}
  966. */
  967. qualifier;
  968. /**
  969. * Optional format override. One of `number`, `currency`, `percent`.
  970. * @type {string|null}
  971. */
  972. outputType = null;
  973. /**
  974. * Optional decimal place formatting override.
  975. * @type {number|null}
  976. */
  977. outputDecimals = null;
  978. /**
  979. * Address ranges to copy this expression into for any blank cells. Used
  980. * by formulas with the `FILL` modifier.
  981. * @type {CellAddressRange[]|null} fillRanges
  982. */
  983. fillRanges = null;
  984. /**
  985. * Source address of the formula.
  986. * @type {CellAddress|null}
  987. */
  988. location = null;
  989. /**
  990. * @param {CellExpressionOperation} op
  991. * @param {Array} args
  992. * @param {string|null} qualifier
  993. */
  994. constructor(op, args, qualifier = null) {
  995. this.op = op;
  996. this.arguments = args;
  997. this.qualifier = qualifier;
  998. }
  999. /**
  1000. * Attempts to parse a formula expression.
  1001. *
  1002. * @param {string} expression - formula string, including leading `=`
  1003. * @param {CellAddress} address - location of the formula
  1004. * @returns {CellExpression|null} - parsed expression, or `null` if it failed
  1005. */
  1006. static parse(expression, address) {
  1007. const tokens = this.expressionToTokens(expression);
  1008. if (tokens.length == 0) return null;
  1009. const expr = this.expressionFromTokens(tokens, address);
  1010. expr.location = address;
  1011. return expr;
  1012. }
  1013. /**
  1014. * Writes an expression tree to console.error for debugging purposes.
  1015. *
  1016. * @param {CellExpression} expression
  1017. * @param {string} indent
  1018. */
  1019. static dumpExpression(expression, indent = '') {
  1020. if (expression.arguments.length == 0) {
  1021. console.error(indent + "expr " + expression.op.name + '()');
  1022. } else {
  1023. console.error(indent + expression.op.name + '(');
  1024. for (const argument of expression.arguments) {
  1025. if (typeof argument == 'number') {
  1026. console.error(indent + `\t${argument}`);
  1027. } else if (typeof argument == 'string') {
  1028. console.error(indent + `\t"${argument}"`);
  1029. } else if (typeof argument == 'boolean') {
  1030. console.error(indent + "\t" + (argument ? "true" : "false"));
  1031. } else if (argument instanceof CellAddress) {
  1032. console.error(indent + "\t" + argument.name);
  1033. } else if (argument instanceof CellAddressRange) {
  1034. console.error(indent + "\t" + argument.name);
  1035. } else if (argument instanceof CellValue) {
  1036. console.error(indent + "\t" + argument.type + " " + argument.formattedValue);
  1037. } else if (argument instanceof CellExpression) {
  1038. this.dumpExpression(argument, indent + "\t");
  1039. } else {
  1040. console.error(indent + "\t" + typeof argument);
  1041. }
  1042. }
  1043. console.error(indent + ')');
  1044. }
  1045. }
  1046. #clone() {
  1047. const cp = new CellExpression();
  1048. cp.op = this.op;
  1049. cp.arguments = this.arguments.slice();
  1050. cp.qualifier = this.qualifier;
  1051. cp.outputType = this.outputType;
  1052. cp.outputDecimals = this.outputDecimals;
  1053. cp.fillRanges = this.fillRanges !== null ? this.fillRanges.slice() : null;
  1054. cp.location = this.location;
  1055. return cp;
  1056. }
  1057. /**
  1058. * Returns a copy of this expression with cell references transposed by
  1059. * the delta between `start` and `end` addresses. Used for repeating an
  1060. * autofilled formula into blank cells.
  1061. *
  1062. * @param {CellAddress} start
  1063. * @param {CellAddress} end
  1064. * @returns {CellExpression|null}
  1065. */
  1066. transpose(start, end) {
  1067. var transposed = this.#clone(); // structuredClone makes a mess of typing
  1068. transposed.arguments = [];
  1069. for (const argument of this.arguments) {
  1070. if (argument instanceof CellExpression) {
  1071. transposed.arguments.push(argument.transpose(start, end));
  1072. } else if (argument instanceof CellAddress) {
  1073. transposed.arguments.push(argument.transpose(start, end));
  1074. } else if (argument instanceof CellAddressRange) {
  1075. transposed.arguments.push(argument.transpose(start, end));
  1076. } else {
  1077. transposed.arguments.push(argument);
  1078. }
  1079. }
  1080. return transposed;
  1081. }
  1082. // -- Tokenizing --------------------------------------------------------
  1083. /**
  1084. * Converts an expression into an array of tokens.
  1085. * @param {string} text - expression
  1086. * @returns {CellExpressionToken[]} tokens
  1087. */
  1088. static expressionToTokens(text) {
  1089. var tokens = [];
  1090. var pos = [0];
  1091. this.#skipWhitespace(text, pos);
  1092. if (text.substring(pos[0], pos[0] + 1) == '=') {
  1093. // Ignore equals
  1094. pos[0]++;
  1095. }
  1096. this.#skipWhitespace(text, pos);
  1097. var l = text.length;
  1098. while (pos[0] < l) {
  1099. tokens.push(this.#readNextToken(text, pos));
  1100. this.#skipWhitespace(text, pos);
  1101. }
  1102. return tokens;
  1103. }
  1104. /**
  1105. * @param {string} text
  1106. * @param {number[]} pos
  1107. * @returns {CellExpressionToken}
  1108. */
  1109. static #readNextToken(text, pos) {
  1110. // Single char tokens
  1111. var token;
  1112. if (token = this.#readNextSimpleToken(text, pos, '==', CellExpressionTokenType.Equal)) return token;
  1113. if (token = this.#readNextSimpleToken(text, pos, '!=', CellExpressionTokenType.Unequal)) return token;
  1114. if (token = this.#readNextSimpleToken(text, pos, '<=', CellExpressionTokenType.LessThanEqual)) return token;
  1115. if (token = this.#readNextSimpleToken(text, pos, '>=', CellExpressionTokenType.GreaterThanEqual)) return token;
  1116. if (token = this.#readNextSimpleToken(text, pos, '<', CellExpressionTokenType.LessThan)) return token;
  1117. if (token = this.#readNextSimpleToken(text, pos, '>', CellExpressionTokenType.GreaterThan)) return token;
  1118. if (token = this.#readNextSimpleToken(text, pos, '!', CellExpressionTokenType.Not)) return token;
  1119. if (token = this.#readNextSimpleToken(text, pos, '+', CellExpressionTokenType.Plus)) return token;
  1120. if (token = this.#readNextSimpleToken(text, pos, '-', CellExpressionTokenType.Minus)) return token;
  1121. if (token = this.#readNextSimpleToken(text, pos, '*', CellExpressionTokenType.Multiply)) return token;
  1122. if (token = this.#readNextSimpleToken(text, pos, '/', CellExpressionTokenType.Divide)) return token;
  1123. if (token = this.#readNextSimpleToken(text, pos, ',', CellExpressionTokenType.Comma)) return token;
  1124. if (token = this.#readNextSimpleToken(text, pos, '(', CellExpressionTokenType.OpenParen)) return token;
  1125. if (token = this.#readNextSimpleToken(text, pos, ')', CellExpressionTokenType.CloseParen)) return token;
  1126. if (token = this.#readNextSimpleToken(text, pos, ':', CellExpressionTokenType.Colon)) return token;
  1127. if (token = this.#readNextSimpleToken(text, pos, ';', CellExpressionTokenType.Semicolon)) return token;
  1128. if (token = this.#readNextSimpleToken(text, pos, '&', CellExpressionTokenType.Ampersand)) return token;
  1129. // Other tokens
  1130. if (token = this.#readNextAddressToken(text, pos)) return token;
  1131. if (token = this.#readNextNameToken(text, pos)) return token;
  1132. if (token = this.#readNextNumberToken(text, pos)) return token;
  1133. if (token = this.#readNextStringToken(text, pos)) return token;
  1134. throw new CellSyntaxException(`Unexpected character "${text.substring(pos[0], pos[0] + 1)}" at ${pos[0]}`);
  1135. }
  1136. /**
  1137. * @param {string} text
  1138. * @param {number[]} pos
  1139. */
  1140. static #skipWhitespace(text, pos) {
  1141. const l = text.length;
  1142. while (pos[0] < l) {
  1143. const ch = text.substring(pos[0], pos[0] + 1);
  1144. if (ch == ' ' || ch == "\t" || ch == "\n" || ch == "\r") {
  1145. pos[0]++;
  1146. } else {
  1147. return;
  1148. }
  1149. }
  1150. }
  1151. /**
  1152. * @param {string} text
  1153. * @param {number[]} pos
  1154. * @param {string} target
  1155. * @param {CellExpressionTokenType} type
  1156. * @returns {CellExpressionToken|null}
  1157. */
  1158. static #readNextSimpleToken(text, pos, target, type) {
  1159. const remaining = text.length - pos[0];
  1160. const l = target.length;
  1161. if (l > remaining) return null;
  1162. const test = text.substring(pos[0], pos[0] + l);
  1163. if (test.toUpperCase() != target.toUpperCase()) return null;
  1164. pos[0] += l;
  1165. return new CellExpressionToken(type, test);
  1166. }
  1167. /**
  1168. * @param {string} text
  1169. * @param {number[]} pos
  1170. * @returns {CellExpressionToken|null}
  1171. */
  1172. static #readNextAddressToken(text, pos) {
  1173. var p = [ pos[0] ];
  1174. var ch = text.substring(p[0], p[0] + 1);
  1175. var address = '';
  1176. var isName = true;
  1177. if (ch == '$') {
  1178. address += ch;
  1179. isName = false;
  1180. p[0]++;
  1181. }
  1182. var col = this.#readChars(text, p, (s) => this.#isLetter(s), 1, 2);
  1183. if (col === null) return null;
  1184. address += col;
  1185. ch = text.substring(p[0], p[0] + 1);
  1186. if (ch == '$') {
  1187. address += ch;
  1188. isName = false;
  1189. p[0]++;
  1190. const row = this.#readChars(text, p, this.#isDigit, 1);
  1191. if (row === null) return null;
  1192. address += row;
  1193. } else {
  1194. const row = this.#readChars(text, p, this.#isDigit, 0);
  1195. if (row === null) return null;
  1196. address += row;
  1197. }
  1198. pos[0] = p[0];
  1199. return new CellExpressionToken(
  1200. isName ? CellExpressionTokenType.NameOrAddress : CellExpressionTokenType.Address,
  1201. address);
  1202. }
  1203. /**
  1204. * @param {string} text
  1205. * @param {number[]} pos
  1206. * @returns {CellExpressionToken|null}
  1207. */
  1208. static #readNextNameToken(text, pos) {
  1209. var p = [ pos[0] ];
  1210. const name = this.#readChars(text, p, (s) => this.#isLetter(s), 1);
  1211. if (name === null) return null;
  1212. pos[0] = p[0];
  1213. if (CellAddress.isAddress(name)) {
  1214. return new CellExpressionToken(CellExpressionTokenType.NameOrAddress, name);
  1215. }
  1216. return new CellExpressionToken(CellExpressionTokenType.Name, name);
  1217. }
  1218. /**
  1219. * @param {string} text
  1220. * @param {number[]} pos
  1221. * @returns {CellExpressionToken|null}
  1222. */
  1223. static #readNextNumberToken(text, pos) {
  1224. var ch = text.substring(pos[0], pos[0] + 1);
  1225. if (!this.#isDigit(ch)) return null;
  1226. const l = text.length;
  1227. var numStr = ch;
  1228. pos[0]++;
  1229. while (pos[0] < l) {
  1230. ch = text.substring(pos[0], pos[0] + 1);
  1231. if (this.#isDigit(ch)) {
  1232. pos[0]++;
  1233. numStr += ch;
  1234. } else {
  1235. break;
  1236. }
  1237. }
  1238. if (pos[0] < l) {
  1239. ch = text.substring(pos[0], pos[0] + 1);
  1240. if (ch == '.') {
  1241. numStr += ch;
  1242. pos[0]++;
  1243. while (pos[0] < l) {
  1244. ch = text.substring(pos[0], pos[0] + 1);
  1245. if (this.#isDigit(ch)) {
  1246. pos[0]++;
  1247. numStr += ch;
  1248. } else {
  1249. break;
  1250. }
  1251. }
  1252. }
  1253. }
  1254. return new CellExpressionToken(CellExpressionTokenType.Number, numStr);
  1255. }
  1256. /**
  1257. * @param {string} text
  1258. * @param {number[]} pos
  1259. * @returns {CellExpressionToken|null}
  1260. */
  1261. static #readNextStringToken(text, pos) {
  1262. var ch = text.substring(pos[0], pos[0] + 1);
  1263. if (ch !== '"') return null;
  1264. var str = '';
  1265. pos[0]++;
  1266. const l = text.length;
  1267. var inEscape = false;
  1268. while (pos[0] < l) {
  1269. ch = text.substring(pos[0], pos[0] + 1);
  1270. pos[0]++;
  1271. if (inEscape) {
  1272. inEscape = false;
  1273. if (ch == '\\' || ch == '"') {
  1274. str += ch;
  1275. } else {
  1276. throw new CellSyntaxException(`Bad string escape sequence "\\${ch}"`);
  1277. }
  1278. } else if (ch == '\\') {
  1279. inEscape = true;
  1280. } else if (ch == '"') {
  1281. return new CellExpressionToken(CellExpressionTokenType.String, str);
  1282. } else {
  1283. str += ch;
  1284. }
  1285. }
  1286. throw new CellSyntaxException('Unterminated string');
  1287. }
  1288. /**
  1289. * Reads the next chars that pass a test function and returns the result.
  1290. * @param {string} text
  1291. * @param {number[]} pos
  1292. * @param {function} charTest
  1293. * @param {number|null} minimumLength
  1294. * @param {number|null} maximumLength
  1295. * @returns {string|null}
  1296. */
  1297. static #readChars(text, pos, charTest, minimumLength = null, maximumLength = null) {
  1298. var p = pos[0];
  1299. const l = text.length;
  1300. var s = '';
  1301. var sl = 0;
  1302. while (p < l && (maximumLength === null || sl < maximumLength)) {
  1303. const ch = text.substring(p, p + 1);
  1304. if (!charTest(ch)) break;
  1305. s += ch;
  1306. sl++;
  1307. p++;
  1308. }
  1309. if (p < l && charTest(text.substring(p, p + 1))) {
  1310. return null;
  1311. }
  1312. if (minimumLength !== null && sl < minimumLength) {
  1313. return null;
  1314. }
  1315. pos[0] = p;
  1316. return s;
  1317. }
  1318. /**
  1319. * @param {string} ch
  1320. * @returns {boolean}
  1321. */
  1322. static #isLetter(ch) {
  1323. const ord = ch.codePointAt(0);
  1324. return (ord >= 65 && ord <= 90) || (ord >= 97 && ord <= 122);
  1325. }
  1326. /**
  1327. * @param {string} ch
  1328. * @returns {boolean}
  1329. */
  1330. static #isDigit(ch) {
  1331. const ord = ch.codePointAt(0);
  1332. return (ord >= 48 && ord <= 57);
  1333. }
  1334. // -- Parsing -----------------------------------------------------------
  1335. /**
  1336. * @param {Array} tokens
  1337. * @param {CellAddress} address
  1338. * @returns {CellExpression|null}
  1339. */
  1340. static expressionFromTokens(tokens, address) {
  1341. var expr;
  1342. if (expr = this.#tryExpressionAndFormat(tokens, 0, tokens.length - 1, address)) return expr;
  1343. if (expr = this.#tryExpressionAndFill(tokens, 0, tokens.length - 1, address)) return expr;
  1344. if (expr = this.#tryExpression(tokens, 0, tokens.length - 1, address)) return expr;
  1345. return null;
  1346. }
  1347. /**
  1348. * @param {Array} tokens
  1349. * @param {number} start
  1350. * @param {number} end
  1351. * @param {CellAddress} address
  1352. * @returns {CellExpression|null}
  1353. */
  1354. static #tryExpressionAndFormat(tokens, start, end, address) {
  1355. for (var t = start + 1; t < end; t++) {
  1356. if (tokens[t].type == CellExpressionTokenType.Semicolon) {
  1357. const expr = this.#tryExpressionAndFill(tokens, start, t - 1, address) ??
  1358. this.#tryExpression(tokens, start, t - 1, address);
  1359. if (expr === null) return null;
  1360. const format = this.#tryFormat(tokens, t + 1, end, address);
  1361. if (format === null) return null;
  1362. [ expr.outputType, expr.outputDecimals ] = format;
  1363. return expr;
  1364. }
  1365. }
  1366. return null;
  1367. }
  1368. /**
  1369. * @param {CellExpressionToken[]} tokens
  1370. * @param {number} start
  1371. * @param {number} end
  1372. * @param {CellAddress} address
  1373. * @returns {CellExpression|null}
  1374. */
  1375. static #tryExpressionAndFill(tokens, start, end, address) {
  1376. var count = end - start + 1;
  1377. if (count < 2) return null;
  1378. if (!tokens[end].type.isPotentialName()) return null;
  1379. var name = tokens[end].content.toUpperCase();
  1380. if (name != 'FILL') return null;
  1381. const exp = this.#tryExpression(tokens, start, end - 1, address);
  1382. const columnIndex = address.columnIndex;
  1383. exp.fillRanges = [
  1384. new CellAddressRange(new CellAddress(columnIndex, address.rowIndex), new CellAddress(columnIndex, 999999)),
  1385. ];
  1386. return exp;
  1387. }
  1388. /**
  1389. * Tries to parse a format suffix after a semicolon. Examples:
  1390. *
  1391. * ```
  1392. * ; number
  1393. * ; number 3
  1394. * ; currency 2
  1395. * ; percent 0
  1396. * ```
  1397. *
  1398. * @param {CellExpressionToken[]} tokens
  1399. * @param {number} start
  1400. * @param {number} end
  1401. * @param {CellAddress} address
  1402. * @return {any[]} CellValue type and decimal places
  1403. */
  1404. static #tryFormat(tokens, start, end, address) {
  1405. const count = end - start + 1;
  1406. if (count < 0 || count > 2) return null;
  1407. if (!tokens[start].type.isPotentialName()) return null;
  1408. const type = tokens[start].content.toLowerCase();
  1409. if (!CellValue.isTypeNumeric(type)) return null;
  1410. var decimals;
  1411. if (count > 1) {
  1412. if (tokens[start + 1].type != CellExpressionTokenType.Number) return null;
  1413. decimals = parseInt(tokens[start + 1].content);
  1414. } else {
  1415. decimals = null;
  1416. }
  1417. return [ type, decimals ];
  1418. }
  1419. /**
  1420. * @param {CellExpressionToken[]} tokens
  1421. * @param {number} start
  1422. * @param {number} end
  1423. * @param {CellAddress} address
  1424. * @returns {CellExpression}
  1425. */
  1426. static #tryExpression(tokens, start, end, address) {
  1427. var expr;
  1428. if (expr = this.#tryParenExpression(tokens, start, end, address)) return expr;
  1429. if (expr = this.#tryNumber(tokens, start, end, address)) return expr;
  1430. if (expr = this.#tryString(tokens, start, end, address)) return expr;
  1431. if (expr = this.#tryBoolean(tokens, start, end, address)) return expr;
  1432. if (expr = this.#tryFunction(tokens, start, end, address)) return expr;
  1433. if (expr = this.#tryRange(tokens, start, end, address)) return expr;
  1434. if (expr = this.#tryReference(tokens, start, end, address)) return expr;
  1435. if (expr = this.#tryInfix(tokens, start, end, address)) return expr;
  1436. if (expr = this.#tryUnary(tokens, start, end, address)) return expr;
  1437. throw new CellSyntaxException("Invalid expression");
  1438. }
  1439. /**
  1440. * @param {CellExpressionToken[]} tokens
  1441. * @param {number} start
  1442. * @param {number} end
  1443. * @param {CellAddress} address
  1444. * @returns {CellExpression|null}
  1445. */
  1446. static #tryParenExpression(tokens, start, end, address) {
  1447. if (tokens[start].type != CellExpressionTokenType.OpenParen) return null;
  1448. if (tokens[end].type != CellExpressionTokenType.CloseParen) return null;
  1449. var parenLevel = 0;
  1450. for (var t = start + 1; t < end; t++) {
  1451. if (tokens[t].type == CellExpressionTokenType.OpenParen) {
  1452. parenLevel++;
  1453. } else if (tokens[t].type == CellExpressionTokenType.CloseParen) {
  1454. parenLevel--;
  1455. }
  1456. if (parenLevel < 0) return null;
  1457. }
  1458. if (parenLevel != 0) return null;
  1459. return this.#tryExpression(tokens, start + 1, end - 1, address);
  1460. }
  1461. /**
  1462. * @param {CellExpressionToken[]} tokens
  1463. * @param {number} start
  1464. * @param {number} end
  1465. * @param {CellAddress} address
  1466. * @returns {CellExpression|null}
  1467. */
  1468. static #tryNumber(tokens, start, end, address) {
  1469. if (tokens[end].type != CellExpressionTokenType.Number) return null;
  1470. if (end > start + 1) return null;
  1471. const val = CellValue.fromCellString(tokens[end].content);
  1472. if (end > start) {
  1473. if (tokens[start].type != CellExpressionTokenType.Minus) return null;
  1474. val.value = -val.value;
  1475. }
  1476. return new CellExpression(CellExpressionOperation.Number, [ val ]);
  1477. }
  1478. /**
  1479. * @param {CellExpressionToken[]} tokens
  1480. * @param {number} start
  1481. * @param {number} end
  1482. * @param {CellAddress} address
  1483. * @returns {CellExpression|null}
  1484. */
  1485. static #tryString(tokens, start, end, address) {
  1486. if (start != end) return null;
  1487. if (tokens[start].type != CellExpressionTokenType.String) return null;
  1488. const str = tokens[start].content;
  1489. return new CellExpression(CellExpressionOperation.String, [ new CellValue(str, str, CellValue.TYPE_STRING, 0) ]);
  1490. }
  1491. /**
  1492. * @param {CellExpressionToken[]} tokens
  1493. * @param {number} start
  1494. * @param {number} end
  1495. * @param {CellAddress} address
  1496. * @returns {CellExpression|null}
  1497. */
  1498. static #tryBoolean(tokens, start, end, address) {
  1499. if (start != end) return null;
  1500. if (!tokens[start].type.isPotentialName()) return null;
  1501. const str = tokens[start].content.toUpperCase();
  1502. if (str != 'TRUE' && str != 'FALSE') return null;
  1503. return new CellExpression(CellExpressionOperation.Boolean, [ new CellValue(str, str == 'TRUE', CellValue.TYPE_BOOLEAN) ]);
  1504. }
  1505. /**
  1506. * @param {CellExpressionToken[]} tokens
  1507. * @param {number} start
  1508. * @param {number} end
  1509. * @param {CellAddress} address
  1510. * @returns {CellExpression|null}
  1511. */
  1512. static #tryFunction(tokens, start, end, address) {
  1513. const count = end - start + 1;
  1514. if (count < 3) return null;
  1515. if (!tokens[start].type.isPotentialName()) return null;
  1516. const qualifier = tokens[start].content;
  1517. if (tokens[start + 1].type != CellExpressionTokenType.OpenParen) return null;
  1518. if (tokens[end].type != CellExpressionTokenType.CloseParen) return null;
  1519. const argList = this.#tryArgumentList(tokens, start + 2, end - 1, address);
  1520. if (argList === null) return null;
  1521. return new CellExpression(CellExpressionOperation.Function, argList, qualifier);
  1522. }
  1523. /**
  1524. * @param {CellExpressionToken[]} tokens
  1525. * @param {number} start
  1526. * @param {number} end
  1527. * @param {CellAddress} address
  1528. * @returns {CellExpression[]|null}
  1529. */
  1530. static #tryArgumentList(tokens, start, end, address) {
  1531. const count = end - start + 1;
  1532. if (count == 0) return [];
  1533. var parenDepth = 0;
  1534. const argCount = 1;
  1535. // Populate argTokens with tuples of start and end token indices for each arg.
  1536. /** @type {int[][]} */
  1537. var argTokens = []; // argindex -> [ start, end ]
  1538. var exprStartToken = start;
  1539. for (var i = start; i <= end; i++) {
  1540. if (tokens[i].type == CellExpressionTokenType.OpenParen) {
  1541. parenDepth++;
  1542. } else if (tokens[i].type == CellExpressionTokenType.CloseParen) {
  1543. parenDepth--;
  1544. } else if (tokens[i].type == CellExpressionTokenType.Comma && parenDepth == 0) {
  1545. const exprEndToken = i - 1;
  1546. argTokens.push([ exprStartToken, exprEndToken ]);
  1547. exprStartToken = i + 1;
  1548. }
  1549. }
  1550. argTokens.push([ exprStartToken, end ]);
  1551. // Convert token ranges to expressions
  1552. var args = [];
  1553. for (const argToken of argTokens) {
  1554. const arg = this.#tryExpression(tokens, argToken[0], argToken[1], address);
  1555. if (arg === null) return null;
  1556. args.push(arg);
  1557. }
  1558. return args;
  1559. }
  1560. /**
  1561. * @param {CellExpressionToken[]} tokens
  1562. * @param {number} start
  1563. * @param {number} end
  1564. * @param {CellAddress} address
  1565. * @returns {CellExpression|null}
  1566. */
  1567. static #tryRange(tokens, start, end, address) {
  1568. const count = end - start + 1;
  1569. if (count != 3) return null;
  1570. if (!tokens[start].type.isPotentialAddress()) return null;
  1571. const first = tokens[start].content.toUpperCase();
  1572. if (tokens[start + 1].type != CellExpressionTokenType.Colon) return null;
  1573. if (!tokens[end].type.isPotentialAddress()) return null;
  1574. const last = tokens[end].content.toUpperCase();
  1575. const firstAddress = CellAddress.fromString(first);
  1576. const lastAddress = CellAddress.fromString(last);
  1577. const range = new CellAddressRange(firstAddress, lastAddress);
  1578. return new CellExpression(CellExpressionOperation.Range, [ range ]);
  1579. }
  1580. /**
  1581. * @param {CellExpressionToken[]} tokens
  1582. * @param {number} start
  1583. * @param {number} end
  1584. * @param {CellAddress} address
  1585. * @returns {CellExpression|null}
  1586. */
  1587. static #tryReference(tokens, start, end, address) {
  1588. if (start != end) return null;
  1589. if (!tokens[start].type.isPotentialAddress()) return null;
  1590. const ref = tokens[start].content.toUpperCase();
  1591. const refAddress = CellAddress.fromString(ref, address, true);
  1592. if (refAddress === null) return null;
  1593. return new CellExpression(CellExpressionOperation.Reference, [ refAddress ]);
  1594. }
  1595. static #infixPriority = {};
  1596. static {
  1597. this.#infixPriority[CellExpressionTokenType.Minus.name] = 1;
  1598. this.#infixPriority[CellExpressionTokenType.Plus.name] = 2;
  1599. this.#infixPriority[CellExpressionTokenType.Divide.name] = 3;
  1600. this.#infixPriority[CellExpressionTokenType.Multiply.name] = 4;
  1601. this.#infixPriority[CellExpressionTokenType.Ampersand.name] = 10;
  1602. this.#infixPriority[CellExpressionTokenType.GreaterThan.name] = 20;
  1603. this.#infixPriority[CellExpressionTokenType.GreaterThanEqual.name] = 20;
  1604. this.#infixPriority[CellExpressionTokenType.LessThan.name] = 20;
  1605. this.#infixPriority[CellExpressionTokenType.LessThanEqual.name] = 20;
  1606. this.#infixPriority[CellExpressionTokenType.Equal.name] = 20;
  1607. this.#infixPriority[CellExpressionTokenType.Unequal.name] = 20;
  1608. }
  1609. /**
  1610. * @param {CellExpressionToken[]} tokens
  1611. * @param {number} start
  1612. * @param {number} end
  1613. * @param {CellAddress} address
  1614. * @returns {CellExpression|null}
  1615. */
  1616. static #tryInfix(tokens, start, end, address) {
  1617. const count = end - start + 1;
  1618. if (count < 3) return null;
  1619. var candidates = [];
  1620. var parenLevel = 0;
  1621. var i;
  1622. for (i = start; i <= end; i++) {
  1623. if (tokens[i].type == CellExpressionTokenType.OpenParen) {
  1624. parenLevel++;
  1625. } else if (tokens[i].type == CellExpressionTokenType.CloseParen) {
  1626. parenLevel--;
  1627. } else if (parenLevel == 0 && i > start && i < end) {
  1628. const op = tokens[i].type.name;
  1629. const priority = this.#infixPriority[op] ?? false;
  1630. if (priority === false) continue;
  1631. candidates.push({ priority: priority, i: i });
  1632. }
  1633. }
  1634. candidates.sort((a, b) => a.priority - b.priority);
  1635. var bestCandidate = null;
  1636. var operand1, operand2;
  1637. for (const candidate of candidates) {
  1638. try {
  1639. i = candidate.i;
  1640. operand1 = this.#tryExpression(tokens, start, i - 1, address);
  1641. if (operand1 === null) continue;
  1642. operand2 = this.#tryExpression(tokens, i + 1, end, address);
  1643. if (operand2 === null) continue;
  1644. bestCandidate = candidate;
  1645. break;
  1646. } catch (e) {
  1647. if (!(e instanceof CellSyntaxException)) {
  1648. throw e;
  1649. }
  1650. }
  1651. }
  1652. if (bestCandidate === null) {
  1653. return null;
  1654. }
  1655. i = bestCandidate.i;
  1656. switch (tokens[bestCandidate.i].type) {
  1657. case CellExpressionTokenType.Plus:
  1658. return new CellExpression(CellExpressionOperation.Add, [ operand1, operand2 ]);
  1659. case CellExpressionTokenType.Minus:
  1660. return new CellExpression(CellExpressionOperation.Subtract, [ operand1, operand2 ]);
  1661. case CellExpressionTokenType.Multiply:
  1662. return new CellExpression(CellExpressionOperation.Multiply, [ operand1, operand2 ]);
  1663. case CellExpressionTokenType.Divide:
  1664. return new CellExpression(CellExpressionOperation.Divide, [ operand1, operand2 ]);
  1665. case CellExpressionTokenType.GreaterThan:
  1666. return new CellExpression(CellExpressionOperation.GreaterThan, [ operand1, operand2 ]);
  1667. case CellExpressionTokenType.GreaterThanEqual:
  1668. return new CellExpression(CellExpressionOperation.GreaterThanEqual, [ operand1, operand2 ]);
  1669. case CellExpressionTokenType.LessThan:
  1670. return new CellExpression(CellExpressionOperation.LessThan, [ operand1, operand2 ]);
  1671. case CellExpressionTokenType.LessThanEqual:
  1672. return new CellExpression(CellExpressionOperation.LessThanEqual, [ operand1, operand2 ]);
  1673. case CellExpressionTokenType.Equal:
  1674. return new CellExpression(CellExpressionOperation.Equal, [ operand1, operand2 ]);
  1675. case CellExpressionTokenType.Unequal:
  1676. return new CellExpression(CellExpressionOperation.Unequal, [ operand1, operand2 ]);
  1677. case CellExpressionTokenType.Ampersand:
  1678. return new CellExpression(CellExpressionOperation.Concatenate, [ operand1, operand2 ]);
  1679. }
  1680. return null;
  1681. }
  1682. /**
  1683. * @param {CellExpressionToken[]} tokens
  1684. * @param {number} start
  1685. * @param {number} end
  1686. * @param {CellAddress} address
  1687. * @returns {CellExpression|null}
  1688. */
  1689. static #tryUnary(tokens, start, end, address) {
  1690. const count = end - start + 1;
  1691. if (count < 2) return null;
  1692. const ops = [
  1693. [ CellExpressionTokenType.Minus, CellExpressionOperation.UnaryMinus ],
  1694. [ CellExpressionTokenType.Not, CellExpressionOperation.UnaryNot ],
  1695. ];
  1696. for (const op of ops) {
  1697. if (tokens[start].type != op[0]) continue;
  1698. const operand = this.#tryExpression(tokens, start + 1, end, address);
  1699. if (operand === null) return null;
  1700. return new CellExpression(op[1], [ operand ]);
  1701. }
  1702. return null;
  1703. }
  1704. }
  1705. /**
  1706. * Parsing token for an expression.
  1707. */
  1708. class CellExpressionToken {
  1709. /** @type {CellExpressionTokenType} */
  1710. type;
  1711. /** @type {string} */
  1712. content;
  1713. /**
  1714. * @param {CellExpressionTokenType} type
  1715. * @param {string} content
  1716. */
  1717. constructor(type, content) {
  1718. this.type = type;
  1719. this.content = content;
  1720. }
  1721. }
  1722. /**
  1723. * The location of a cell in a table. If the address was specified without a
  1724. * row, the address is considered "unresolved" and needs more context to
  1725. * uniquely identify a cell.
  1726. */
  1727. class CellAddress {
  1728. /**
  1729. * @type {string}
  1730. */
  1731. get name() { return this.#name; }
  1732. #name;
  1733. /**
  1734. * Whether the column should remain unchanged when transposed. This is
  1735. * symbolized by prefixing the column name with a `$` (e.g. `$C3`).
  1736. * @type {boolean}
  1737. */
  1738. get isColumnFixed() { return this.#isColumnFixed; }
  1739. #isColumnFixed = false;
  1740. /**
  1741. * Zero-based column index.
  1742. * @type {number}
  1743. */
  1744. get columnIndex() { return this.#columnIndex; };
  1745. #columnIndex = -1;
  1746. /**
  1747. * Letter code for the column.
  1748. * @type {string}
  1749. */
  1750. get columnLetter() { return CellAddress.#columnIndexToLetters(this.#columnIndex); }
  1751. /**
  1752. * Whether the row should remain unchanged when transposed. This is
  1753. * symbolized by prefixing the row number with a `$` (e.g. `C$3`).
  1754. * @type {boolean}
  1755. */
  1756. get isRowFixed() { return this.#isRowFixed; }
  1757. #isRowFixed = false;
  1758. /**
  1759. * Zero-based row index.
  1760. * @type {number}
  1761. */
  1762. get rowIndex() { return this.#rowIndex; }
  1763. #rowIndex = -1;
  1764. /**
  1765. * One-based row number. This is the human-facing row number.
  1766. */
  1767. get rowNumber() { return this.#rowIndex + 1; }
  1768. /**
  1769. * Whether this address has both a definite column and row.
  1770. * @type {boolean}
  1771. */
  1772. get isResolved() { return this.columnIndex >= 0 && this.rowIndex >= 0; }
  1773. /**
  1774. * @param {number} columnIndex - 0-based column index
  1775. * @param {number} rowIndex - 0-based row index
  1776. * @param {boolean} isColumnFixed - whether the column name is fixed in
  1777. * place during transpositions. Denoted with a `$` in front of the column letters.
  1778. * @param {boolean} isRowFixed - whether the row number is fixed in place
  1779. * during transpositions. Denoted with a `$` in front of the row digits.
  1780. */
  1781. constructor(columnIndex, rowIndex, isColumnFixed=false, isRowFixed=false) {
  1782. if (typeof columnIndex != 'number') {
  1783. throw new Error(`columnIndex must be number, got ${typeof columnIndex}`);
  1784. }
  1785. if (typeof rowIndex != 'number') {
  1786. throw new Error(`rowIndex must be number, got ${typeof rowIndex}`);
  1787. }
  1788. this.#columnIndex = columnIndex;
  1789. this.#rowIndex = rowIndex;
  1790. this.#isColumnFixed = isColumnFixed;
  1791. this.#isRowFixed = isRowFixed;
  1792. this.#name = CellAddress.#formatAddress(columnIndex, rowIndex, isColumnFixed, isRowFixed);
  1793. }
  1794. /**
  1795. * Tests if a string is formatted like an address.
  1796. *
  1797. * @param {string} text
  1798. * @returns {boolean}
  1799. */
  1800. static isAddress(text) {
  1801. return this.fromString(text) != null;
  1802. }
  1803. /**
  1804. * Returns a converted form of this address reference in a formula that has
  1805. * been copied from its original location. In other words, if a formula
  1806. * refers to a cell one to the left and that formula is copied to the next
  1807. * cell down, that copy's reference should point to the cell on the next
  1808. * row as well. Addresses with an absolute column or row (e.g. "A5") will
  1809. * not be altered on that axis.
  1810. *
  1811. * Examples:
  1812. * - C6.transpose(A5, A9) = C10 (A9-A5 = +4 rows, C6 + 4 rows = C10)
  1813. * - C6.transpose(A5, B9) = D10 (B9-A5 = +4 rows +1 cols, C6 + 4 rows + 1
  1814. * col = D10)
  1815. * - C$6.transpose(A5, A9) = C6 (A9-A5 = +4 rows, but row is fixed, so
  1816. * still C6)
  1817. * - B.transpose(A5, A9) = B9 (A9-A4 = +4 rows, B has no row so last row
  1818. * used = B9)
  1819. * - A1.transpose(C3, A1) = null (out of bounds)
  1820. *
  1821. * @param {CellAddress} relativeFrom - original address of the formula
  1822. * @param {CellAddress} relativeTo - address where the formula is being
  1823. * repeated
  1824. * @param {boolean} resolveToRow - whether to fill in a row number if this
  1825. * address doesn't have one
  1826. * @returns {CellAddress|null} - resolved address, or `null` if out of bounds
  1827. */
  1828. transpose(relativeFrom, relativeTo, resolveToRow = true) {
  1829. if (!relativeFrom.isResolved || !relativeTo.isResolved) {
  1830. throw new CellEvaluationException("Can only transpose to and from resolved addresses");
  1831. }
  1832. var newColumnIndex = this.columnIndex;
  1833. if (!this.isColumnFixed) {
  1834. const columnDelta = relativeTo.columnIndex - relativeFrom.columnIndex;
  1835. newColumnIndex += columnDelta;
  1836. }
  1837. var newRowIndex = this.rowIndex;
  1838. if (!this.isResolved && resolveToRow) {
  1839. newRowIndex = relativeFrom.rowIndex;
  1840. }
  1841. if (newRowIndex != -1 && !this.isRowFixed) {
  1842. const rowDelta = relativeTo.rowIndex - relativeFrom.rowIndex;
  1843. newRowIndex += rowDelta;
  1844. }
  1845. if (newColumnIndex < 0 || newRowIndex < 0) return null;
  1846. return new CellAddress(newColumnIndex, newRowIndex);
  1847. }
  1848. equals(other) {
  1849. if (!(other instanceof CellAddress)) return false;
  1850. return other.columnIndex == this.columnIndex && other.rowIndex == this.rowIndex;
  1851. }
  1852. exactlyEquals(other) {
  1853. if (!(other instanceof CellAddress)) return false;
  1854. return other.name == this.name;
  1855. }
  1856. toString() {
  1857. return this.name;
  1858. }
  1859. /**
  1860. * Converts column letters (e.g. `A`, `C`, `AA`) to a 0-based column index.
  1861. * Assumes a validated well-formed column letter or else behavior is undefined.
  1862. *
  1863. * @param {string} letters
  1864. * @returns {number} column index
  1865. */
  1866. static #lettersToColumnIndex(letters) {
  1867. const ACodepoint = 'A'.codePointAt(0);
  1868. var columnIndex = 0;
  1869. for (var i = letters.length - 1; i >= 0; i--) {
  1870. const letterIndex = letters.codePointAt(i) - ACodepoint;
  1871. columnIndex = columnIndex * 26 + letterIndex;
  1872. }
  1873. return columnIndex;
  1874. }
  1875. /**
  1876. * Converts a column index to column letters (e.g. index 0 = `A`).
  1877. *
  1878. * @param {number} columnIndex
  1879. * @returns {string}
  1880. */
  1881. static #columnIndexToLetters(columnIndex) {
  1882. var letters = '';
  1883. if (columnIndex >= 0) {
  1884. const ACodepoint = 'A'.codePointAt(0);
  1885. var remaining = columnIndex;
  1886. do {
  1887. letters = String.fromCodePoint(ACodepoint + (remaining % 26)) + letters;
  1888. remaining = Math.floor(remaining / 26);
  1889. } while (remaining > 0);
  1890. }
  1891. return letters;
  1892. }
  1893. static #formatAddress(columnIndex, rowIndex, isColumnFixed, isRowFixed) {
  1894. var addr = '';
  1895. if (isColumnFixed && columnIndex >= 0) addr += '$';
  1896. if (columnIndex >= 0) addr += this.#columnIndexToLetters(columnIndex);
  1897. if (isRowFixed && rowIndex >= 0) addr += '$';
  1898. if (rowIndex >= 0) addr += `${rowIndex + 1}`;
  1899. return addr;
  1900. }
  1901. /**
  1902. * Attempts to convert a cell address string to a `CellAddress`.
  1903. *
  1904. * @param {string} address - cell address string
  1905. * @param {CellAddress|null} relativeTo - address to resolve relative
  1906. * addresses against
  1907. * @param {boolean} throwIfInvalid - whether to throw an error if address
  1908. * is invalid
  1909. * @returns {CellAddress|null} address, if parsable
  1910. * @throws {CellEvaluationException} if the address is invalid and
  1911. * `throwIfInvalid` is `true`
  1912. */
  1913. static fromString(address, relativeTo=null, throwIfInvalid=false) {
  1914. const groups = /^(\$?)([A-Z]{1,2}?)((?:\$(?=[0-9]))?)([0-9]*)$/i.exec(address);
  1915. if (groups === null) {
  1916. if (throwIfInvalid) throw new CellEvaluationException(`Bad address "${address}"`, '#REF');
  1917. return null;
  1918. }
  1919. const isColumnFixed = groups[1] == '$';
  1920. const letters = groups[2].toUpperCase();
  1921. const isRowFixed = groups[3] == '$';
  1922. const numbers = groups[4];
  1923. var columnIndex = this.#lettersToColumnIndex(letters);
  1924. var rowIndex = (numbers.length == 0) ? -1 : parseInt(numbers) - 1;
  1925. if (columnIndex < 0 && relativeTo != null) columnIndex = relativeTo.columnIndex;
  1926. if (rowIndex < 0 && relativeTo != null) rowIndex = relativeTo.rowIndex;
  1927. return new CellAddress(columnIndex, rowIndex, isColumnFixed, isRowFixed);
  1928. }
  1929. }
  1930. /**
  1931. * Range of cells addresses. Can be iterated via `cellsIn`.
  1932. */
  1933. class CellAddressRange {
  1934. /** @type {boolean} */
  1935. isResolved;
  1936. /** @type {number} */
  1937. minColumnIndex;
  1938. /** @type {number} */
  1939. maxColumnIndex;
  1940. /** @type {number} */
  1941. minRowIndex;
  1942. /** @type {number} */
  1943. maxRowIndex;
  1944. /** @type {string} */
  1945. name;
  1946. /**
  1947. * Creates a rectangular range between two corner cells. They can be in
  1948. * any order. The given cells must either both be resolved or both unresolved.
  1949. *
  1950. * @param {CellAddress} fromCell
  1951. * @param {CellAddress} toCell
  1952. */
  1953. constructor(fromCell, toCell) {
  1954. if (fromCell.isResolved != toCell.isResolved) {
  1955. throw new CellEvaluationException(`Cannot mix resolved and unresolved cell addresses in range: ${fromCell.name} and ${toCell.name}`);
  1956. }
  1957. this.minColumnIndex = Math.min(fromCell.columnIndex, toCell.columnIndex);
  1958. this.maxColumnIndex = Math.max(fromCell.columnIndex, toCell.columnIndex);
  1959. this.minRowIndex = Math.min(fromCell.rowIndex, toCell.rowIndex);
  1960. this.maxRowIndex = Math.max(fromCell.rowIndex, toCell.rowIndex);
  1961. this.isResolved = fromCell.isResolved;
  1962. this.name = (new CellAddress(this.minColumnIndex, this.minRowIndex)).name +
  1963. ':' +
  1964. (new CellAddress(this.maxColumnIndex, this.maxRowIndex)).name;
  1965. }
  1966. /**
  1967. * Creates an iterator for every `CellAddress` in this range within the
  1968. * confines of the given grid's dimensions. Iterates each row in the first
  1969. * column, then each row in the second, etc. Iteration range is inclusive
  1970. * of the min and max extents.
  1971. *
  1972. * Example:
  1973. * ```
  1974. * for (const address of range.cellsIn(grid)) {
  1975. * ...
  1976. * }
  1977. * ```
  1978. *
  1979. * @param {SpreadsheetGrid} grid
  1980. * @returns {object} iterable object
  1981. */
  1982. cellsIn(grid) {
  1983. const minCol = this.minColumnIndex < 0 ? 0 : this.minColumnIndex;
  1984. const maxCol = this.maxColumnIndex < 0 ? grid.columnCount - 1
  1985. : Math.min(this.maxColumnIndex, grid.columnCount - 1);
  1986. const minRow = this.minRowIndex < 0 ? 0 : this.minRowIndex;
  1987. const maxRow = this.maxRowIndex < 0 ? grid.rowCount - 1
  1988. : Math.min(this.maxRowIndex, grid.rowCount - 1);
  1989. const iterable = {};
  1990. iterable[Symbol.iterator] = function() {
  1991. var currentCol = minCol;
  1992. var currentRow = minRow;
  1993. return {
  1994. next() {
  1995. const col = currentCol;
  1996. const row = currentRow++;
  1997. if (currentRow > maxRow) {
  1998. currentRow = minRow;
  1999. currentCol++;
  2000. }
  2001. return {
  2002. value: new CellAddress(col, row),
  2003. done: col > maxCol || row > maxRow,
  2004. };
  2005. }
  2006. };
  2007. };
  2008. return iterable;
  2009. }
  2010. }
  2011. /**
  2012. * A value in a spreadsheet or calculation.
  2013. */
  2014. class CellValue {
  2015. /**
  2016. * Blank cell. `value` is `null`.
  2017. */
  2018. static TYPE_BLANK = 'blank';
  2019. /**
  2020. * Currency value. `value` is `number`.
  2021. */
  2022. static TYPE_CURRENCY = 'currency';
  2023. /**
  2024. * Regular number value. `value` is `number`.
  2025. */
  2026. static TYPE_NUMBER = 'number';
  2027. /**
  2028. * Percentage. `value` is `number`, represented as a ratio (100% = 1.0).
  2029. */
  2030. static TYPE_PERCENT = 'percent';
  2031. /**
  2032. * Unaltered text value. `value` is `string`.
  2033. */
  2034. static TYPE_STRING = 'string';
  2035. /**
  2036. * Boolean. `value` is `boolean`.
  2037. */
  2038. static TYPE_BOOLEAN = 'boolean';
  2039. /**
  2040. * A formula that has resulted in an error during parsing or evaluation.
  2041. * `value` is `string` error message.
  2042. */
  2043. static TYPE_ERROR = 'error';
  2044. /**
  2045. * A formula expression. `value` is `string` and includes the leading `=`.
  2046. */
  2047. static TYPE_FORMULA = 'formula';
  2048. // -- Properties -----
  2049. /**
  2050. * A blank value.
  2051. * @type {CellValue}
  2052. */
  2053. static BLANK = new CellValue('', null, CellValue.TYPE_BLANK);
  2054. /**
  2055. * Type of value. One of the `TYPE_` constants.
  2056. * @type {string}
  2057. */
  2058. type = CellValue.TYPE_STRING;
  2059. /**
  2060. * Number of decimal places shown in the formatted value.
  2061. * @type {number}
  2062. */
  2063. decimals = 0;
  2064. /**
  2065. * The string shown in the table cell to the user.
  2066. * @type {string}
  2067. */
  2068. formattedValue = '';
  2069. /**
  2070. * The PHP data value. E.g. a `float` for currency values or an `Exception`
  2071. * for errors.
  2072. * @type {any}
  2073. */
  2074. value = null;
  2075. /**
  2076. * Constructs a cell value explicitly. Values are not validated. Consider
  2077. * using `.fromCellString()` or `.fromValue()` to populate values more
  2078. * intelligently and consistently.
  2079. *
  2080. * @param {string} formattedValue
  2081. * @param {any} value
  2082. * @param {string} type
  2083. * @param {number} decimals
  2084. */
  2085. constructor(
  2086. formattedValue,
  2087. value = null,
  2088. type = CellValue.TYPE_STRING,
  2089. decimals = 0
  2090. ) {
  2091. this.formattedValue = formattedValue;
  2092. this.value = value;
  2093. this.type = type;
  2094. this.decimals = decimals;
  2095. }
  2096. /**
  2097. * Returns whether this value is a numeric type.
  2098. *
  2099. * @returns {boolean}
  2100. */
  2101. isNumeric() {
  2102. return CellValue.isTypeNumeric(this.type);
  2103. }
  2104. /**
  2105. * Creates a CellValue from formatted table cell contents. Attempts to
  2106. * detect formatted numbers including currency and percentages.
  2107. *
  2108. * @param {string} cellString
  2109. * @returns {CellValue}
  2110. */
  2111. static fromCellString(cellString) {
  2112. const cv = new CellValue(cellString);
  2113. cv.#populateFromCellString(cellString);
  2114. return cv;
  2115. }
  2116. /**
  2117. * Creates a CellValue from a value. Based off datatype, not string
  2118. * formatting; use `fromCellString` to parse formatted numbers.
  2119. *
  2120. * @param {any} value
  2121. * @param {string|null} type - optional forced type
  2122. * @param {number|null} decimals - optional number of decimal places to format to
  2123. * @returns {CellValue}
  2124. * @throws {CellEvaluationException} if `value` is of an unsupported type
  2125. */
  2126. static fromValue(value, type = null, decimals = null) {
  2127. if (value === null) {
  2128. return new CellValue('', null, CellValue.TYPE_BLANK);
  2129. }
  2130. if (value instanceof Error) {
  2131. if (value instanceof CellException) {
  2132. return new CellValue(value.errorSymbol, value.message, CellValue.TYPE_ERROR);
  2133. }
  2134. return new CellValue('#ERROR', value.message, CellValue.TYPE_ERROR);
  2135. }
  2136. if (typeof value == 'boolean') {
  2137. const formatted = CellValue.formatType(value, CellValue.TYPE_BOOLEAN, 0);
  2138. return new CellValue(formatted, value, CellValue.TYPE_BOOLEAN);
  2139. }
  2140. if (typeof value == 'number') {
  2141. const resolvedType = type || CellValue.TYPE_NUMBER;
  2142. const resolvedDecimals = (decimals !== null) ? decimals :
  2143. (resolvedType == CellValue.TYPE_CURRENCY ? 2 : CellValue.#autodecimals(resolvedType == CellValue.TYPE_PERCENT ? value * 100.0 : value));
  2144. const formatted = CellValue.formatType(value, resolvedType, resolvedDecimals);
  2145. return new CellValue(formatted, value, resolvedType, resolvedDecimals);
  2146. }
  2147. if (typeof value != 'string') {
  2148. throw new CellEvaluationException(`Value of type ${typeof value} unsupported`);
  2149. }
  2150. const trimmed = value.trim();
  2151. if (trimmed.startsWith('=')) {
  2152. return new CellValue(trimmed, trimmed, CellValue.TYPE_FORMULA);
  2153. }
  2154. return new CellValue(trimmed, trimmed, CellValue.TYPE_STRING);
  2155. }
  2156. /**
  2157. * @param {string|null} cellString
  2158. */
  2159. #populateFromCellString(cellString) {
  2160. cellString = (cellString !== null) ? cellString.trim() : null;
  2161. this.formattedValue = cellString;
  2162. // blank
  2163. if (cellString === null || cellString == '') {
  2164. this.type = CellValue.TYPE_BLANK;
  2165. this.value = null;
  2166. return;
  2167. }
  2168. // 'literal
  2169. if (cellString.startsWith("'")) {
  2170. const stripped = cellString.substring(1).trim();
  2171. this.type = CellValue.TYPE_STRING;
  2172. this.formattedValue = stripped;
  2173. this.value = stripped;
  2174. return;
  2175. }
  2176. // =TRUE
  2177. const caps = cellString.toUpperCase();
  2178. if (caps == 'TRUE') {
  2179. this.type = CellValue.TYPE_BOOLEAN;
  2180. this.formattedValue = caps;
  2181. this.value = true;
  2182. this.formattedValue = 'TRUE';
  2183. return;
  2184. }
  2185. // =FALSE
  2186. if (caps == 'FALSE') {
  2187. this.type = CellValue.TYPE_BOOLEAN;
  2188. this.formattedValue = caps;
  2189. this.value = false;
  2190. this.formattedValue = 'FALSE';
  2191. return;
  2192. }
  2193. // =A*B
  2194. if (cellString.startsWith('=')) {
  2195. this.type = CellValue.TYPE_FORMULA;
  2196. this.value = cellString;
  2197. return;
  2198. }
  2199. // -$1,234.56
  2200. var groups;
  2201. if (groups = /^([-]?)\$(-?[0-9,]*\.)([0-9]+)$/.exec(cellString)) {
  2202. const sign = groups[1];
  2203. const dollars = groups[2].replace(/,/g, '');
  2204. const cents = groups[3];
  2205. this.type = CellValue.TYPE_CURRENCY;
  2206. this.decimals = 2;
  2207. this.value = parseFloat(sign + dollars + cents);
  2208. this.formattedValue = CellValue.#formatCurrency(this.value, this.decimals);
  2209. return;
  2210. }
  2211. // -$1,234
  2212. if (groups = /^([-]?)\$(-?[0-9,]+)$/.exec(cellString)) {
  2213. const sign = groups[1];
  2214. const dollars = groups[2].replace(/,/g, '');
  2215. this.type = CellValue.TYPE_CURRENCY;
  2216. this.decimals = 0;
  2217. this.value = parseFloat(sign + dollars);
  2218. this.formattedValue = CellValue.#formatCurrency(this.value, this.decimals);
  2219. return;
  2220. }
  2221. // -1,234.56%
  2222. if (groups = /^([-]?[0-9,]*\.)([0-9,]+)%$/.exec(cellString)) {
  2223. const wholes = groups[1].replace(/,/, '');
  2224. const decimals = groups[2];
  2225. this.type = CellValue.TYPE_PERCENT;
  2226. this.decimals = decimals.length;
  2227. this.value = parseFloat(wholes + decimals) / 100.0;
  2228. this.formattedValue = CellValue.#formatPercent(this.value, this.decimals);
  2229. return;
  2230. }
  2231. // -1,234%
  2232. if (groups = /^([-]?[0-9,]+)%$/.exec(cellString)) {
  2233. const wholes = groups[1].replace(/,/g, '');
  2234. this.type = CellValue.TYPE_PERCENT;
  2235. this.decimals = 0;
  2236. this.value = parseFloat(wholes) / 100.0;
  2237. this.formattedValue = CellValue.#formatPercent(this.value, this.decimals);
  2238. return;
  2239. }
  2240. // -1,234.56
  2241. if (groups = /^([-]?[0-9,]*\.)([0-9]+)$/.exec(cellString)) {
  2242. const wholes = groups[1].replace(/,/g, '');
  2243. const decimals = groups[2];
  2244. this.type = CellValue.TYPE_NUMBER;
  2245. this.decimals = decimals.length;
  2246. this.value = parseFloat(wholes + decimals);
  2247. this.formattedValue = CellValue.#formatNumber(this.value, this.decimals);
  2248. return;
  2249. }
  2250. // -1,234
  2251. if (groups = /^([-]?[0-9,]+)$/.exec(cellString)) {
  2252. const wholes = groups[1].replace(/,/g, '');
  2253. this.type = CellValue.TYPE_NUMBER;
  2254. this.decimals = 0;
  2255. this.value = parseFloat(wholes);
  2256. this.formattedValue = CellValue.#formatNumber(this.value, this.decimals);
  2257. return;
  2258. }
  2259. this.type = CellValue.TYPE_STRING;
  2260. this.value = cellString;
  2261. }
  2262. /**
  2263. * Returns the boolean equivalent of this value if possible.
  2264. *
  2265. * @returns {boolean|null}
  2266. */
  2267. booleanValue() {
  2268. switch (this.type) {
  2269. case CellValue.TYPE_BLANK:
  2270. return false;
  2271. case CellValue.TYPE_BOOLEAN:
  2272. return this.value;
  2273. case CellValue.TYPE_CURRENCY:
  2274. case CellValue.TYPE_NUMBER:
  2275. case CellValue.TYPE_PERCENT:
  2276. return this.value != 0;
  2277. case CellValue.TYPE_ERROR:
  2278. case CellValue.TYPE_FORMULA:
  2279. case CellValue.TYPE_STRING:
  2280. return null;
  2281. }
  2282. }
  2283. /**
  2284. * Returns the numeric value of this value if possible.
  2285. *
  2286. * @returns {number|null}
  2287. */
  2288. numericValue() {
  2289. switch (this.type) {
  2290. case CellValue.TYPE_BLANK:
  2291. return 0.0;
  2292. case CellValue.TYPE_BOOLEAN:
  2293. return this.value ? 1.0 : 0.0;
  2294. case CellValue.TYPE_CURRENCY:
  2295. case CellValue.TYPE_NUMBER:
  2296. case CellValue.TYPE_PERCENT:
  2297. return this.value;
  2298. case CellValue.TYPE_ERROR:
  2299. case CellValue.TYPE_FORMULA:
  2300. case CellValue.TYPE_STRING:
  2301. return null;
  2302. }
  2303. }
  2304. /**
  2305. * Returns the string value of this value if possible.
  2306. *
  2307. * @param {boolean} formatted
  2308. * @returns {string|null}
  2309. */
  2310. stringValue(formatted = false) {
  2311. switch (this.type) {
  2312. case CellValue.TYPE_BLANK:
  2313. return '';
  2314. case CellValue.TYPE_BOOLEAN:
  2315. return this.value ? 'TRUE' : 'FALSE';
  2316. case CellValue.TYPE_CURRENCY:
  2317. case CellValue.TYPE_NUMBER:
  2318. case CellValue.TYPE_PERCENT:
  2319. return formatted ? this.formattedValue : `${this.value}`;
  2320. case CellValue.TYPE_STRING:
  2321. return formatted ? this.formattedValue : this.value;
  2322. case CellValue.TYPE_ERROR:
  2323. case CellValue.TYPE_FORMULA:
  2324. return null;
  2325. }
  2326. }
  2327. // -- Operations --------------------------------------------------------
  2328. /**
  2329. * Returns the result of this value plus `b`.
  2330. *
  2331. * @param {CellValue} b
  2332. * @returns {CellValue} sum
  2333. */
  2334. add(b) {
  2335. return CellValue.#binaryNumericOperation(this, b, '+',
  2336. (aVal, bVal) => aVal + bVal);
  2337. }
  2338. /**
  2339. * Returns the result of this value minus `b`.
  2340. *
  2341. * @param {CellValue} b
  2342. * @returns {CellValue} difference
  2343. */
  2344. subtract(b) {
  2345. return CellValue.#binaryNumericOperation(this, b, '-',
  2346. (aVal, bVal) => aVal - bVal);
  2347. }
  2348. /**
  2349. * Returns the result of this value multiplied by `b`.
  2350. *
  2351. * @param {CellValue} b
  2352. * @returns {CellValue} product
  2353. */
  2354. multiply(b) {
  2355. return CellValue.#binaryNumericOperation(this, b, '*',
  2356. (aVal, bVal) => aVal * bVal);
  2357. }
  2358. /**
  2359. * Returns the result of this value divided by `b`.
  2360. *
  2361. * @param {CellValue} b
  2362. * @returns {CellValue} quotient
  2363. * @throws {CellEvaluationException} on divide by zero
  2364. */
  2365. divide(b) {
  2366. return CellValue.#binaryNumericOperation(this, b, '/', (aVal, bVal) => {
  2367. if (bVal == 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2368. return aVal / bVal
  2369. });
  2370. }
  2371. /**
  2372. * Returns the result of this value modulo by `b`.
  2373. *
  2374. * @param {CellValue} b
  2375. * @returns {CellValue} remainder
  2376. * @throws {CellEvaluationException} on divide by zero
  2377. */
  2378. modulo(b) {
  2379. return CellValue.#binaryNumericOperation(this, b, '%', (aVal, bVal) => {
  2380. if (bVal == 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2381. return aVal % bVal
  2382. });
  2383. }
  2384. /**
  2385. * Returns the result of whether this value is greater than `b`.
  2386. *
  2387. * @param {CellValue} b
  2388. * @returns {CellValue}
  2389. */
  2390. gt(b) {
  2391. return CellValue.fromValue(CellValue.#compare(this, b) > 0);
  2392. }
  2393. /**
  2394. * Returns the result of whether tihs value is greater than or equal to `b`.
  2395. *
  2396. * @param {CellValue} b
  2397. * @returns {CellValue}
  2398. */
  2399. gte(b) {
  2400. return CellValue.fromValue(CellValue.#compare(this, b) >= 0);
  2401. }
  2402. /**
  2403. * Returns the result of whether this value is less than `b`.
  2404. *
  2405. * @param {CellValue} b
  2406. * @returns {CellValue}
  2407. */
  2408. lt(b) {
  2409. return CellValue.fromValue(CellValue.#compare(this, b) < 0);
  2410. }
  2411. /**
  2412. * Returns the result of whether this value is less than or equal to `b`.
  2413. *
  2414. * @param {CellValue} b
  2415. * @returns {CellValue}
  2416. */
  2417. lte(b) {
  2418. return CellValue.fromValue(CellValue.#compare(this, b) <= 0);
  2419. }
  2420. /**
  2421. * Returns the result of whether this value is equal to `b`.
  2422. *
  2423. * @param {CellValue} b
  2424. * @returns {CellValue}
  2425. */
  2426. eq(b) {
  2427. return CellValue.fromValue(CellValue.#compare(this, b) == 0);
  2428. }
  2429. /**
  2430. * Returns the result of whether this value is unequal to `b`.
  2431. *
  2432. * @param {CellValue} b
  2433. * @returns {CellValue}
  2434. */
  2435. neq(b) {
  2436. return CellValue.fromValue(CellValue.#compare(this, b) != 0);
  2437. }
  2438. /**
  2439. * Returns the boolean not of this value.
  2440. *
  2441. * @returns {CellValue}
  2442. */
  2443. not() {
  2444. switch (this.type) {
  2445. case CellValue.TYPE_BLANK:
  2446. return CellValue.fromValue(true);
  2447. case CellValue.TYPE_CURRENCY:
  2448. case CellValue.TYPE_NUMBER:
  2449. case CellValue.TYPE_PERCENT:
  2450. return CellValue.fromValue(this.value == 0);
  2451. case CellValue.TYPE_STRING:
  2452. throw new CellEvaluationException("Cannot perform NOT on string");
  2453. case CellValue.TYPE_BOOLEAN:
  2454. return CellValue.fromValue(!this.value);
  2455. case CellValue.TYPE_ERROR:
  2456. throw this.value;
  2457. case CellValue.TYPE_FORMULA:
  2458. throw new CellEvaluationException("Cannot perform NOT on expression");
  2459. }
  2460. }
  2461. /**
  2462. * Returns the string representation of a value concatenated to the string
  2463. * representation of this value.
  2464. *
  2465. * @param {CellValue} b
  2466. * @returns {CellValue}
  2467. */
  2468. concatenate(b) {
  2469. const s1 = this.stringValue(true);
  2470. const s2 = b.stringValue(true);
  2471. if (s1 === null || s2 === null) {
  2472. throw new CellEvaluationException("Concatenation requires string arguments");
  2473. }
  2474. return CellValue.fromValue(`${s1}${s2}`);
  2475. }
  2476. /**
  2477. * Helper to resolve two numeric arguments and perform an operation on them.
  2478. *
  2479. * @param {CellValue} a - operand A
  2480. * @param {CellValue} b - operand B
  2481. * @param {string} op - operator
  2482. * @param {function} fn - takes two `number` arguments and returns a `number` result
  2483. * @returns {CellValue} result
  2484. * @throws {CellEvaluationException}
  2485. */
  2486. static #binaryNumericOperation(a, b, op, fn) {
  2487. const ops = this.#resolveNumericOperands(a, b, op);
  2488. const aNum = ops[0];
  2489. const bNum = ops[1];
  2490. const type = ops[2];
  2491. const result = fn(aNum, bNum);
  2492. return CellValue.fromValue(result, type);
  2493. }
  2494. /**
  2495. * Determines what the result of a calculation with two operands should
  2496. * look like. Returns a tuple array of the A float value, the B float value,
  2497. * and the type of the result.
  2498. *
  2499. * @param {CellValue} a - operand A
  2500. * @param {CellValue} b - operand B
  2501. * @param {string} op - operator symbol
  2502. * @returns {Array} 3-element tuple array with A number value, B number value,
  2503. * and result type string
  2504. * @throws {CellEvaluationException} if types are incompatible for numeric operations
  2505. */
  2506. static #resolveNumericOperands(a, b, op) {
  2507. if (a.type == this.TYPE_ERROR) throw a.value;
  2508. if (b.type == this.TYPE_ERROR) throw b.value;
  2509. if (a.type == this.TYPE_STRING || b.type == this.TYPE_STRING) {
  2510. throw new CellEvaluationException("Cannot perform math on text values");
  2511. }
  2512. if (a.type == this.TYPE_BLANK) {
  2513. if (b.type == this.TYPE_BLANK) {
  2514. return [ 0, 0, this.TYPE_NUMBER, 0 ];
  2515. }
  2516. return [ 0, b.value, b.type ];
  2517. } else if (b.type == this.TYPE_BLANK) {
  2518. return [ a.value, 0, a.type ];
  2519. }
  2520. const isMultOrDiv = (op == '*' || op == '/' || op == '%');
  2521. if (a.type == b.type) {
  2522. return [ a.value, b.value, a.type ];
  2523. }
  2524. switch (a.type + b.type) {
  2525. case this.TYPE_CURRENCY + this.TYPE_NUMBER:
  2526. case this.TYPE_CURRENCY + this.TYPE_PERCENT:
  2527. return [ a.value, b.value, this.TYPE_CURRENCY ];
  2528. case this.TYPE_PERCENT + this.TYPE_CURRENCY:
  2529. return [ a.value, b.value,
  2530. isMultOrDiv ? this.TYPE_CURRENCY : this.TYPE_PERCENT ];
  2531. case this.TYPE_PERCENT + this.TYPE_NUMBER:
  2532. return [ a.value, b.value,
  2533. isMultOrDiv ? this.TYPE_NUMBER : this.TYPE_PERCENT ];
  2534. case this.TYPE_NUMBER + this.TYPE_CURRENCY:
  2535. return [ a.value, b.value, b.type ];
  2536. case this.TYPE_NUMBER + this.TYPE_PERCENT:
  2537. return [ a.value, b.value,
  2538. isMultOrDiv ? this.TYPE_NUMBER : b.type ];
  2539. case this.TYPE_BOOLEAN + this.TYPE_CURRENCY:
  2540. case this.TYPE_BOOLEAN + this.TYPE_NUMBER:
  2541. case this.TYPE_BOOLEAN + this.TYPE_PERCENT:
  2542. return [ a.value ? 1 : 0, b.value, b.type ];
  2543. case this.TYPE_CURRENCY + this.TYPE_BOOLEAN:
  2544. case this.TYPE_NUMBER + this.TYPE_BOOLEAN:
  2545. case this.TYPE_PERCENT + this.TYPE_BOOLEAN:
  2546. return [ a.value, b.value ? 1 : 0, a.type ];
  2547. }
  2548. throw new CellEvaluationException(`Unhandled operand types "${a.type}" and "${b.type}"`);
  2549. }
  2550. /**
  2551. * Performs a comparison of two values.
  2552. *
  2553. * @param {CellValue} a
  2554. * @param {CellValue} b
  2555. * @returns {number} `-1`, `0`, or `1` if a < b, a == b, or a > b, respectively
  2556. */
  2557. static #compare(a, b) {
  2558. const args = CellValue.#resolveComparableArguments(a, b);
  2559. const valueA = args[0];
  2560. const valueB = args[1];
  2561. if (typeof valueA == 'string') {
  2562. return valueA.localeCompare(valueB, undefined, { sensitivity: 'accent' });
  2563. } else {
  2564. if (valueA < valueB) return -1;
  2565. if (valueA > valueB) return 1;
  2566. return 0;
  2567. }
  2568. }
  2569. /**
  2570. * @param {CellValue} a
  2571. * @param {CellValue} b
  2572. * @returns {Array}
  2573. */
  2574. static #resolveComparableArguments(a, b) {
  2575. if (a.type == CellValue.TYPE_ERROR) throw a.value;
  2576. if (b.type == CellValue.TYPE_ERROR) throw b.value;
  2577. if (a.type == CellValue.TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2578. if (b.type == CellValue.TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2579. const aNumValue = a.value;
  2580. const bNumValue = b.value;
  2581. const aStrValue = `${a.value}`;
  2582. const bStrValue = `${b.value}`;
  2583. switch (a.type) {
  2584. case CellValue.TYPE_BLANK:
  2585. aNumValue = 0;
  2586. aStrValue = '';
  2587. break;
  2588. case CellValue.TYPE_BOOLEAN:
  2589. aNumValue = (aNumValue) ? 1 : 0;
  2590. break;
  2591. }
  2592. switch (b.type) {
  2593. case CellValue.TYPE_BLANK:
  2594. bNumValue = 0;
  2595. bStrValue = '';
  2596. break;
  2597. case CellValue.TYPE_BOOLEAN:
  2598. bNumValue = (bNumValue) ? 1 : 0;
  2599. break;
  2600. }
  2601. if (a.type == CellValue.TYPE_STRING || b.type == CellValue.TYPE_STRING) {
  2602. return [ aStrValue, bStrValue ];
  2603. }
  2604. return [ aNumValue, bNumValue ];
  2605. }
  2606. /**
  2607. * Returns a formatted string for the given raw value, value type, and
  2608. * decimal places.
  2609. *
  2610. * @param {any} value
  2611. * @param {string} type
  2612. * @param {number} decimals
  2613. * @returns {string} formatted value
  2614. */
  2615. static formatType(value, type, decimals) {
  2616. switch (type) {
  2617. case CellValue.TYPE_BLANK: return '';
  2618. case CellValue.TYPE_CURRENCY: return CellValue.#formatCurrency(value, decimals);
  2619. case CellValue.TYPE_NUMBER: return CellValue.#formatNumber(value, decimals);
  2620. case CellValue.TYPE_PERCENT: return CellValue.#formatPercent(value, decimals);
  2621. case CellValue.TYPE_BOOLEAN: return value ? 'TRUE' : 'FALSE';
  2622. case CellValue.TYPE_STRING: return `${value}`;
  2623. case CellValue.TYPE_FORMULA: return `${value}`;
  2624. }
  2625. }
  2626. /**
  2627. * @param {number} value
  2628. * @param {number} decimals
  2629. * @returns {string}
  2630. */
  2631. static #formatNumber(value, decimals) {
  2632. return (value).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  2633. }
  2634. /**
  2635. * @param {number} dollars
  2636. * @param {number} decimals
  2637. * @returns {string}
  2638. */
  2639. static #formatCurrency(dollars, decimals) {
  2640. var s = (dollars).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  2641. if (s.startsWith('-')) {
  2642. return '-$' + s.substring(1);
  2643. }
  2644. return '$' + s;
  2645. }
  2646. /**
  2647. * @param {number} value
  2648. * @param {number} decimals
  2649. * @returns {string}
  2650. */
  2651. static #formatPercent(value, decimals) {
  2652. const dec = value * 100.0;
  2653. return (dec).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals }) + '%';
  2654. }
  2655. /**
  2656. * Determines a good number of decimal places to format a value to.
  2657. *
  2658. * @param {any} value
  2659. * @param {number} maxDigits
  2660. * @returns {number} digit count
  2661. */
  2662. static #autodecimals(value, maxDigits = 6) {
  2663. if (value instanceof CellValue) {
  2664. return CellValue.#autodecimals(value.value);
  2665. }
  2666. if (typeof value == 'number') {
  2667. var s = (value).toLocaleString(undefined, { maximumFractionDigits: maxDigits });
  2668. if (/\./.exec(s) === null) return 0;
  2669. var fraction = s.split('.')[1];
  2670. return Math.min(maxDigits, fraction.length);
  2671. }
  2672. return 0;
  2673. }
  2674. /**
  2675. * Tests if a type is numeric.
  2676. *
  2677. * @param {string} type
  2678. * @returns {boolean}
  2679. */
  2680. static isTypeNumeric(type) {
  2681. return type == CellValue.TYPE_NUMBER ||
  2682. type == CellValue.TYPE_PERCENT ||
  2683. type == CellValue.TYPE_CURRENCY ||
  2684. type == CellValue.TYPE_BOOLEAN;
  2685. }
  2686. toString() {
  2687. return `[CellValue type=${this.type} value=${this.value} "${this.formattedValue}"]`;
  2688. }
  2689. }
  2690. /**
  2691. * A rectangular grid of `SpreadsheetCell`s representing a spreadsheet.
  2692. * Agnostic of presentation.
  2693. */
  2694. class SpreadsheetGrid {
  2695. /**
  2696. * Indexed by column then row.
  2697. * @type {SpreadsheetCell[][]}
  2698. */
  2699. cells;
  2700. /** @type {number} */
  2701. columnCount;
  2702. /** @type {number} */
  2703. rowCount;
  2704. /**
  2705. * @param {number} columnCount
  2706. * @param {number} rowCount
  2707. */
  2708. constructor(columnCount, rowCount) {
  2709. this.columnCount = columnCount;
  2710. this.rowCount = rowCount;
  2711. this.cells = new Array(columnCount);
  2712. for (var c = 0; c < columnCount; c++) {
  2713. this.cells[c] = new Array(rowCount);
  2714. for (var r = 0; r < rowCount; r++) {
  2715. this.cells[c][r] = new SpreadsheetCell();
  2716. }
  2717. }
  2718. }
  2719. /**
  2720. * @param {CellAddress} address
  2721. * @returns {SpreadsheetCell|null} cell, or `null` if no cell available
  2722. * @throws {CellEvaluationException} if the address it out of bounds
  2723. */
  2724. cellAt(address) {
  2725. const c = address.columnIndex, r = address.rowIndex;
  2726. if (c < 0 || c >= this.cells.length) throw new CellEvaluationException(`Unresolved cell address ${address.name}`, '#REF');
  2727. const row = this.cells[c];
  2728. if (r < 0 || r >= row.length) throw new CellEvaluationException(`Unresolved cell address ${address.name}`, '#REF');
  2729. return row[r];
  2730. }
  2731. /**
  2732. * Returns the original value at the given address.
  2733. * @param {CellAddress} address
  2734. */
  2735. valueAt(address) {
  2736. return this.cellAt(address)?.originalValue;
  2737. }
  2738. /**
  2739. * Returns the computed value at the given address.
  2740. * @param {CellAddress} address
  2741. * @returns {CellValue|null} computed value or `null`
  2742. */
  2743. outputValueAt(address) {
  2744. return this.cellAt(address)?.outputValue;
  2745. }
  2746. }
  2747. /**
  2748. * One cell in a spreadsheet grid. Has an `originalValue` to start and an
  2749. * evaluated `outputValue` after population by a `CellExpressionSet` computation.
  2750. */
  2751. class SpreadsheetCell {
  2752. /**
  2753. * @type {CellValue}
  2754. */
  2755. originalValue = CellValue.BLANK;
  2756. /**
  2757. * @type {CellValue|null}
  2758. */
  2759. outputValue = null;
  2760. /**
  2761. * Whether `outputValue` is the result of a formula evaluation.
  2762. * @type {boolean}
  2763. */
  2764. isCalculated = false;
  2765. /** @type {CellExpression|null} */
  2766. parsedExpression = null;
  2767. /**
  2768. * @type {CellValue|null}
  2769. */
  2770. get resolvedValue() { return this.outputValue ?? this.originalValue; }
  2771. }
  2772. /**
  2773. * Integration with Markdown. Adding this block reader to a parser will run a
  2774. * post-process step on any tables in the document tree. Must be used with
  2775. * `MDTableReader`. Tables without at least one formula will not be altered.
  2776. */
  2777. class MDSpreadsheetReader extends MDReader {
  2778. preProcess(state) {
  2779. for (const reader of state.readersByBlockPriority) {
  2780. if (reader instanceof MDTableReader) {
  2781. reader.preferFormulas = true;
  2782. }
  2783. }
  2784. }
  2785. postProcess(state, nodes) {
  2786. for (const node of nodes) {
  2787. if (node instanceof MDTableNode) {
  2788. this.#processTable(node, state);
  2789. }
  2790. }
  2791. }
  2792. /**
  2793. * @param {MDTableNode} tableNode
  2794. * @param {MDState} state
  2795. */
  2796. #processTable(tableNode, state) {
  2797. // Measure table
  2798. const rowCount = tableNode.bodyRows.length;
  2799. var columnCount = 0;
  2800. for (const row of tableNode.bodyRows) {
  2801. columnCount = Math.max(columnCount, row.children.length);
  2802. }
  2803. // Create and populate grid
  2804. const grid = new SpreadsheetGrid(columnCount, rowCount);
  2805. for (var c = 0; c < columnCount; c++) {
  2806. for (var r = 0; r < rowCount; r++) {
  2807. const cellNode = tableNode.bodyCellAt(c, r);
  2808. if (cellNode === null) continue;
  2809. const cellText = cellNode.toPlaintext(state);
  2810. const gridCell = grid.cells[c][r];
  2811. gridCell.originalValue = CellValue.fromCellString(cellText);
  2812. }
  2813. }
  2814. // Calculate
  2815. const expressions = new CellExpressionSet(grid);
  2816. expressions.calculateCells();
  2817. // See if anything was calculated. If not, don't mess with table.
  2818. var isCalculated = false;
  2819. for (var c = 0; c < columnCount && !isCalculated; c++) {
  2820. for (var r = 0; r < rowCount; r++) {
  2821. if (grid.cellAt(new CellAddress(c, r)).isCalculated) {
  2822. isCalculated = true;
  2823. break;
  2824. }
  2825. }
  2826. }
  2827. if (!isCalculated) return;
  2828. // Copy results back to table
  2829. for (var c = 0; c < columnCount; c++) {
  2830. for (var r = 0; r < rowCount; r++) {
  2831. const cellNode = tableNode.bodyCellAt(c, r);
  2832. const gridCell = grid.cellAt(new CellAddress(c, r));
  2833. if (cellNode === null || gridCell === null) continue;
  2834. this.#populateCell(cellNode, gridCell, state, c, r);
  2835. }
  2836. }
  2837. }
  2838. /**
  2839. * @param {MDTableCellNode} cellNode
  2840. * @param {SpreadsheetCell} gridCell
  2841. * @param {MDState} state
  2842. * @param {number} c - column index
  2843. * @param {number} r - row index
  2844. */
  2845. #populateCell(cellNode, gridCell, state, c, r) {
  2846. const gridValue = gridCell.outputValue;
  2847. if (gridValue === null) return;
  2848. const oldCellText = cellNode.toPlaintext(state).trim();
  2849. const cellText = gridValue.formattedValue;
  2850. if (cellText != oldCellText) {
  2851. // Try to insert the text into any nested whole-value formatting nodes
  2852. // if possible
  2853. if (!this.#findTextNode(cellNode, oldCellText, cellText)) {
  2854. // Contents contain mixed formatting. We'll have to just replace
  2855. // the whole thing.
  2856. cellNode.children = [ new MDTextNode(cellText) ];
  2857. }
  2858. }
  2859. if (gridCell.isCalculated) {
  2860. cellNode.cssClasses.push('calculated');
  2861. }
  2862. cellNode.cssClasses.push(`spreadsheet-type-${gridValue.type}`);
  2863. if (gridValue.type == CellValue.TYPE_ERROR) {
  2864. cellNode.attributes['title'] = gridValue.value;
  2865. }
  2866. const gridNumber = gridValue.numericValue();
  2867. if (gridNumber !== null) {
  2868. cellNode.attributes['data-numeric-value'] = `${gridNumber}`;
  2869. }
  2870. const gridString = gridValue.stringValue(false);
  2871. if (gridString !== null) {
  2872. cellNode.attributes['data-string-value'] = gridString;
  2873. }
  2874. }
  2875. #findTextNode(startNode, expectedText, newText) {
  2876. if (startNode instanceof MDTextNode) {
  2877. if (startNode.text.trim() === expectedText.trim()) {
  2878. startNode.text = newText;
  2879. return true;
  2880. }
  2881. }
  2882. for (const child of startNode.children) {
  2883. if (this.#findTextNode(child, expectedText, newText)) return true;
  2884. }
  2885. return false;
  2886. }
  2887. }