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.

OperandResolver.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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.hssf.record.formula.eval;
  16. /**
  17. * Provides functionality for evaluating arguments to functions and operators.
  18. *
  19. * @author Josh Micich
  20. */
  21. public final class OperandResolver {
  22. private OperandResolver() {
  23. // no instances of this class
  24. }
  25. /**
  26. * Retrieves a single value from a variety of different argument types according to standard
  27. * Excel rules. Does not perform any type conversion.
  28. * @param arg the evaluated argument as passed to the function or operator.
  29. * @param srcCellRow used when arg is a single column AreaRef
  30. * @param srcCellCol used when arg is a single row AreaRef
  31. * @return a <tt>NumberEval</tt>, <tt>StringEval</tt>, <tt>BoolEval</tt> or <tt>BlankEval</tt>.
  32. * Never <code>null</code> or <tt>ErrorEval</tt>.
  33. * @throws EvaluationException(#VALUE!) if srcCellRow or srcCellCol do not properly index into
  34. * an AreaEval. If the actual value retrieved is an ErrorEval, a corresponding
  35. * EvaluationException is thrown.
  36. */
  37. public static ValueEval getSingleValue(ValueEval arg, int srcCellRow, int srcCellCol)
  38. throws EvaluationException {
  39. ValueEval result;
  40. if (arg instanceof RefEval) {
  41. result = ((RefEval) arg).getInnerValueEval();
  42. } else if (arg instanceof AreaEval) {
  43. result = chooseSingleElementFromArea((AreaEval) arg, srcCellRow, srcCellCol);
  44. } else {
  45. result = arg;
  46. }
  47. if (result instanceof ErrorEval) {
  48. throw new EvaluationException((ErrorEval) result);
  49. }
  50. return result;
  51. }
  52. /**
  53. * Implements (some perhaps not well known) Excel functionality to select a single cell from an
  54. * area depending on the coordinates of the calling cell. Here is an example demonstrating
  55. * both selection from a single row area and a single column area in the same formula.
  56. *
  57. * <table border="1" cellpadding="1" cellspacing="1" summary="sample spreadsheet">
  58. * <tr><th>&nbsp;</th><th>&nbsp;A&nbsp;</th><th>&nbsp;B&nbsp;</th><th>&nbsp;C&nbsp;</th><th>&nbsp;D&nbsp;</th></tr>
  59. * <tr><th>1</th><td>15</td><td>20</td><td>25</td><td>&nbsp;</td></tr>
  60. * <tr><th>2</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>200</td></tr>
  61. * <tr><th>3</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>300</td></tr>
  62. * <tr><th>3</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>400</td></tr>
  63. * </table>
  64. *
  65. * If the formula "=1000+A1:B1+D2:D3" is put into the 9 cells from A2 to C4, the spreadsheet
  66. * will look like this:
  67. *
  68. * <table border="1" cellpadding="1" cellspacing="1" summary="sample spreadsheet">
  69. * <tr><th>&nbsp;</th><th>&nbsp;A&nbsp;</th><th>&nbsp;B&nbsp;</th><th>&nbsp;C&nbsp;</th><th>&nbsp;D&nbsp;</th></tr>
  70. * <tr><th>1</th><td>15</td><td>20</td><td>25</td><td>&nbsp;</td></tr>
  71. * <tr><th>2</th><td>1215</td><td>1220</td><td>#VALUE!</td><td>200</td></tr>
  72. * <tr><th>3</th><td>1315</td><td>1320</td><td>#VALUE!</td><td>300</td></tr>
  73. * <tr><th>4</th><td>#VALUE!</td><td>#VALUE!</td><td>#VALUE!</td><td>400</td></tr>
  74. * </table>
  75. *
  76. * Note that the row area (A1:B1) does not include column C and the column area (D2:D3) does
  77. * not include row 4, so the values in C1(=25) and D4(=400) are not accessible to the formula
  78. * as written, but in the 4 cells A2:B3, the row and column selection works ok.<p/>
  79. *
  80. * The same concept is extended to references across sheets, such that even multi-row,
  81. * multi-column areas can be useful.<p/>
  82. *
  83. * Of course with carefully (or carelessly) chosen parameters, cyclic references can occur and
  84. * hence this method <b>can</b> throw a 'circular reference' EvaluationException. Note that
  85. * this method does not attempt to detect cycles. Every cell in the specified Area <tt>ae</tt>
  86. * has already been evaluated prior to this method call. Any cell (or cell<b>s</b>) part of
  87. * <tt>ae</tt> that would incur a cyclic reference error if selected by this method, will
  88. * already have the value <t>ErrorEval.CIRCULAR_REF_ERROR</tt> upon entry to this method. It
  89. * is assumed logic exists elsewhere to produce this behaviour.
  90. *
  91. * @return whatever the selected cell's evaluated value is. Never <code>null</code>. Never
  92. * <tt>ErrorEval</tt>.
  93. * @throws EvaluationException if there is a problem with indexing into the area, or if the
  94. * evaluated cell has an error.
  95. */
  96. public static ValueEval chooseSingleElementFromArea(AreaEval ae,
  97. int srcCellRow, int srcCellCol) throws EvaluationException {
  98. ValueEval result = chooseSingleElementFromAreaInternal(ae, srcCellRow, (short) srcCellCol);
  99. if(result == null) {
  100. // This seems to be required because AreaEval.values() array may contain nulls.
  101. // perhaps that should not be allowed.
  102. result = BlankEval.INSTANCE;
  103. }
  104. if (result instanceof ErrorEval) {
  105. throw new EvaluationException((ErrorEval) result);
  106. }
  107. return result;
  108. }
  109. /**
  110. * @return possibly <tt>ErrorEval</tt>, and <code>null</code>
  111. */
  112. private static ValueEval chooseSingleElementFromAreaInternal(AreaEval ae,
  113. int srcCellRow, short srcCellCol) throws EvaluationException {
  114. if(false) {
  115. // this is too simplistic
  116. if(ae.containsRow(srcCellRow) && ae.containsColumn(srcCellCol)) {
  117. throw new EvaluationException(ErrorEval.CIRCULAR_REF_ERROR);
  118. }
  119. /*
  120. Circular references are not dealt with directly here, but it is worth noting some issues.
  121. ANY one of the return statements in this method could return a cell that is identical
  122. to the one immediately being evaluated. The evaluating cell is identified by srcCellRow,
  123. srcCellRow AND sheet. The sheet is not available in any nearby calling method, so that's
  124. one reason why circular references are not easy to detect here. (The sheet of the returned
  125. cell can be obtained from ae if it is an Area3DEval.)
  126. Another reason there's little value in attempting to detect circular references here is
  127. that only direct circular references could be detected. If the cycle involved two or more
  128. cells this method could not detect it.
  129. Logic to detect evaluation cycles of all kinds has been coded in EvaluationCycleDetector
  130. (and HSSFFormulaEvaluator).
  131. */
  132. }
  133. if (ae.isColumn()) {
  134. if(ae.isRow()) {
  135. return ae.getRelativeValue(0, 0);
  136. }
  137. if(!ae.containsRow(srcCellRow)) {
  138. throw EvaluationException.invalidValue();
  139. }
  140. return ae.getValueAt(srcCellRow, ae.getFirstColumn());
  141. }
  142. if(!ae.isRow()) {
  143. // multi-column, multi-row area
  144. if(ae.containsRow(srcCellRow) && ae.containsColumn(srcCellCol)) {
  145. return ae.getValueAt(ae.getFirstRow(), ae.getFirstColumn());
  146. }
  147. throw EvaluationException.invalidValue();
  148. }
  149. if(!ae.containsColumn(srcCellCol)) {
  150. throw EvaluationException.invalidValue();
  151. }
  152. return ae.getValueAt(ae.getFirstRow(), srcCellCol);
  153. }
  154. /**
  155. * Applies some conversion rules if the supplied value is not already an integer.<br/>
  156. * Value is first coerced to a <tt>double</tt> ( See <tt>coerceValueToDouble()</tt> ).
  157. * Note - <tt>BlankEval</tt> is converted to <code>0</code>.<p/>
  158. *
  159. * Excel typically converts doubles to integers by truncating toward negative infinity.<br/>
  160. * The equivalent java code is:<br/>
  161. * &nbsp;&nbsp;<code>return (int)Math.floor(d);</code><br/>
  162. * <b>not</b>:<br/>
  163. * &nbsp;&nbsp;<code>return (int)d; // wrong - rounds toward zero</code>
  164. *
  165. */
  166. public static int coerceValueToInt(ValueEval ev) throws EvaluationException {
  167. if (ev == BlankEval.INSTANCE) {
  168. return 0;
  169. }
  170. double d = coerceValueToDouble(ev);
  171. // Note - the standard java type conversion from double to int truncates toward zero.
  172. // but Math.floor() truncates toward negative infinity
  173. return (int)Math.floor(d);
  174. }
  175. /**
  176. * Applies some conversion rules if the supplied value is not already a number.
  177. * Note - <tt>BlankEval</tt> is converted to {@link NumberEval#ZERO}.
  178. * @param ev must be a {@link NumberEval}, {@link StringEval}, {@link BoolEval} or
  179. * {@link BlankEval}
  180. * @return actual, parsed or interpreted double value (respectively).
  181. * @throws EvaluationException(#VALUE!) only if a StringEval is supplied and cannot be parsed
  182. * as a double (See <tt>parseDouble()</tt> for allowable formats).
  183. * @throws RuntimeException if the supplied parameter is not {@link NumberEval},
  184. * {@link StringEval}, {@link BoolEval} or {@link BlankEval}
  185. */
  186. public static double coerceValueToDouble(ValueEval ev) throws EvaluationException {
  187. if (ev == BlankEval.INSTANCE) {
  188. return 0.0;
  189. }
  190. if (ev instanceof NumericValueEval) {
  191. // this also handles booleans
  192. return ((NumericValueEval)ev).getNumberValue();
  193. }
  194. if (ev instanceof StringEval) {
  195. Double dd = parseDouble(((StringEval) ev).getStringValue());
  196. if (dd == null) {
  197. throw EvaluationException.invalidValue();
  198. }
  199. return dd.doubleValue();
  200. }
  201. throw new RuntimeException("Unexpected arg eval type (" + ev.getClass().getName() + ")");
  202. }
  203. /**
  204. * Converts a string to a double using standard rules that Excel would use.<br/>
  205. * Tolerates currency prefixes, commas, leading and trailing spaces.<p/>
  206. *
  207. * Some examples:<br/>
  208. * " 123 " -&gt; 123.0<br/>
  209. * ".123" -&gt; 0.123<br/>
  210. * These not supported yet:<br/>
  211. * " $ 1,000.00 " -&gt; 1000.0<br/>
  212. * "$1.25E4" -&gt; 12500.0<br/>
  213. * "5**2" -&gt; 500<br/>
  214. * "250%" -&gt; 2.5<br/>
  215. *
  216. * @return <code>null</code> if the specified text cannot be parsed as a number
  217. */
  218. public static Double parseDouble(String pText) {
  219. String text = pText.trim();
  220. if(text.length() < 1) {
  221. return null;
  222. }
  223. boolean isPositive = true;
  224. if(text.charAt(0) == '-') {
  225. isPositive = false;
  226. text= text.substring(1).trim();
  227. }
  228. if(!Character.isDigit(text.charAt(0))) {
  229. // avoid using NumberFormatException to tell when string is not a number
  230. return null;
  231. }
  232. // TODO - support notation like '1E3' (==1000)
  233. double val;
  234. try {
  235. val = Double.parseDouble(text);
  236. } catch (NumberFormatException e) {
  237. return null;
  238. }
  239. return new Double(isPositive ? +val : -val);
  240. }
  241. /**
  242. * @param ve must be a <tt>NumberEval</tt>, <tt>StringEval</tt>, <tt>BoolEval</tt>, or <tt>BlankEval</tt>
  243. * @return the converted string value. never <code>null</code>
  244. */
  245. public static String coerceValueToString(ValueEval ve) {
  246. if (ve instanceof StringValueEval) {
  247. StringValueEval sve = (StringValueEval) ve;
  248. return sve.getStringValue();
  249. }
  250. if (ve == BlankEval.INSTANCE) {
  251. return "";
  252. }
  253. throw new IllegalArgumentException("Unexpected eval class (" + ve.getClass().getName() + ")");
  254. }
  255. /**
  256. * @return <code>null</code> to represent blank values
  257. * @throws EvaluationException if ve is an ErrorEval, or if a string value cannot be converted
  258. */
  259. public static Boolean coerceValueToBoolean(ValueEval ve, boolean stringsAreBlanks) throws EvaluationException {
  260. if (ve == null || ve == BlankEval.INSTANCE) {
  261. // TODO - remove 've == null' condition once AreaEval is fixed
  262. return null;
  263. }
  264. if (ve instanceof BoolEval) {
  265. return Boolean.valueOf(((BoolEval) ve).getBooleanValue());
  266. }
  267. if (ve == BlankEval.INSTANCE) {
  268. return null;
  269. }
  270. if (ve instanceof StringEval) {
  271. if (stringsAreBlanks) {
  272. return null;
  273. }
  274. String str = ((StringEval) ve).getStringValue();
  275. if (str.equalsIgnoreCase("true")) {
  276. return Boolean.TRUE;
  277. }
  278. if (str.equalsIgnoreCase("false")) {
  279. return Boolean.FALSE;
  280. }
  281. // else - string cannot be converted to boolean
  282. throw new EvaluationException(ErrorEval.VALUE_INVALID);
  283. }
  284. if (ve instanceof NumericValueEval) {
  285. NumericValueEval ne = (NumericValueEval) ve;
  286. double d = ne.getNumberValue();
  287. if (Double.isNaN(d)) {
  288. throw new EvaluationException(ErrorEval.VALUE_INVALID);
  289. }
  290. return Boolean.valueOf(d != 0);
  291. }
  292. if (ve instanceof ErrorEval) {
  293. throw new EvaluationException((ErrorEval) ve);
  294. }
  295. throw new RuntimeException("Unexpected eval (" + ve.getClass().getName() + ")");
  296. }
  297. }