選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

OperandResolver.java 16KB

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