您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

WorkbookEvaluator.java 23KB

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