PHP and Javascript implementations of a simple markdown parser
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

spreadsheet.js 93KB

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