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.

FormulaParser.java 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626
  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.ArrayList;
  17. import java.util.List;
  18. import java.util.regex.Pattern;
  19. import org.apache.poi.ss.SpreadsheetVersion;
  20. import org.apache.poi.ss.formula.constant.ErrorConstant;
  21. import org.apache.poi.ss.formula.function.FunctionMetadata;
  22. import org.apache.poi.ss.formula.function.FunctionMetadataRegistry;
  23. import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg;
  24. import org.apache.poi.ss.formula.ptg.AddPtg;
  25. import org.apache.poi.ss.formula.ptg.AreaPtg;
  26. import org.apache.poi.ss.formula.ptg.ArrayPtg;
  27. import org.apache.poi.ss.formula.ptg.AttrPtg;
  28. import org.apache.poi.ss.formula.ptg.BoolPtg;
  29. import org.apache.poi.ss.formula.ptg.ConcatPtg;
  30. import org.apache.poi.ss.formula.ptg.DividePtg;
  31. import org.apache.poi.ss.formula.ptg.EqualPtg;
  32. import org.apache.poi.ss.formula.ptg.ErrPtg;
  33. import org.apache.poi.ss.formula.ptg.FuncPtg;
  34. import org.apache.poi.ss.formula.ptg.FuncVarPtg;
  35. import org.apache.poi.ss.formula.ptg.GreaterEqualPtg;
  36. import org.apache.poi.ss.formula.ptg.GreaterThanPtg;
  37. import org.apache.poi.ss.formula.ptg.IntersectionPtg;
  38. import org.apache.poi.ss.formula.ptg.IntPtg;
  39. import org.apache.poi.ss.formula.ptg.LessEqualPtg;
  40. import org.apache.poi.ss.formula.ptg.LessThanPtg;
  41. import org.apache.poi.ss.formula.ptg.MemAreaPtg;
  42. import org.apache.poi.ss.formula.ptg.MemFuncPtg;
  43. import org.apache.poi.ss.formula.ptg.MissingArgPtg;
  44. import org.apache.poi.ss.formula.ptg.MultiplyPtg;
  45. import org.apache.poi.ss.formula.ptg.NamePtg;
  46. import org.apache.poi.ss.formula.ptg.NameXPtg;
  47. import org.apache.poi.ss.formula.ptg.NotEqualPtg;
  48. import org.apache.poi.ss.formula.ptg.NumberPtg;
  49. import org.apache.poi.ss.formula.ptg.OperandPtg;
  50. import org.apache.poi.ss.formula.ptg.OperationPtg;
  51. import org.apache.poi.ss.formula.ptg.ParenthesisPtg;
  52. import org.apache.poi.ss.formula.ptg.PercentPtg;
  53. import org.apache.poi.ss.formula.ptg.PowerPtg;
  54. import org.apache.poi.ss.formula.ptg.Ptg;
  55. import org.apache.poi.ss.formula.ptg.RangePtg;
  56. import org.apache.poi.ss.formula.ptg.RefPtg;
  57. import org.apache.poi.ss.formula.ptg.StringPtg;
  58. import org.apache.poi.ss.formula.ptg.SubtractPtg;
  59. import org.apache.poi.ss.formula.ptg.UnaryMinusPtg;
  60. import org.apache.poi.ss.formula.ptg.UnaryPlusPtg;
  61. import org.apache.poi.ss.formula.ptg.UnionPtg;
  62. import org.apache.poi.ss.formula.ptg.ValueOperatorPtg;
  63. import org.apache.poi.ss.usermodel.ErrorConstants;
  64. import org.apache.poi.ss.util.AreaReference;
  65. import org.apache.poi.ss.util.CellReference;
  66. import org.apache.poi.ss.util.CellReference.NameType;
  67. /**
  68. * This class parses a formula string into a List of tokens in RPN order.
  69. * Inspired by
  70. * Lets Build a Compiler, by Jack Crenshaw
  71. * BNF for the formula expression is :
  72. * <expression> ::= <term> [<addop> <term>]*
  73. * <term> ::= <factor> [ <mulop> <factor> ]*
  74. * <factor> ::= <number> | (<expression>) | <cellRef> | <function>
  75. * <function> ::= <functionName> ([expression [, expression]*])
  76. * <p/>
  77. * For POI internal use only
  78. * <p/>
  79. */
  80. public final class FormulaParser {
  81. private final String _formulaString;
  82. private final int _formulaLength;
  83. /** points at the next character to be read (after the {@link #look} char) */
  84. private int _pointer;
  85. private ParseNode _rootNode;
  86. private final static char TAB = '\t'; // HSSF + XSSF
  87. private final static char CR = '\r'; // Normally just XSSF
  88. private final static char LF = '\n'; // Normally just XSSF
  89. /**
  90. * Lookahead Character.
  91. * gets value '\0' when the input string is exhausted
  92. */
  93. private char look;
  94. /**
  95. * Tracks whether the run of whitespace preceeding "look" could be an
  96. * intersection operator. See GetChar.
  97. */
  98. private boolean _inIntersection = false;
  99. private FormulaParsingWorkbook _book;
  100. private SpreadsheetVersion _ssVersion;
  101. private int _sheetIndex;
  102. /**
  103. * Create the formula parser, with the string that is to be
  104. * parsed against the supplied workbook.
  105. * A later call the parse() method to return ptg list in
  106. * rpn order, then call the getRPNPtg() to retrieve the
  107. * parse results.
  108. * This class is recommended only for single threaded use.
  109. *
  110. * If you only have a usermodel.HSSFWorkbook, and not a
  111. * model.Workbook, then use the convenience method on
  112. * usermodel.HSSFFormulaEvaluator
  113. */
  114. private FormulaParser(String formula, FormulaParsingWorkbook book, int sheetIndex){
  115. _formulaString = formula;
  116. _pointer=0;
  117. _book = book;
  118. _ssVersion = book == null ? SpreadsheetVersion.EXCEL97 : book.getSpreadsheetVersion();
  119. _formulaLength = _formulaString.length();
  120. _sheetIndex = sheetIndex;
  121. }
  122. /**
  123. * Parse a formula into a array of tokens
  124. *
  125. * @param formula the formula to parse
  126. * @param workbook the parent workbook
  127. * @param formulaType the type of the formula, see {@link FormulaType}
  128. * @param sheetIndex the 0-based index of the sheet this formula belongs to.
  129. * The sheet index is required to resolve sheet-level names. <code>-1</code> means that
  130. * the scope of the name will be ignored and the parser will match names only by name
  131. *
  132. * @return array of parsed tokens
  133. * @throws FormulaParseException if the formula has incorrect syntax or is otherwise invalid
  134. */
  135. public static Ptg[] parse(String formula, FormulaParsingWorkbook workbook, int formulaType, int sheetIndex) {
  136. FormulaParser fp = new FormulaParser(formula, workbook, sheetIndex);
  137. fp.parse();
  138. return fp.getRPNPtg(formulaType);
  139. }
  140. /** Read New Character From Input Stream */
  141. private void GetChar() {
  142. // The intersection operator is a space. We track whether the run of
  143. // whitespace preceeding "look" counts as an intersection operator.
  144. if (IsWhite(look)) {
  145. if (look == ' ') {
  146. _inIntersection = true;
  147. }
  148. }
  149. else {
  150. _inIntersection = false;
  151. }
  152. // Check to see if we've walked off the end of the string.
  153. if (_pointer > _formulaLength) {
  154. throw new RuntimeException("too far");
  155. }
  156. if (_pointer < _formulaLength) {
  157. look=_formulaString.charAt(_pointer);
  158. } else {
  159. // Just return if so and reset 'look' to something to keep
  160. // SkipWhitespace from spinning
  161. look = (char)0;
  162. _inIntersection = false;
  163. }
  164. _pointer++;
  165. //System.out.println("Got char: "+ look);
  166. }
  167. private void resetPointer(int ptr) {
  168. _pointer = ptr;
  169. if (_pointer <= _formulaLength) {
  170. look=_formulaString.charAt(_pointer-1);
  171. } else {
  172. // Just return if so and reset 'look' to something to keep
  173. // SkipWhitespace from spinning
  174. look = (char)0;
  175. }
  176. }
  177. /** Report What Was Expected */
  178. private RuntimeException expected(String s) {
  179. String msg;
  180. if (look == '=' && _formulaString.substring(0, _pointer-1).trim().length() < 1) {
  181. msg = "The specified formula '" + _formulaString
  182. + "' starts with an equals sign which is not allowed.";
  183. } else {
  184. msg = "Parse error near char " + (_pointer-1) + " '" + look + "'"
  185. + " in specified formula '" + _formulaString + "'. Expected "
  186. + s;
  187. }
  188. return new FormulaParseException(msg);
  189. }
  190. /** Recognize an Alpha Character */
  191. private static boolean IsAlpha(char c) {
  192. return Character.isLetter(c) || c == '$' || c=='_';
  193. }
  194. /** Recognize a Decimal Digit */
  195. private static boolean IsDigit(char c) {
  196. return Character.isDigit(c);
  197. }
  198. /** Recognize White Space */
  199. private static boolean IsWhite( char c) {
  200. return c ==' ' || c== TAB || c == CR || c == LF;
  201. }
  202. /** Skip Over Leading White Space */
  203. private void SkipWhite() {
  204. while (IsWhite(look)) {
  205. GetChar();
  206. }
  207. }
  208. /**
  209. * Consumes the next input character if it is equal to the one specified otherwise throws an
  210. * unchecked exception. This method does <b>not</b> consume whitespace (before or after the
  211. * matched character).
  212. */
  213. private void Match(char x) {
  214. if (look != x) {
  215. throw expected("'" + x + "'");
  216. }
  217. GetChar();
  218. }
  219. /** Get a Number */
  220. private String GetNum() {
  221. StringBuffer value = new StringBuffer();
  222. while (IsDigit(this.look)){
  223. value.append(this.look);
  224. GetChar();
  225. }
  226. return value.length() == 0 ? null : value.toString();
  227. }
  228. private ParseNode parseRangeExpression() {
  229. ParseNode result = parseRangeable();
  230. boolean hasRange = false;
  231. while (look == ':') {
  232. int pos = _pointer;
  233. GetChar();
  234. ParseNode nextPart = parseRangeable();
  235. // Note - no range simplification here. An expr like "A1:B2:C3:D4:E5" should be
  236. // grouped into area ref pairs like: "(A1:B2):(C3:D4):E5"
  237. // Furthermore, Excel doesn't seem to simplify
  238. // expressions like "Sheet1!A1:Sheet1:B2" into "Sheet1!A1:B2"
  239. checkValidRangeOperand("LHS", pos, result);
  240. checkValidRangeOperand("RHS", pos, nextPart);
  241. ParseNode[] children = { result, nextPart, };
  242. result = new ParseNode(RangePtg.instance, children);
  243. hasRange = true;
  244. }
  245. if (hasRange) {
  246. return augmentWithMemPtg(result);
  247. }
  248. return result;
  249. }
  250. private static ParseNode augmentWithMemPtg(ParseNode root) {
  251. Ptg memPtg;
  252. if (needsMemFunc(root)) {
  253. memPtg = new MemFuncPtg(root.getEncodedSize());
  254. } else {
  255. memPtg = new MemAreaPtg(root.getEncodedSize());
  256. }
  257. return new ParseNode(memPtg, root);
  258. }
  259. /**
  260. * From OOO doc: "Whenever one operand of the reference subexpression is a function,
  261. * a defined name, a 3D reference, or an external reference (and no error occurs),
  262. * a tMemFunc token is used"
  263. *
  264. */
  265. private static boolean needsMemFunc(ParseNode root) {
  266. Ptg token = root.getToken();
  267. if (token instanceof AbstractFunctionPtg) {
  268. return true;
  269. }
  270. if (token instanceof ExternSheetReferenceToken) { // 3D refs
  271. return true;
  272. }
  273. if (token instanceof NamePtg || token instanceof NameXPtg) { // 3D refs
  274. return true;
  275. }
  276. if (token instanceof OperationPtg || token instanceof ParenthesisPtg) {
  277. // expect RangePtg, but perhaps also UnionPtg, IntersectionPtg etc
  278. for(ParseNode child : root.getChildren()) {
  279. if (needsMemFunc(child)) {
  280. return true;
  281. }
  282. }
  283. return false;
  284. }
  285. if (token instanceof OperandPtg) {
  286. return false;
  287. }
  288. if (token instanceof OperationPtg) {
  289. return true;
  290. }
  291. return false;
  292. }
  293. /**
  294. * @param currentParsePosition used to format a potential error message
  295. */
  296. private static void checkValidRangeOperand(String sideName, int currentParsePosition, ParseNode pn) {
  297. if (!isValidRangeOperand(pn)) {
  298. throw new FormulaParseException("The " + sideName
  299. + " of the range operator ':' at position "
  300. + currentParsePosition + " is not a proper reference.");
  301. }
  302. }
  303. /**
  304. * @return <code>false</code> if sub-expression represented the specified ParseNode definitely
  305. * cannot appear on either side of the range (':') operator
  306. */
  307. private static boolean isValidRangeOperand(ParseNode a) {
  308. Ptg tkn = a.getToken();
  309. // Note - order is important for these instance-of checks
  310. if (tkn instanceof OperandPtg) {
  311. // notably cell refs and area refs
  312. return true;
  313. }
  314. // next 2 are special cases of OperationPtg
  315. if (tkn instanceof AbstractFunctionPtg) {
  316. AbstractFunctionPtg afp = (AbstractFunctionPtg) tkn;
  317. byte returnClass = afp.getDefaultOperandClass();
  318. return Ptg.CLASS_REF == returnClass;
  319. }
  320. if (tkn instanceof ValueOperatorPtg) {
  321. return false;
  322. }
  323. if (tkn instanceof OperationPtg) {
  324. return true;
  325. }
  326. // one special case of ControlPtg
  327. if (tkn instanceof ParenthesisPtg) {
  328. // parenthesis Ptg should have only one child
  329. return isValidRangeOperand(a.getChildren()[0]);
  330. }
  331. // one special case of ScalarConstantPtg
  332. if (tkn == ErrPtg.REF_INVALID) {
  333. return true;
  334. }
  335. // All other ControlPtgs and ScalarConstantPtgs cannot be used with ':'
  336. return false;
  337. }
  338. /**
  339. * Parses area refs (things which could be the operand of ':') and simple factors
  340. * Examples
  341. * <pre>
  342. * A$1
  343. * $A$1 : $B1
  344. * A1 ....... C2
  345. * Sheet1 !$A1
  346. * a..b!A1
  347. * 'my sheet'!A1
  348. * .my.sheet!A1
  349. * 'my sheet':'my alt sheet'!A1
  350. * .my.sheet1:.my.sheet2!$B$2
  351. * my.named..range.
  352. * 'my sheet'!my.named.range
  353. * .my.sheet!my.named.range
  354. * foo.bar(123.456, "abc")
  355. * 123.456
  356. * "abc"
  357. * true
  358. * [Foo.xls]!$A$1
  359. * [Foo.xls]'my sheet'!$A$1
  360. * [Foo.xls]!my.named.range
  361. * </pre>
  362. *
  363. */
  364. private ParseNode parseRangeable() {
  365. SkipWhite();
  366. int savePointer = _pointer;
  367. SheetIdentifier sheetIden = parseSheetName();
  368. if (sheetIden == null) {
  369. resetPointer(savePointer);
  370. } else {
  371. SkipWhite();
  372. savePointer = _pointer;
  373. }
  374. SimpleRangePart part1 = parseSimpleRangePart();
  375. if (part1 == null) {
  376. if (sheetIden != null) {
  377. if(look == '#'){ // error ref like MySheet!#REF!
  378. return new ParseNode(ErrPtg.valueOf(parseErrorLiteral()));
  379. } else {
  380. // Is it a named range?
  381. String name = parseAsName();
  382. if (name.length() == 0) {
  383. throw new FormulaParseException("Cell reference or Named Range "
  384. + "expected after sheet name at index " + _pointer + ".");
  385. }
  386. Ptg nameXPtg = _book.getNameXPtg(name, sheetIden);
  387. if (nameXPtg == null) {
  388. throw new FormulaParseException("Specified name '" + name +
  389. "' for sheet " + sheetIden.asFormulaString() + " not found");
  390. }
  391. return new ParseNode(nameXPtg);
  392. }
  393. }
  394. return parseNonRange(savePointer);
  395. }
  396. boolean whiteAfterPart1 = IsWhite(look);
  397. if (whiteAfterPart1) {
  398. SkipWhite();
  399. }
  400. if (look == ':') {
  401. int colonPos = _pointer;
  402. GetChar();
  403. SkipWhite();
  404. SimpleRangePart part2 = parseSimpleRangePart();
  405. if (part2 != null && !part1.isCompatibleForArea(part2)) {
  406. // second part is not compatible with an area ref e.g. S!A1:S!B2
  407. // where S might be a sheet name (that looks like a column name)
  408. part2 = null;
  409. }
  410. if (part2 == null) {
  411. // second part is not compatible with an area ref e.g. A1:OFFSET(B2, 1, 2)
  412. // reset and let caller use explicit range operator
  413. resetPointer(colonPos);
  414. if (!part1.isCell()) {
  415. String prefix;
  416. if (sheetIden == null) {
  417. prefix = "";
  418. } else {
  419. prefix = "'" + sheetIden.getSheetIdentifier().getName() + '!';
  420. }
  421. throw new FormulaParseException(prefix + part1.getRep() + "' is not a proper reference.");
  422. }
  423. return createAreaRefParseNode(sheetIden, part1, part2);
  424. }
  425. return createAreaRefParseNode(sheetIden, part1, part2);
  426. }
  427. if (look == '.') {
  428. GetChar();
  429. int dotCount = 1;
  430. while (look =='.') {
  431. dotCount ++;
  432. GetChar();
  433. }
  434. boolean whiteBeforePart2 = IsWhite(look);
  435. SkipWhite();
  436. SimpleRangePart part2 = parseSimpleRangePart();
  437. String part1And2 = _formulaString.substring(savePointer-1, _pointer-1);
  438. if (part2 == null) {
  439. if (sheetIden != null) {
  440. throw new FormulaParseException("Complete area reference expected after sheet name at index "
  441. + _pointer + ".");
  442. }
  443. return parseNonRange(savePointer);
  444. }
  445. if (whiteAfterPart1 || whiteBeforePart2) {
  446. if (part1.isRowOrColumn() || part2.isRowOrColumn()) {
  447. // "A .. B" not valid syntax for "A:B"
  448. // and there's no other valid expression that fits this grammar
  449. throw new FormulaParseException("Dotted range (full row or column) expression '"
  450. + part1And2 + "' must not contain whitespace.");
  451. }
  452. return createAreaRefParseNode(sheetIden, part1, part2);
  453. }
  454. if (dotCount == 1 && part1.isRow() && part2.isRow()) {
  455. // actually, this is looking more like a number
  456. return parseNonRange(savePointer);
  457. }
  458. if (part1.isRowOrColumn() || part2.isRowOrColumn()) {
  459. if (dotCount != 2) {
  460. throw new FormulaParseException("Dotted range (full row or column) expression '" + part1And2
  461. + "' must have exactly 2 dots.");
  462. }
  463. }
  464. return createAreaRefParseNode(sheetIden, part1, part2);
  465. }
  466. if (part1.isCell() && isValidCellReference(part1.getRep())) {
  467. return createAreaRefParseNode(sheetIden, part1, null);
  468. }
  469. if (sheetIden != null) {
  470. throw new FormulaParseException("Second part of cell reference expected after sheet name at index "
  471. + _pointer + ".");
  472. }
  473. return parseNonRange(savePointer);
  474. }
  475. /**
  476. * Parses simple factors that are not primitive ranges or range components
  477. * i.e. '!', ':'(and equiv '...') do not appear
  478. * Examples
  479. * <pre>
  480. * my.named...range.
  481. * foo.bar(123.456, "abc")
  482. * 123.456
  483. * "abc"
  484. * true
  485. * </pre>
  486. */
  487. private ParseNode parseNonRange(int savePointer) {
  488. resetPointer(savePointer);
  489. if (Character.isDigit(look)) {
  490. return new ParseNode(parseNumber());
  491. }
  492. if (look == '"') {
  493. return new ParseNode(new StringPtg(parseStringLiteral()));
  494. }
  495. // from now on we can only be dealing with non-quoted identifiers
  496. // which will either be named ranges or functions
  497. String name = parseAsName();
  498. if (look == '(') {
  499. return function(name);
  500. }
  501. if (name.equalsIgnoreCase("TRUE") || name.equalsIgnoreCase("FALSE")) {
  502. return new ParseNode(BoolPtg.valueOf(name.equalsIgnoreCase("TRUE")));
  503. }
  504. if (_book == null) {
  505. // Only test cases omit the book (expecting it not to be needed)
  506. throw new IllegalStateException("Need book to evaluate name '" + name + "'");
  507. }
  508. EvaluationName evalName = _book.getName(name, _sheetIndex);
  509. if (evalName == null) {
  510. throw new FormulaParseException("Specified named range '"
  511. + name + "' does not exist in the current workbook.");
  512. }
  513. if (evalName.isRange()) {
  514. return new ParseNode(evalName.createPtg());
  515. }
  516. // TODO - what about NameX ?
  517. throw new FormulaParseException("Specified name '"
  518. + name + "' is not a range as expected.");
  519. }
  520. private String parseAsName() {
  521. StringBuilder sb = new StringBuilder();
  522. // defined names may begin with a letter or underscore
  523. if (!Character.isLetter(look) && look != '_') {
  524. throw expected("number, string, or defined name");
  525. }
  526. while (isValidDefinedNameChar(look)) {
  527. sb.append(look);
  528. GetChar();
  529. }
  530. SkipWhite();
  531. return sb.toString();
  532. }
  533. /**
  534. *
  535. * @return <code>true</code> if the specified character may be used in a defined name
  536. */
  537. private static boolean isValidDefinedNameChar(char ch) {
  538. if (Character.isLetterOrDigit(ch)) {
  539. return true;
  540. }
  541. switch (ch) {
  542. case '.':
  543. case '_':
  544. case '?':
  545. case '\\': // of all things
  546. return true;
  547. }
  548. return false;
  549. }
  550. /**
  551. *
  552. * @param sheetIden may be <code>null</code>
  553. * @param part1
  554. * @param part2 may be <code>null</code>
  555. */
  556. private ParseNode createAreaRefParseNode(SheetIdentifier sheetIden, SimpleRangePart part1,
  557. SimpleRangePart part2) throws FormulaParseException {
  558. Ptg ptg;
  559. if (part2 == null) {
  560. CellReference cr = part1.getCellReference();
  561. if (sheetIden == null) {
  562. ptg = new RefPtg(cr);
  563. } else {
  564. ptg = _book.get3DReferencePtg(cr, sheetIden);
  565. }
  566. } else {
  567. AreaReference areaRef = createAreaRef(part1, part2);
  568. if (sheetIden == null) {
  569. ptg = new AreaPtg(areaRef);
  570. } else {
  571. ptg = _book.get3DReferencePtg(areaRef, sheetIden);
  572. }
  573. }
  574. return new ParseNode(ptg);
  575. }
  576. private AreaReference createAreaRef(SimpleRangePart part1, SimpleRangePart part2) {
  577. if (!part1.isCompatibleForArea(part2)) {
  578. throw new FormulaParseException("has incompatible parts: '"
  579. + part1.getRep() + "' and '" + part2.getRep() + "'.");
  580. }
  581. if (part1.isRow()) {
  582. return AreaReference.getWholeRow(_ssVersion, part1.getRep(), part2.getRep());
  583. }
  584. if (part1.isColumn()) {
  585. return AreaReference.getWholeColumn(_ssVersion, part1.getRep(), part2.getRep());
  586. }
  587. return new AreaReference(part1.getCellReference(), part2.getCellReference());
  588. }
  589. /**
  590. * Matches a zero or one letter-runs followed by zero or one digit-runs.
  591. * Either or both runs man optionally be prefixed with a single '$'.
  592. * (copied+modified from {@link org.apache.poi.ss.util.CellReference#CELL_REF_PATTERN})
  593. */
  594. private static final Pattern CELL_REF_PATTERN = Pattern.compile("(\\$?[A-Za-z]+)?(\\$?[0-9]+)?");
  595. /**
  596. * Parses out a potential LHS or RHS of a ':' intended to produce a plain AreaRef. Normally these are
  597. * proper cell references but they could also be row or column refs like "$AC" or "10"
  598. * @return <code>null</code> (and leaves {@link #_pointer} unchanged if a proper range part does not parse out
  599. */
  600. private SimpleRangePart parseSimpleRangePart() {
  601. int ptr = _pointer-1; // TODO avoid StringIndexOutOfBounds
  602. boolean hasDigits = false;
  603. boolean hasLetters = false;
  604. while (ptr < _formulaLength) {
  605. char ch = _formulaString.charAt(ptr);
  606. if (Character.isDigit(ch)) {
  607. hasDigits = true;
  608. } else if (Character.isLetter(ch)) {
  609. hasLetters = true;
  610. } else if (ch =='$' || ch =='_') {
  611. //
  612. } else {
  613. break;
  614. }
  615. ptr++;
  616. }
  617. if (ptr <= _pointer-1) {
  618. return null;
  619. }
  620. String rep = _formulaString.substring(_pointer-1, ptr);
  621. if (!CELL_REF_PATTERN.matcher(rep).matches()) {
  622. return null;
  623. }
  624. // Check range bounds against grid max
  625. if (hasLetters && hasDigits) {
  626. if (!isValidCellReference(rep)) {
  627. return null;
  628. }
  629. } else if (hasLetters) {
  630. if (!CellReference.isColumnWithnRange(rep.replace("$", ""), _ssVersion)) {
  631. return null;
  632. }
  633. } else if (hasDigits) {
  634. int i;
  635. try {
  636. i = Integer.parseInt(rep.replace("$", ""));
  637. } catch (NumberFormatException e) {
  638. return null;
  639. }
  640. if (i<1 || i>_ssVersion.getMaxRows()) {
  641. return null;
  642. }
  643. } else {
  644. // just dollars ? can this happen?
  645. return null;
  646. }
  647. resetPointer(ptr+1); // stepping forward
  648. return new SimpleRangePart(rep, hasLetters, hasDigits);
  649. }
  650. /**
  651. * A1, $A1, A$1, $A$1, A, 1
  652. */
  653. private static final class SimpleRangePart {
  654. private enum Type {
  655. CELL, ROW, COLUMN;
  656. public static Type get(boolean hasLetters, boolean hasDigits) {
  657. if (hasLetters) {
  658. return hasDigits ? CELL : COLUMN;
  659. }
  660. if (!hasDigits) {
  661. throw new IllegalArgumentException("must have either letters or numbers");
  662. }
  663. return ROW;
  664. }
  665. }
  666. private final Type _type;
  667. private final String _rep;
  668. public SimpleRangePart(String rep, boolean hasLetters, boolean hasNumbers) {
  669. _rep = rep;
  670. _type = Type.get(hasLetters, hasNumbers);
  671. }
  672. public boolean isCell() {
  673. return _type == Type.CELL;
  674. }
  675. public boolean isRowOrColumn() {
  676. return _type != Type.CELL;
  677. }
  678. public CellReference getCellReference() {
  679. if (_type != Type.CELL) {
  680. throw new IllegalStateException("Not applicable to this type");
  681. }
  682. return new CellReference(_rep);
  683. }
  684. public boolean isColumn() {
  685. return _type == Type.COLUMN;
  686. }
  687. public boolean isRow() {
  688. return _type == Type.ROW;
  689. }
  690. public String getRep() {
  691. return _rep;
  692. }
  693. /**
  694. * @return <code>true</code> if the two range parts can be combined in an
  695. * {@link AreaPtg} ( Note - the explicit range operator (:) may still be valid
  696. * when this method returns <code>false</code> )
  697. */
  698. public boolean isCompatibleForArea(SimpleRangePart part2) {
  699. return _type == part2._type;
  700. }
  701. @Override
  702. public String toString() {
  703. StringBuilder sb = new StringBuilder(64);
  704. sb.append(getClass().getName()).append(" [");
  705. sb.append(_rep);
  706. sb.append("]");
  707. return sb.toString();
  708. }
  709. }
  710. /**
  711. * Note - caller should reset {@link #_pointer} upon <code>null</code> result
  712. * @return The sheet name as an identifier <code>null</code> if '!' is not found in the right place
  713. */
  714. private SheetIdentifier parseSheetName() {
  715. String bookName;
  716. if (look == '[') {
  717. StringBuilder sb = new StringBuilder();
  718. GetChar();
  719. while (look != ']') {
  720. sb.append(look);
  721. GetChar();
  722. }
  723. GetChar();
  724. bookName = sb.toString();
  725. } else {
  726. bookName = null;
  727. }
  728. if (look == '\'') {
  729. StringBuffer sb = new StringBuffer();
  730. Match('\'');
  731. boolean done = look == '\'';
  732. while(!done) {
  733. sb.append(look);
  734. GetChar();
  735. if(look == '\'')
  736. {
  737. Match('\'');
  738. done = look != '\'';
  739. }
  740. }
  741. NameIdentifier iden = new NameIdentifier(sb.toString(), true);
  742. // quoted identifier - can't concatenate anything more
  743. SkipWhite();
  744. if (look == '!') {
  745. GetChar();
  746. return new SheetIdentifier(bookName, iden);
  747. }
  748. // See if it's a multi-sheet range, eg Sheet1:Sheet3!A1
  749. if (look == ':') {
  750. return parseSheetRange(bookName, iden);
  751. }
  752. return null;
  753. }
  754. // unquoted sheet names must start with underscore or a letter
  755. if (look =='_' || Character.isLetter(look)) {
  756. StringBuilder sb = new StringBuilder();
  757. // can concatenate idens with dots
  758. while (isUnquotedSheetNameChar(look)) {
  759. sb.append(look);
  760. GetChar();
  761. }
  762. NameIdentifier iden = new NameIdentifier(sb.toString(), false);
  763. SkipWhite();
  764. if (look == '!') {
  765. GetChar();
  766. return new SheetIdentifier(bookName, iden);
  767. }
  768. // See if it's a multi-sheet range, eg Sheet1:Sheet3!A1
  769. if (look == ':') {
  770. return parseSheetRange(bookName, iden);
  771. }
  772. return null;
  773. }
  774. if (look == '!' && bookName != null) {
  775. // Raw book reference, without a sheet
  776. GetChar();
  777. return new SheetIdentifier(bookName, null);
  778. }
  779. return null;
  780. }
  781. /**
  782. * If we have something that looks like [book]Sheet1: or
  783. * Sheet1, see if it's actually a range eg Sheet1:Sheet2!
  784. */
  785. private SheetIdentifier parseSheetRange(String bookname, NameIdentifier sheet1Name) {
  786. GetChar();
  787. SheetIdentifier sheet2 = parseSheetName();
  788. if (sheet2 != null) {
  789. return new SheetRangeIdentifier(bookname, sheet1Name, sheet2.getSheetIdentifier());
  790. }
  791. return null;
  792. }
  793. /**
  794. * very similar to {@link SheetNameFormatter#isSpecialChar(char)}
  795. */
  796. private static boolean isUnquotedSheetNameChar(char ch) {
  797. if(Character.isLetterOrDigit(ch)) {
  798. return true;
  799. }
  800. switch(ch) {
  801. case '.': // dot is OK
  802. case '_': // underscore is OK
  803. return true;
  804. }
  805. return false;
  806. }
  807. /**
  808. * @return <code>true</code> if the specified name is a valid cell reference
  809. */
  810. private boolean isValidCellReference(String str) {
  811. //check range bounds against grid max
  812. boolean result = CellReference.classifyCellReference(str, _ssVersion) == NameType.CELL;
  813. if(result){
  814. /**
  815. * Check if the argument is a function. Certain names can be either a cell reference or a function name
  816. * depending on the contenxt. Compare the following examples in Excel 2007:
  817. * (a) LOG10(100) + 1
  818. * (b) LOG10 + 1
  819. * In (a) LOG10 is a name of a built-in function. In (b) LOG10 is a cell reference
  820. */
  821. boolean isFunc = FunctionMetadataRegistry.getFunctionByName(str.toUpperCase()) != null;
  822. if(isFunc){
  823. int savePointer = _pointer;
  824. resetPointer(_pointer + str.length());
  825. SkipWhite();
  826. // open bracket indicates that the argument is a function,
  827. // the returning value should be false, i.e. "not a valid cell reference"
  828. result = look != '(';
  829. resetPointer(savePointer);
  830. }
  831. }
  832. return result;
  833. }
  834. /**
  835. * Note - Excel function names are 'case aware but not case sensitive'. This method may end
  836. * up creating a defined name record in the workbook if the specified name is not an internal
  837. * Excel function, and has not been encountered before.
  838. *
  839. * @param name case preserved function name (as it was entered/appeared in the formula).
  840. */
  841. private ParseNode function(String name) {
  842. Ptg nameToken = null;
  843. if(!AbstractFunctionPtg.isBuiltInFunctionName(name)) {
  844. // user defined function
  845. // in the token tree, the name is more or less the first argument
  846. if (_book == null) {
  847. // Only test cases omit the book (expecting it not to be needed)
  848. throw new IllegalStateException("Need book to evaluate name '" + name + "'");
  849. }
  850. EvaluationName hName = _book.getName(name, _sheetIndex);
  851. if (hName == null) {
  852. nameToken = _book.getNameXPtg(name, null);
  853. if (nameToken == null) {
  854. throw new FormulaParseException("Name '" + name
  855. + "' is completely unknown in the current workbook");
  856. }
  857. } else {
  858. if (!hName.isFunctionName()) {
  859. throw new FormulaParseException("Attempt to use name '" + name
  860. + "' as a function, but defined name in workbook does not refer to a function");
  861. }
  862. // calls to user-defined functions within the workbook
  863. // get a Name token which points to a defined name record
  864. nameToken = hName.createPtg();
  865. }
  866. }
  867. Match('(');
  868. ParseNode[] args = Arguments();
  869. Match(')');
  870. return getFunction(name, nameToken, args);
  871. }
  872. /**
  873. * Generates the variable function ptg for the formula.
  874. * <p>
  875. * For IF Formulas, additional PTGs are added to the tokens
  876. * @param name a {@link NamePtg} or {@link NameXPtg} or <code>null</code>
  877. * @return Ptg a null is returned if we're in an IF formula, it needs extreme manipulation and is handled in this function
  878. */
  879. private ParseNode getFunction(String name, Ptg namePtg, ParseNode[] args) {
  880. FunctionMetadata fm = FunctionMetadataRegistry.getFunctionByName(name.toUpperCase());
  881. int numArgs = args.length;
  882. if(fm == null) {
  883. if (namePtg == null) {
  884. throw new IllegalStateException("NamePtg must be supplied for external functions");
  885. }
  886. // must be external function
  887. ParseNode[] allArgs = new ParseNode[numArgs+1];
  888. allArgs[0] = new ParseNode(namePtg);
  889. System.arraycopy(args, 0, allArgs, 1, numArgs);
  890. return new ParseNode(FuncVarPtg.create(name, numArgs+1), allArgs);
  891. }
  892. if (namePtg != null) {
  893. throw new IllegalStateException("NamePtg no applicable to internal functions");
  894. }
  895. boolean isVarArgs = !fm.hasFixedArgsLength();
  896. int funcIx = fm.getIndex();
  897. if (funcIx == FunctionMetadataRegistry.FUNCTION_INDEX_SUM && args.length == 1) {
  898. // Excel encodes the sum of a single argument as tAttrSum
  899. // POI does the same for consistency, but this is not critical
  900. return new ParseNode(AttrPtg.getSumSingle(), args);
  901. // The code below would encode tFuncVar(SUM) which seems to do no harm
  902. }
  903. validateNumArgs(args.length, fm);
  904. AbstractFunctionPtg retval;
  905. if(isVarArgs) {
  906. retval = FuncVarPtg.create(name, numArgs);
  907. } else {
  908. retval = FuncPtg.create(funcIx);
  909. }
  910. return new ParseNode(retval, args);
  911. }
  912. private void validateNumArgs(int numArgs, FunctionMetadata fm) {
  913. if(numArgs < fm.getMinParams()) {
  914. String msg = "Too few arguments to function '" + fm.getName() + "'. ";
  915. if(fm.hasFixedArgsLength()) {
  916. msg += "Expected " + fm.getMinParams();
  917. } else {
  918. msg += "At least " + fm.getMinParams() + " were expected";
  919. }
  920. msg += " but got " + numArgs + ".";
  921. throw new FormulaParseException(msg);
  922. }
  923. //the maximum number of arguments depends on the Excel version
  924. int maxArgs;
  925. if (fm.hasUnlimitedVarags()) {
  926. if(_book != null) {
  927. maxArgs = _book.getSpreadsheetVersion().getMaxFunctionArgs();
  928. } else {
  929. //_book can be omitted by test cases
  930. maxArgs = fm.getMaxParams(); // just use BIFF8
  931. }
  932. } else {
  933. maxArgs = fm.getMaxParams();
  934. }
  935. if(numArgs > maxArgs) {
  936. String msg = "Too many arguments to function '" + fm.getName() + "'. ";
  937. if(fm.hasFixedArgsLength()) {
  938. msg += "Expected " + maxArgs;
  939. } else {
  940. msg += "At most " + maxArgs + " were expected";
  941. }
  942. msg += " but got " + numArgs + ".";
  943. throw new FormulaParseException(msg);
  944. }
  945. }
  946. private static boolean isArgumentDelimiter(char ch) {
  947. return ch == ',' || ch == ')';
  948. }
  949. /** get arguments to a function */
  950. private ParseNode[] Arguments() {
  951. //average 2 args per function
  952. List<ParseNode> temp = new ArrayList<ParseNode>(2);
  953. SkipWhite();
  954. if(look == ')') {
  955. return ParseNode.EMPTY_ARRAY;
  956. }
  957. boolean missedPrevArg = true;
  958. while (true) {
  959. SkipWhite();
  960. if (isArgumentDelimiter(look)) {
  961. if (missedPrevArg) {
  962. temp.add(new ParseNode(MissingArgPtg.instance));
  963. }
  964. if (look == ')') {
  965. break;
  966. }
  967. Match(',');
  968. missedPrevArg = true;
  969. continue;
  970. }
  971. temp.add(comparisonExpression());
  972. missedPrevArg = false;
  973. SkipWhite();
  974. if (!isArgumentDelimiter(look)) {
  975. throw expected("',' or ')'");
  976. }
  977. }
  978. ParseNode[] result = new ParseNode[temp.size()];
  979. temp.toArray(result);
  980. return result;
  981. }
  982. /** Parse and Translate a Math Factor */
  983. private ParseNode powerFactor() {
  984. ParseNode result = percentFactor();
  985. while(true) {
  986. SkipWhite();
  987. if(look != '^') {
  988. return result;
  989. }
  990. Match('^');
  991. ParseNode other = percentFactor();
  992. result = new ParseNode(PowerPtg.instance, result, other);
  993. }
  994. }
  995. private ParseNode percentFactor() {
  996. ParseNode result = parseSimpleFactor();
  997. while(true) {
  998. SkipWhite();
  999. if(look != '%') {
  1000. return result;
  1001. }
  1002. Match('%');
  1003. result = new ParseNode(PercentPtg.instance, result);
  1004. }
  1005. }
  1006. /**
  1007. * factors (without ^ or % )
  1008. */
  1009. private ParseNode parseSimpleFactor() {
  1010. SkipWhite();
  1011. switch(look) {
  1012. case '#':
  1013. return new ParseNode(ErrPtg.valueOf(parseErrorLiteral()));
  1014. case '-':
  1015. Match('-');
  1016. return parseUnary(false);
  1017. case '+':
  1018. Match('+');
  1019. return parseUnary(true);
  1020. case '(':
  1021. Match('(');
  1022. ParseNode inside = unionExpression();
  1023. Match(')');
  1024. return new ParseNode(ParenthesisPtg.instance, inside);
  1025. case '"':
  1026. return new ParseNode(new StringPtg(parseStringLiteral()));
  1027. case '{':
  1028. Match('{');
  1029. ParseNode arrayNode = parseArray();
  1030. Match('}');
  1031. return arrayNode;
  1032. }
  1033. if (IsAlpha(look) || Character.isDigit(look) || look == '\'' || look == '['){
  1034. return parseRangeExpression();
  1035. }
  1036. if (look == '.') {
  1037. return new ParseNode(parseNumber());
  1038. }
  1039. throw expected("cell ref or constant literal");
  1040. }
  1041. private ParseNode parseUnary(boolean isPlus) {
  1042. boolean numberFollows = IsDigit(look) || look=='.';
  1043. ParseNode factor = powerFactor();
  1044. if (numberFollows) {
  1045. // + or - directly next to a number is parsed with the number
  1046. Ptg token = factor.getToken();
  1047. if (token instanceof NumberPtg) {
  1048. if (isPlus) {
  1049. return factor;
  1050. }
  1051. token = new NumberPtg(-((NumberPtg)token).getValue());
  1052. return new ParseNode(token);
  1053. }
  1054. if (token instanceof IntPtg) {
  1055. if (isPlus) {
  1056. return factor;
  1057. }
  1058. int intVal = ((IntPtg)token).getValue();
  1059. // note - cannot use IntPtg for negatives
  1060. token = new NumberPtg(-intVal);
  1061. return new ParseNode(token);
  1062. }
  1063. }
  1064. return new ParseNode(isPlus ? UnaryPlusPtg.instance : UnaryMinusPtg.instance, factor);
  1065. }
  1066. private ParseNode parseArray() {
  1067. List<Object[]> rowsData = new ArrayList<Object[]>();
  1068. while(true) {
  1069. Object[] singleRowData = parseArrayRow();
  1070. rowsData.add(singleRowData);
  1071. if (look == '}') {
  1072. break;
  1073. }
  1074. if (look != ';') {
  1075. throw expected("'}' or ';'");
  1076. }
  1077. Match(';');
  1078. }
  1079. int nRows = rowsData.size();
  1080. Object[][] values2d = new Object[nRows][];
  1081. rowsData.toArray(values2d);
  1082. int nColumns = values2d[0].length;
  1083. checkRowLengths(values2d, nColumns);
  1084. return new ParseNode(new ArrayPtg(values2d));
  1085. }
  1086. private void checkRowLengths(Object[][] values2d, int nColumns) {
  1087. for (int i = 0; i < values2d.length; i++) {
  1088. int rowLen = values2d[i].length;
  1089. if (rowLen != nColumns) {
  1090. throw new FormulaParseException("Array row " + i + " has length " + rowLen
  1091. + " but row 0 has length " + nColumns);
  1092. }
  1093. }
  1094. }
  1095. private Object[] parseArrayRow() {
  1096. List<Object> temp = new ArrayList<Object>();
  1097. while (true) {
  1098. temp.add(parseArrayItem());
  1099. SkipWhite();
  1100. switch(look) {
  1101. case '}':
  1102. case ';':
  1103. break;
  1104. case ',':
  1105. Match(',');
  1106. continue;
  1107. default:
  1108. throw expected("'}' or ','");
  1109. }
  1110. break;
  1111. }
  1112. Object[] result = new Object[temp.size()];
  1113. temp.toArray(result);
  1114. return result;
  1115. }
  1116. private Object parseArrayItem() {
  1117. SkipWhite();
  1118. switch(look) {
  1119. case '"': return parseStringLiteral();
  1120. case '#': return ErrorConstant.valueOf(parseErrorLiteral());
  1121. case 'F': case 'f':
  1122. case 'T': case 't':
  1123. return parseBooleanLiteral();
  1124. case '-':
  1125. Match('-');
  1126. SkipWhite();
  1127. return convertArrayNumber(parseNumber(), false);
  1128. }
  1129. // else assume number
  1130. return convertArrayNumber(parseNumber(), true);
  1131. }
  1132. private Boolean parseBooleanLiteral() {
  1133. String iden = parseUnquotedIdentifier();
  1134. if ("TRUE".equalsIgnoreCase(iden)) {
  1135. return Boolean.TRUE;
  1136. }
  1137. if ("FALSE".equalsIgnoreCase(iden)) {
  1138. return Boolean.FALSE;
  1139. }
  1140. throw expected("'TRUE' or 'FALSE'");
  1141. }
  1142. private static Double convertArrayNumber(Ptg ptg, boolean isPositive) {
  1143. double value;
  1144. if (ptg instanceof IntPtg) {
  1145. value = ((IntPtg)ptg).getValue();
  1146. } else if (ptg instanceof NumberPtg) {
  1147. value = ((NumberPtg)ptg).getValue();
  1148. } else {
  1149. throw new RuntimeException("Unexpected ptg (" + ptg.getClass().getName() + ")");
  1150. }
  1151. if (!isPositive) {
  1152. value = -value;
  1153. }
  1154. return new Double(value);
  1155. }
  1156. private Ptg parseNumber() {
  1157. String number2 = null;
  1158. String exponent = null;
  1159. String number1 = GetNum();
  1160. if (look == '.') {
  1161. GetChar();
  1162. number2 = GetNum();
  1163. }
  1164. if (look == 'E') {
  1165. GetChar();
  1166. String sign = "";
  1167. if (look == '+') {
  1168. GetChar();
  1169. } else if (look == '-') {
  1170. GetChar();
  1171. sign = "-";
  1172. }
  1173. String number = GetNum();
  1174. if (number == null) {
  1175. throw expected("Integer");
  1176. }
  1177. exponent = sign + number;
  1178. }
  1179. if (number1 == null && number2 == null) {
  1180. throw expected("Integer");
  1181. }
  1182. return getNumberPtgFromString(number1, number2, exponent);
  1183. }
  1184. private int parseErrorLiteral() {
  1185. Match('#');
  1186. String part1 = parseUnquotedIdentifier().toUpperCase();
  1187. if (part1 == null) {
  1188. throw expected("remainder of error constant literal");
  1189. }
  1190. switch(part1.charAt(0)) {
  1191. case 'V':
  1192. if(part1.equals("VALUE")) {
  1193. Match('!');
  1194. return ErrorConstants.ERROR_VALUE;
  1195. }
  1196. throw expected("#VALUE!");
  1197. case 'R':
  1198. if(part1.equals("REF")) {
  1199. Match('!');
  1200. return ErrorConstants.ERROR_REF;
  1201. }
  1202. throw expected("#REF!");
  1203. case 'D':
  1204. if(part1.equals("DIV")) {
  1205. Match('/');
  1206. Match('0');
  1207. Match('!');
  1208. return ErrorConstants.ERROR_DIV_0;
  1209. }
  1210. throw expected("#DIV/0!");
  1211. case 'N':
  1212. if(part1.equals("NAME")) {
  1213. Match('?'); // only one that ends in '?'
  1214. return ErrorConstants.ERROR_NAME;
  1215. }
  1216. if(part1.equals("NUM")) {
  1217. Match('!');
  1218. return ErrorConstants.ERROR_NUM;
  1219. }
  1220. if(part1.equals("NULL")) {
  1221. Match('!');
  1222. return ErrorConstants.ERROR_NULL;
  1223. }
  1224. if(part1.equals("N")) {
  1225. Match('/');
  1226. if(look != 'A' && look != 'a') {
  1227. throw expected("#N/A");
  1228. }
  1229. Match(look);
  1230. // Note - no '!' or '?' suffix
  1231. return ErrorConstants.ERROR_NA;
  1232. }
  1233. throw expected("#NAME?, #NUM!, #NULL! or #N/A");
  1234. }
  1235. throw expected("#VALUE!, #REF!, #DIV/0!, #NAME?, #NUM!, #NULL! or #N/A");
  1236. }
  1237. private String parseUnquotedIdentifier() {
  1238. if (look == '\'') {
  1239. throw expected("unquoted identifier");
  1240. }
  1241. StringBuilder sb = new StringBuilder();
  1242. while (Character.isLetterOrDigit(look) || look == '.') {
  1243. sb.append(look);
  1244. GetChar();
  1245. }
  1246. if (sb.length() < 1) {
  1247. return null;
  1248. }
  1249. return sb.toString();
  1250. }
  1251. /**
  1252. * Get a PTG for an integer from its string representation.
  1253. * return Int or Number Ptg based on size of input
  1254. */
  1255. private static Ptg getNumberPtgFromString(String number1, String number2, String exponent) {
  1256. StringBuffer number = new StringBuffer();
  1257. if (number2 == null) {
  1258. number.append(number1);
  1259. if (exponent != null) {
  1260. number.append('E');
  1261. number.append(exponent);
  1262. }
  1263. String numberStr = number.toString();
  1264. int intVal;
  1265. try {
  1266. intVal = Integer.parseInt(numberStr);
  1267. } catch (NumberFormatException e) {
  1268. return new NumberPtg(numberStr);
  1269. }
  1270. if (IntPtg.isInRange(intVal)) {
  1271. return new IntPtg(intVal);
  1272. }
  1273. return new NumberPtg(numberStr);
  1274. }
  1275. if (number1 != null) {
  1276. number.append(number1);
  1277. }
  1278. number.append('.');
  1279. number.append(number2);
  1280. if (exponent != null) {
  1281. number.append('E');
  1282. number.append(exponent);
  1283. }
  1284. return new NumberPtg(number.toString());
  1285. }
  1286. private String parseStringLiteral() {
  1287. Match('"');
  1288. StringBuffer token = new StringBuffer();
  1289. while (true) {
  1290. if (look == '"') {
  1291. GetChar();
  1292. if (look != '"') {
  1293. break;
  1294. }
  1295. }
  1296. token.append(look);
  1297. GetChar();
  1298. }
  1299. return token.toString();
  1300. }
  1301. /** Parse and Translate a Math Term */
  1302. private ParseNode Term() {
  1303. ParseNode result = powerFactor();
  1304. while(true) {
  1305. SkipWhite();
  1306. Ptg operator;
  1307. switch(look) {
  1308. case '*':
  1309. Match('*');
  1310. operator = MultiplyPtg.instance;
  1311. break;
  1312. case '/':
  1313. Match('/');
  1314. operator = DividePtg.instance;
  1315. break;
  1316. default:
  1317. return result; // finished with Term
  1318. }
  1319. ParseNode other = powerFactor();
  1320. result = new ParseNode(operator, result, other);
  1321. }
  1322. }
  1323. private ParseNode unionExpression() {
  1324. ParseNode result = intersectionExpression();
  1325. boolean hasUnions = false;
  1326. while (true) {
  1327. SkipWhite();
  1328. switch(look) {
  1329. case ',':
  1330. GetChar();
  1331. hasUnions = true;
  1332. ParseNode other = intersectionExpression();
  1333. result = new ParseNode(UnionPtg.instance, result, other);
  1334. continue;
  1335. }
  1336. if (hasUnions) {
  1337. return augmentWithMemPtg(result);
  1338. }
  1339. return result;
  1340. }
  1341. }
  1342. private ParseNode intersectionExpression() {
  1343. ParseNode result = comparisonExpression();
  1344. boolean hasIntersections = false;
  1345. while (true) {
  1346. SkipWhite();
  1347. if (_inIntersection) {
  1348. // Don't getChar() as the space has already been eaten and recorded by SkipWhite().
  1349. hasIntersections = true;
  1350. ParseNode other = comparisonExpression();
  1351. result = new ParseNode(IntersectionPtg.instance, result, other);
  1352. continue;
  1353. }
  1354. if (hasIntersections) {
  1355. return augmentWithMemPtg(result);
  1356. }
  1357. return result;
  1358. }
  1359. }
  1360. private ParseNode comparisonExpression() {
  1361. ParseNode result = concatExpression();
  1362. while (true) {
  1363. SkipWhite();
  1364. switch(look) {
  1365. case '=':
  1366. case '>':
  1367. case '<':
  1368. Ptg comparisonToken = getComparisonToken();
  1369. ParseNode other = concatExpression();
  1370. result = new ParseNode(comparisonToken, result, other);
  1371. continue;
  1372. }
  1373. return result; // finished with predicate expression
  1374. }
  1375. }
  1376. private Ptg getComparisonToken() {
  1377. if(look == '=') {
  1378. Match(look);
  1379. return EqualPtg.instance;
  1380. }
  1381. boolean isGreater = look == '>';
  1382. Match(look);
  1383. if(isGreater) {
  1384. if(look == '=') {
  1385. Match('=');
  1386. return GreaterEqualPtg.instance;
  1387. }
  1388. return GreaterThanPtg.instance;
  1389. }
  1390. switch(look) {
  1391. case '=':
  1392. Match('=');
  1393. return LessEqualPtg.instance;
  1394. case '>':
  1395. Match('>');
  1396. return NotEqualPtg.instance;
  1397. }
  1398. return LessThanPtg.instance;
  1399. }
  1400. private ParseNode concatExpression() {
  1401. ParseNode result = additiveExpression();
  1402. while (true) {
  1403. SkipWhite();
  1404. if(look != '&') {
  1405. break; // finished with concat expression
  1406. }
  1407. Match('&');
  1408. ParseNode other = additiveExpression();
  1409. result = new ParseNode(ConcatPtg.instance, result, other);
  1410. }
  1411. return result;
  1412. }
  1413. /** Parse and Translate an Expression */
  1414. private ParseNode additiveExpression() {
  1415. ParseNode result = Term();
  1416. while (true) {
  1417. SkipWhite();
  1418. Ptg operator;
  1419. switch(look) {
  1420. case '+':
  1421. Match('+');
  1422. operator = AddPtg.instance;
  1423. break;
  1424. case '-':
  1425. Match('-');
  1426. operator = SubtractPtg.instance;
  1427. break;
  1428. default:
  1429. return result; // finished with additive expression
  1430. }
  1431. ParseNode other = Term();
  1432. result = new ParseNode(operator, result, other);
  1433. }
  1434. }
  1435. //{--------------------------------------------------------------}
  1436. //{ Parse and Translate an Assignment Statement }
  1437. /**
  1438. procedure Assignment;
  1439. var Name: string[8];
  1440. begin
  1441. Name := GetName;
  1442. Match('=');
  1443. Expression;
  1444. end;
  1445. **/
  1446. /**
  1447. * API call to execute the parsing of the formula
  1448. *
  1449. */
  1450. private void parse() {
  1451. _pointer=0;
  1452. GetChar();
  1453. _rootNode = unionExpression();
  1454. if(_pointer <= _formulaLength) {
  1455. String msg = "Unused input [" + _formulaString.substring(_pointer-1)
  1456. + "] after attempting to parse the formula [" + _formulaString + "]";
  1457. throw new FormulaParseException(msg);
  1458. }
  1459. }
  1460. private Ptg[] getRPNPtg(int formulaType) {
  1461. OperandClassTransformer oct = new OperandClassTransformer(formulaType);
  1462. // RVA is for 'operand class': 'reference', 'value', 'array'
  1463. oct.transformFormula(_rootNode);
  1464. return ParseNode.toTokenArray(_rootNode);
  1465. }
  1466. }