You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WorkbookEvaluator.java 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.ss.formula;
  16. import java.util.IdentityHashMap;
  17. import java.util.Map;
  18. import java.util.Stack;
  19. import org.apache.poi.ss.formula.ptg.Area3DPtg;
  20. import org.apache.poi.ss.formula.ptg.AreaErrPtg;
  21. import org.apache.poi.ss.formula.ptg.AreaPtg;
  22. import org.apache.poi.ss.formula.ptg.AttrPtg;
  23. import org.apache.poi.ss.formula.ptg.BoolPtg;
  24. import org.apache.poi.ss.formula.ptg.ControlPtg;
  25. import org.apache.poi.ss.formula.ptg.DeletedArea3DPtg;
  26. import org.apache.poi.ss.formula.ptg.DeletedRef3DPtg;
  27. import org.apache.poi.ss.formula.ptg.ErrPtg;
  28. import org.apache.poi.ss.formula.ptg.ExpPtg;
  29. import org.apache.poi.ss.formula.ptg.FuncVarPtg;
  30. import org.apache.poi.ss.formula.ptg.IntPtg;
  31. import org.apache.poi.ss.formula.ptg.MemAreaPtg;
  32. import org.apache.poi.ss.formula.ptg.MemErrPtg;
  33. import org.apache.poi.ss.formula.ptg.MemFuncPtg;
  34. import org.apache.poi.ss.formula.ptg.MissingArgPtg;
  35. import org.apache.poi.ss.formula.ptg.NamePtg;
  36. import org.apache.poi.ss.formula.ptg.NameXPtg;
  37. import org.apache.poi.ss.formula.ptg.NumberPtg;
  38. import org.apache.poi.ss.formula.ptg.OperationPtg;
  39. import org.apache.poi.ss.formula.ptg.Ptg;
  40. import org.apache.poi.ss.formula.ptg.Ref3DPtg;
  41. import org.apache.poi.ss.formula.ptg.RefErrorPtg;
  42. import org.apache.poi.ss.formula.ptg.RefPtg;
  43. import org.apache.poi.ss.formula.ptg.StringPtg;
  44. import org.apache.poi.ss.formula.ptg.UnionPtg;
  45. import org.apache.poi.ss.formula.ptg.UnknownPtg;
  46. import org.apache.poi.ss.formula.eval.BlankEval;
  47. import org.apache.poi.ss.formula.eval.BoolEval;
  48. import org.apache.poi.ss.formula.eval.ErrorEval;
  49. import org.apache.poi.ss.formula.eval.EvaluationException;
  50. import org.apache.poi.ss.formula.eval.MissingArgEval;
  51. import org.apache.poi.ss.formula.eval.NameEval;
  52. import org.apache.poi.ss.formula.eval.NumberEval;
  53. import org.apache.poi.ss.formula.eval.OperandResolver;
  54. import org.apache.poi.ss.formula.eval.StringEval;
  55. import org.apache.poi.ss.formula.eval.ValueEval;
  56. import org.apache.poi.ss.formula.functions.Choose;
  57. import org.apache.poi.ss.formula.functions.FreeRefFunction;
  58. import org.apache.poi.ss.formula.functions.IfFunc;
  59. import org.apache.poi.ss.formula.udf.AggregatingUDFFinder;
  60. import org.apache.poi.ss.formula.udf.UDFFinder;
  61. import org.apache.poi.ss.util.CellReference;
  62. import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment.WorkbookNotFoundException;
  63. import org.apache.poi.ss.formula.eval.NotImplementedException;
  64. import org.apache.poi.ss.usermodel.Cell;
  65. import org.apache.poi.util.POILogFactory;
  66. import org.apache.poi.util.POILogger;
  67. /**
  68. * Evaluates formula cells.<p/>
  69. *
  70. * For performance reasons, this class keeps a cache of all previously calculated intermediate
  71. * cell values. Be sure to call {@link #clearAllCachedResultValues()} if any workbook cells are changed between
  72. * calls to evaluate~ methods on this class.<br/>
  73. *
  74. * For POI internal use only
  75. *
  76. * @author Josh Micich
  77. */
  78. public final class WorkbookEvaluator {
  79. private static final POILogger LOG = POILogFactory.getLogger(WorkbookEvaluator.class);
  80. /**
  81. * Whether to use cached formula results if external workbook references in a formula is not available.
  82. * See Bugzilla 52575 for details.
  83. */
  84. private static final String IGNORE_MISSING_WORKBOOKS = WorkbookEvaluator.class.getName() + ".IGNORE_MISSING_WORKBOOKS";
  85. private final EvaluationWorkbook _workbook;
  86. private EvaluationCache _cache;
  87. /** part of cache entry key (useful when evaluating multiple workbooks) */
  88. private int _workbookIx;
  89. private final IEvaluationListener _evaluationListener;
  90. private final Map<EvaluationSheet, Integer> _sheetIndexesBySheet;
  91. private final Map<String, Integer> _sheetIndexesByName;
  92. private CollaboratingWorkbooksEnvironment _collaboratingWorkbookEnvironment;
  93. private final IStabilityClassifier _stabilityClassifier;
  94. private final AggregatingUDFFinder _udfFinder;
  95. /**
  96. * @param udfFinder pass <code>null</code> for default (AnalysisToolPak only)
  97. */
  98. public WorkbookEvaluator(EvaluationWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) {
  99. this (workbook, null, stabilityClassifier, udfFinder);
  100. }
  101. /* package */ WorkbookEvaluator(EvaluationWorkbook workbook, IEvaluationListener evaluationListener,
  102. IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) {
  103. _workbook = workbook;
  104. _evaluationListener = evaluationListener;
  105. _cache = new EvaluationCache(evaluationListener);
  106. _sheetIndexesBySheet = new IdentityHashMap<EvaluationSheet, Integer>();
  107. _sheetIndexesByName = new IdentityHashMap<String, Integer>();
  108. _collaboratingWorkbookEnvironment = CollaboratingWorkbooksEnvironment.EMPTY;
  109. _workbookIx = 0;
  110. _stabilityClassifier = stabilityClassifier;
  111. AggregatingUDFFinder defaultToolkit = // workbook can be null in unit tests
  112. workbook == null ? null : (AggregatingUDFFinder)workbook.getUDFFinder();
  113. if(defaultToolkit != null && udfFinder != null) {
  114. defaultToolkit.add(udfFinder);
  115. }
  116. _udfFinder = defaultToolkit;
  117. }
  118. /**
  119. * also for debug use. Used in toString methods
  120. */
  121. /* package */ String getSheetName(int sheetIndex) {
  122. return _workbook.getSheetName(sheetIndex);
  123. }
  124. /* package */ EvaluationSheet getSheet(int sheetIndex) {
  125. return _workbook.getSheet(sheetIndex);
  126. }
  127. /* package */ EvaluationWorkbook getWorkbook() {
  128. return _workbook;
  129. }
  130. /* package */ EvaluationName getName(String name, int sheetIndex) {
  131. NamePtg namePtg = _workbook.getName(name, sheetIndex).createPtg();
  132. if(namePtg == null) {
  133. return null;
  134. } else {
  135. return _workbook.getName(namePtg);
  136. }
  137. }
  138. private static boolean isDebugLogEnabled() {
  139. return LOG.check(POILogger.DEBUG);
  140. }
  141. private static boolean isInfoLogEnabled() {
  142. return LOG.check(POILogger.INFO);
  143. }
  144. private static void logDebug(String s) {
  145. if (isDebugLogEnabled()) {
  146. LOG.log(POILogger.DEBUG, s);
  147. }
  148. }
  149. private static void logInfo(String s) {
  150. if (isInfoLogEnabled()) {
  151. LOG.log(POILogger.INFO, s);
  152. }
  153. }
  154. /* package */ void attachToEnvironment(CollaboratingWorkbooksEnvironment collaboratingWorkbooksEnvironment, EvaluationCache cache, int workbookIx) {
  155. _collaboratingWorkbookEnvironment = collaboratingWorkbooksEnvironment;
  156. _cache = cache;
  157. _workbookIx = workbookIx;
  158. }
  159. /* package */ CollaboratingWorkbooksEnvironment getEnvironment() {
  160. return _collaboratingWorkbookEnvironment;
  161. }
  162. /**
  163. * Discards the current workbook environment and attaches to the default 'empty' environment.
  164. * Also resets evaluation cache.
  165. */
  166. /* package */ void detachFromEnvironment() {
  167. _collaboratingWorkbookEnvironment = CollaboratingWorkbooksEnvironment.EMPTY;
  168. _cache = new EvaluationCache(_evaluationListener);
  169. _workbookIx = 0;
  170. }
  171. /**
  172. * @return the evaluator for another workbook which is part of the same {@link CollaboratingWorkbooksEnvironment}
  173. */
  174. /* package */ WorkbookEvaluator getOtherWorkbookEvaluator(String workbookName) throws WorkbookNotFoundException {
  175. return _collaboratingWorkbookEnvironment.getWorkbookEvaluator(workbookName);
  176. }
  177. /* package */ IEvaluationListener getEvaluationListener() {
  178. return _evaluationListener;
  179. }
  180. /**
  181. * Should be called whenever there are changes to input cells in the evaluated workbook.
  182. * Failure to call this method after changing cell values will cause incorrect behaviour
  183. * of the evaluate~ methods of this class
  184. */
  185. public void clearAllCachedResultValues() {
  186. _cache.clear();
  187. _sheetIndexesBySheet.clear();
  188. }
  189. /**
  190. * Should be called to tell the cell value cache that the specified (value or formula) cell
  191. * has changed.
  192. */
  193. public void notifyUpdateCell(EvaluationCell cell) {
  194. int sheetIndex = getSheetIndex(cell.getSheet());
  195. _cache.notifyUpdateCell(_workbookIx, sheetIndex, cell);
  196. }
  197. /**
  198. * Should be called to tell the cell value cache that the specified cell has just been
  199. * deleted.
  200. */
  201. public void notifyDeleteCell(EvaluationCell cell) {
  202. int sheetIndex = getSheetIndex(cell.getSheet());
  203. _cache.notifyDeleteCell(_workbookIx, sheetIndex, cell);
  204. }
  205. private int getSheetIndex(EvaluationSheet sheet) {
  206. Integer result = _sheetIndexesBySheet.get(sheet);
  207. if (result == null) {
  208. int sheetIndex = _workbook.getSheetIndex(sheet);
  209. if (sheetIndex < 0) {
  210. throw new RuntimeException("Specified sheet from a different book");
  211. }
  212. result = Integer.valueOf(sheetIndex);
  213. _sheetIndexesBySheet.put(sheet, result);
  214. }
  215. return result.intValue();
  216. }
  217. public ValueEval evaluate(EvaluationCell srcCell) {
  218. int sheetIndex = getSheetIndex(srcCell.getSheet());
  219. return evaluateAny(srcCell, sheetIndex, srcCell.getRowIndex(), srcCell.getColumnIndex(), new EvaluationTracker(_cache));
  220. }
  221. /**
  222. * Case-insensitive.
  223. * @return -1 if sheet with specified name does not exist
  224. */
  225. /* package */ int getSheetIndex(String sheetName) {
  226. Integer result = _sheetIndexesByName.get(sheetName);
  227. if (result == null) {
  228. int sheetIndex = _workbook.getSheetIndex(sheetName);
  229. if (sheetIndex < 0) {
  230. return -1;
  231. }
  232. result = Integer.valueOf(sheetIndex);
  233. _sheetIndexesByName.put(sheetName, result);
  234. }
  235. return result.intValue();
  236. }
  237. /* package */ int getSheetIndexByExternIndex(int externSheetIndex) {
  238. return _workbook.convertFromExternSheetIndex(externSheetIndex);
  239. }
  240. /**
  241. * @return never <code>null</code>, never {@link BlankEval}
  242. */
  243. private ValueEval evaluateAny(EvaluationCell srcCell, int sheetIndex,
  244. int rowIndex, int columnIndex, EvaluationTracker tracker) {
  245. // avoid tracking dependencies to cells that have constant definition
  246. boolean shouldCellDependencyBeRecorded = _stabilityClassifier == null ? true
  247. : !_stabilityClassifier.isCellFinal(sheetIndex, rowIndex, columnIndex);
  248. if (srcCell == null || srcCell.getCellType() != Cell.CELL_TYPE_FORMULA) {
  249. ValueEval result = getValueFromNonFormulaCell(srcCell);
  250. if (shouldCellDependencyBeRecorded) {
  251. tracker.acceptPlainValueDependency(_workbookIx, sheetIndex, rowIndex, columnIndex, result);
  252. }
  253. return result;
  254. }
  255. FormulaCellCacheEntry cce = _cache.getOrCreateFormulaCellEntry(srcCell);
  256. if (shouldCellDependencyBeRecorded || cce.isInputSensitive()) {
  257. tracker.acceptFormulaDependency(cce);
  258. }
  259. IEvaluationListener evalListener = _evaluationListener;
  260. ValueEval result;
  261. if (cce.getValue() == null) {
  262. if (!tracker.startEvaluate(cce)) {
  263. return ErrorEval.CIRCULAR_REF_ERROR;
  264. }
  265. OperationEvaluationContext ec = new OperationEvaluationContext(this, _workbook, sheetIndex, rowIndex, columnIndex, tracker);
  266. try {
  267. Ptg[] ptgs = _workbook.getFormulaTokens(srcCell);
  268. if (evalListener == null) {
  269. result = evaluateFormula(ec, ptgs);
  270. } else {
  271. evalListener.onStartEvaluate(srcCell, cce);
  272. result = evaluateFormula(ec, ptgs);
  273. evalListener.onEndEvaluate(cce, result);
  274. }
  275. tracker.updateCacheResult(result);
  276. }
  277. catch (NotImplementedException e) {
  278. throw addExceptionInfo(e, sheetIndex, rowIndex, columnIndex);
  279. } catch (RuntimeException re) {
  280. if (re.getCause() instanceof WorkbookNotFoundException
  281. //To be replaced by configuration infrastructure
  282. && Boolean.valueOf(System.getProperty(IGNORE_MISSING_WORKBOOKS))) {
  283. logInfo(re.getCause().getMessage() + " - Continuing with cached value!");
  284. switch(srcCell.getCachedFormulaResultType()) {
  285. case Cell.CELL_TYPE_NUMERIC:
  286. result = new NumberEval(srcCell.getNumericCellValue());
  287. break;
  288. case Cell.CELL_TYPE_STRING:
  289. result = new StringEval(srcCell.getStringCellValue());
  290. break;
  291. case Cell.CELL_TYPE_BLANK:
  292. result = BlankEval.instance;
  293. break;
  294. case Cell.CELL_TYPE_BOOLEAN:
  295. result = BoolEval.valueOf(srcCell.getBooleanCellValue());
  296. break;
  297. case Cell.CELL_TYPE_ERROR:
  298. result = ErrorEval.valueOf(srcCell.getErrorCellValue());
  299. break;
  300. case Cell.CELL_TYPE_FORMULA:
  301. default:
  302. throw new RuntimeException("Unexpected cell type '" + srcCell.getCellType()+"' found!");
  303. }
  304. } else {
  305. throw re;
  306. }
  307. } finally {
  308. tracker.endEvaluate(cce);
  309. }
  310. } else {
  311. if(evalListener != null) {
  312. evalListener.onCacheHit(sheetIndex, rowIndex, columnIndex, cce.getValue());
  313. }
  314. return cce.getValue();
  315. }
  316. if (isDebugLogEnabled()) {
  317. String sheetName = getSheetName(sheetIndex);
  318. CellReference cr = new CellReference(rowIndex, columnIndex);
  319. logDebug("Evaluated " + sheetName + "!" + cr.formatAsString() + " to " + result.toString());
  320. }
  321. // Usually (result === cce.getValue())
  322. // But sometimes: (result==ErrorEval.CIRCULAR_REF_ERROR, cce.getValue()==null)
  323. // When circular references are detected, the cache entry is only updated for
  324. // the top evaluation frame
  325. return result;
  326. }
  327. /**
  328. * Adds the current cell reference to the exception for easier debugging.
  329. * Would be nice to get the formula text as well, but that seems to require
  330. * too much digging around and casting to get the FormulaRenderingWorkbook.
  331. */
  332. private NotImplementedException addExceptionInfo(NotImplementedException inner, int sheetIndex, int rowIndex, int columnIndex) {
  333. try {
  334. String sheetName = _workbook.getSheetName(sheetIndex);
  335. CellReference cr = new CellReference(sheetName, rowIndex, columnIndex, false, false);
  336. String msg = "Error evaluating cell " + cr.formatAsString();
  337. return new NotImplementedException(msg, inner);
  338. } catch (Exception e) {
  339. // avoid bombing out during exception handling
  340. e.printStackTrace();
  341. return inner; // preserve original exception
  342. }
  343. }
  344. /**
  345. * Gets the value from a non-formula cell.
  346. * @param cell may be <code>null</code>
  347. * @return {@link BlankEval} if cell is <code>null</code> or blank, never <code>null</code>
  348. */
  349. /* package */ static ValueEval getValueFromNonFormulaCell(EvaluationCell cell) {
  350. if (cell == null) {
  351. return BlankEval.instance;
  352. }
  353. int cellType = cell.getCellType();
  354. switch (cellType) {
  355. case Cell.CELL_TYPE_NUMERIC:
  356. return new NumberEval(cell.getNumericCellValue());
  357. case Cell.CELL_TYPE_STRING:
  358. return new StringEval(cell.getStringCellValue());
  359. case Cell.CELL_TYPE_BOOLEAN:
  360. return BoolEval.valueOf(cell.getBooleanCellValue());
  361. case Cell.CELL_TYPE_BLANK:
  362. return BlankEval.instance;
  363. case Cell.CELL_TYPE_ERROR:
  364. return ErrorEval.valueOf(cell.getErrorCellValue());
  365. }
  366. throw new RuntimeException("Unexpected cell type (" + cellType + ")");
  367. }
  368. // visibility raised for testing
  369. /* package */ ValueEval evaluateFormula(OperationEvaluationContext ec, Ptg[] ptgs) {
  370. Stack<ValueEval> stack = new Stack<ValueEval>();
  371. for (int i = 0, iSize = ptgs.length; i < iSize; i++) {
  372. // since we don't know how to handle these yet :(
  373. Ptg ptg = ptgs[i];
  374. if (ptg instanceof AttrPtg) {
  375. AttrPtg attrPtg = (AttrPtg) ptg;
  376. if (attrPtg.isSum()) {
  377. // Excel prefers to encode 'SUM()' as a tAttr token, but this evaluator
  378. // expects the equivalent function token
  379. ptg = FuncVarPtg.SUM;
  380. }
  381. if (attrPtg.isOptimizedChoose()) {
  382. ValueEval arg0 = stack.pop();
  383. int[] jumpTable = attrPtg.getJumpTable();
  384. int dist;
  385. int nChoices = jumpTable.length;
  386. try {
  387. int switchIndex = Choose.evaluateFirstArg(arg0, ec.getRowIndex(), ec.getColumnIndex());
  388. if (switchIndex<1 || switchIndex > nChoices) {
  389. stack.push(ErrorEval.VALUE_INVALID);
  390. dist = attrPtg.getChooseFuncOffset() + 4; // +4 for tFuncFar(CHOOSE)
  391. } else {
  392. dist = jumpTable[switchIndex-1];
  393. }
  394. } catch (EvaluationException e) {
  395. stack.push(e.getErrorEval());
  396. dist = attrPtg.getChooseFuncOffset() + 4; // +4 for tFuncFar(CHOOSE)
  397. }
  398. // Encoded dist for tAttrChoose includes size of jump table, but
  399. // countTokensToBeSkipped() does not (it counts whole tokens).
  400. dist -= nChoices*2+2; // subtract jump table size
  401. i+= countTokensToBeSkipped(ptgs, i, dist);
  402. continue;
  403. }
  404. if (attrPtg.isOptimizedIf()) {
  405. ValueEval arg0 = stack.pop();
  406. boolean evaluatedPredicate;
  407. try {
  408. evaluatedPredicate = IfFunc.evaluateFirstArg(arg0, ec.getRowIndex(), ec.getColumnIndex());
  409. } catch (EvaluationException e) {
  410. stack.push(e.getErrorEval());
  411. int dist = attrPtg.getData();
  412. i+= countTokensToBeSkipped(ptgs, i, dist);
  413. attrPtg = (AttrPtg) ptgs[i];
  414. dist = attrPtg.getData()+1;
  415. i+= countTokensToBeSkipped(ptgs, i, dist);
  416. continue;
  417. }
  418. if (evaluatedPredicate) {
  419. // nothing to skip - true param folows
  420. } else {
  421. int dist = attrPtg.getData();
  422. i+= countTokensToBeSkipped(ptgs, i, dist);
  423. Ptg nextPtg = ptgs[i+1];
  424. if (ptgs[i] instanceof AttrPtg && nextPtg instanceof FuncVarPtg) {
  425. // this is an if statement without a false param (as opposed to MissingArgPtg as the false param)
  426. i++;
  427. stack.push(BoolEval.FALSE);
  428. }
  429. }
  430. continue;
  431. }
  432. if (attrPtg.isSkip()) {
  433. int dist = attrPtg.getData()+1;
  434. i+= countTokensToBeSkipped(ptgs, i, dist);
  435. if (stack.peek() == MissingArgEval.instance) {
  436. stack.pop();
  437. stack.push(BlankEval.instance);
  438. }
  439. continue;
  440. }
  441. }
  442. if (ptg instanceof ControlPtg) {
  443. // skip Parentheses, Attr, etc
  444. continue;
  445. }
  446. if (ptg instanceof MemFuncPtg || ptg instanceof MemAreaPtg) {
  447. // can ignore, rest of tokens for this expression are in OK RPN order
  448. continue;
  449. }
  450. if (ptg instanceof MemErrPtg) {
  451. continue;
  452. }
  453. ValueEval opResult;
  454. if (ptg instanceof OperationPtg) {
  455. OperationPtg optg = (OperationPtg) ptg;
  456. if (optg instanceof UnionPtg) { continue; }
  457. int numops = optg.getNumberOfOperands();
  458. ValueEval[] ops = new ValueEval[numops];
  459. // storing the ops in reverse order since they are popping
  460. for (int j = numops - 1; j >= 0; j--) {
  461. ValueEval p = stack.pop();
  462. ops[j] = p;
  463. }
  464. // logDebug("invoke " + operation + " (nAgs=" + numops + ")");
  465. opResult = OperationEvaluatorFactory.evaluate(optg, ops, ec);
  466. } else {
  467. opResult = getEvalForPtg(ptg, ec);
  468. }
  469. if (opResult == null) {
  470. throw new RuntimeException("Evaluation result must not be null");
  471. }
  472. // logDebug("push " + opResult);
  473. stack.push(opResult);
  474. }
  475. ValueEval value = stack.pop();
  476. if (!stack.isEmpty()) {
  477. throw new IllegalStateException("evaluation stack not empty");
  478. }
  479. return dereferenceResult(value, ec.getRowIndex(), ec.getColumnIndex());
  480. }
  481. /**
  482. * Calculates the number of tokens that the evaluator should skip upon reaching a tAttrSkip.
  483. *
  484. * @return the number of tokens (starting from <tt>startIndex+1</tt>) that need to be skipped
  485. * to achieve the specified <tt>distInBytes</tt> skip distance.
  486. */
  487. private static int countTokensToBeSkipped(Ptg[] ptgs, int startIndex, int distInBytes) {
  488. int remBytes = distInBytes;
  489. int index = startIndex;
  490. while (remBytes != 0) {
  491. index++;
  492. remBytes -= ptgs[index].getSize();
  493. if (remBytes < 0) {
  494. throw new RuntimeException("Bad skip distance (wrong token size calculation).");
  495. }
  496. if (index >= ptgs.length) {
  497. throw new RuntimeException("Skip distance too far (ran out of formula tokens).");
  498. }
  499. }
  500. return index-startIndex;
  501. }
  502. /**
  503. * Dereferences a single value from any AreaEval or RefEval evaluation
  504. * result. If the supplied evaluationResult is just a plain value, it is
  505. * returned as-is.
  506. *
  507. * @return a {@link NumberEval}, {@link StringEval}, {@link BoolEval}, or
  508. * {@link ErrorEval}. Never <code>null</code>. {@link BlankEval} is
  509. * converted to {@link NumberEval#ZERO}
  510. */
  511. public static ValueEval dereferenceResult(ValueEval evaluationResult, int srcRowNum, int srcColNum) {
  512. ValueEval value;
  513. try {
  514. value = OperandResolver.getSingleValue(evaluationResult, srcRowNum, srcColNum);
  515. } catch (EvaluationException e) {
  516. return e.getErrorEval();
  517. }
  518. if (value == BlankEval.instance) {
  519. // Note Excel behaviour here. A blank final final value is converted to zero.
  520. return NumberEval.ZERO;
  521. // Formulas _never_ evaluate to blank. If a formula appears to have evaluated to
  522. // blank, the actual value is empty string. This can be verified with ISBLANK().
  523. }
  524. return value;
  525. }
  526. /**
  527. * returns an appropriate Eval impl instance for the Ptg. The Ptg must be
  528. * one of: Area3DPtg, AreaPtg, ReferencePtg, Ref3DPtg, IntPtg, NumberPtg,
  529. * StringPtg, BoolPtg <br/>special Note: OperationPtg subtypes cannot be
  530. * passed here!
  531. */
  532. private ValueEval getEvalForPtg(Ptg ptg, OperationEvaluationContext ec) {
  533. // consider converting all these (ptg instanceof XxxPtg) expressions to (ptg.getClass() == XxxPtg.class)
  534. if (ptg instanceof NamePtg) {
  535. // named ranges, macro functions
  536. NamePtg namePtg = (NamePtg) ptg;
  537. EvaluationName nameRecord = _workbook.getName(namePtg);
  538. if (nameRecord.isFunctionName()) {
  539. return new NameEval(nameRecord.getNameText());
  540. }
  541. if (nameRecord.hasFormula()) {
  542. return evaluateNameFormula(nameRecord.getNameDefinition(), ec);
  543. }
  544. throw new RuntimeException("Don't now how to evalate name '" + nameRecord.getNameText() + "'");
  545. }
  546. if (ptg instanceof NameXPtg) {
  547. return ec.getNameXEval(((NameXPtg) ptg));
  548. }
  549. if (ptg instanceof IntPtg) {
  550. return new NumberEval(((IntPtg)ptg).getValue());
  551. }
  552. if (ptg instanceof NumberPtg) {
  553. return new NumberEval(((NumberPtg)ptg).getValue());
  554. }
  555. if (ptg instanceof StringPtg) {
  556. return new StringEval(((StringPtg) ptg).getValue());
  557. }
  558. if (ptg instanceof BoolPtg) {
  559. return BoolEval.valueOf(((BoolPtg) ptg).getValue());
  560. }
  561. if (ptg instanceof ErrPtg) {
  562. return ErrorEval.valueOf(((ErrPtg) ptg).getErrorCode());
  563. }
  564. if (ptg instanceof MissingArgPtg) {
  565. return MissingArgEval.instance;
  566. }
  567. if (ptg instanceof AreaErrPtg ||ptg instanceof RefErrorPtg
  568. || ptg instanceof DeletedArea3DPtg || ptg instanceof DeletedRef3DPtg) {
  569. return ErrorEval.REF_INVALID;
  570. }
  571. if (ptg instanceof Ref3DPtg) {
  572. Ref3DPtg rptg = (Ref3DPtg) ptg;
  573. return ec.getRef3DEval(rptg.getRow(), rptg.getColumn(), rptg.getExternSheetIndex());
  574. }
  575. if (ptg instanceof Area3DPtg) {
  576. Area3DPtg aptg = (Area3DPtg) ptg;
  577. return ec.getArea3DEval(aptg.getFirstRow(), aptg.getFirstColumn(), aptg.getLastRow(), aptg.getLastColumn(), aptg.getExternSheetIndex());
  578. }
  579. if (ptg instanceof RefPtg) {
  580. RefPtg rptg = (RefPtg) ptg;
  581. return ec.getRefEval(rptg.getRow(), rptg.getColumn());
  582. }
  583. if (ptg instanceof AreaPtg) {
  584. AreaPtg aptg = (AreaPtg) ptg;
  585. return ec.getAreaEval(aptg.getFirstRow(), aptg.getFirstColumn(), aptg.getLastRow(), aptg.getLastColumn());
  586. }
  587. if (ptg instanceof UnknownPtg) {
  588. // POI uses UnknownPtg when the encoded Ptg array seems to be corrupted.
  589. // This seems to occur in very rare cases (e.g. unused name formulas in bug 44774, attachment 21790)
  590. // In any case, formulas are re-parsed before execution, so UnknownPtg should not get here
  591. throw new RuntimeException("UnknownPtg not allowed");
  592. }
  593. if (ptg instanceof ExpPtg) {
  594. // ExpPtg is used for array formulas and shared formulas.
  595. // it is currently unsupported, and may not even get implemented here
  596. throw new RuntimeException("ExpPtg currently not supported");
  597. }
  598. throw new RuntimeException("Unexpected ptg class (" + ptg.getClass().getName() + ")");
  599. }
  600. /**
  601. * YK: Used by OperationEvaluationContext to resolve indirect names.
  602. */
  603. /*package*/ ValueEval evaluateNameFormula(Ptg[] ptgs, OperationEvaluationContext ec) {
  604. if (ptgs.length > 1) {
  605. throw new RuntimeException("Complex name formulas not supported yet");
  606. }
  607. return getEvalForPtg(ptgs[0], ec);
  608. }
  609. /**
  610. * Used by the lazy ref evals whenever they need to get the value of a contained cell.
  611. */
  612. /* package */ ValueEval evaluateReference(EvaluationSheet sheet, int sheetIndex, int rowIndex,
  613. int columnIndex, EvaluationTracker tracker) {
  614. EvaluationCell cell = sheet.getCell(rowIndex, columnIndex);
  615. return evaluateAny(cell, sheetIndex, rowIndex, columnIndex, tracker);
  616. }
  617. public FreeRefFunction findUserDefinedFunction(String functionName) {
  618. return _udfFinder.findFunction(functionName);
  619. }
  620. }