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.

Expressionator.java 57KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125
  1. /*
  2. Copyright (c) 2016 James Ahlborn
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl.expr;
  14. import java.math.BigDecimal;
  15. import java.text.DateFormat;
  16. import java.text.SimpleDateFormat;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.Date;
  22. import java.util.Deque;
  23. import java.util.HashMap;
  24. import java.util.HashSet;
  25. import java.util.Iterator;
  26. import java.util.LinkedList;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Set;
  30. import java.util.regex.Pattern;
  31. import java.util.regex.PatternSyntaxException;
  32. import com.healthmarketscience.jackcess.expr.EvalContext;
  33. import com.healthmarketscience.jackcess.expr.EvalException;
  34. import com.healthmarketscience.jackcess.expr.Expression;
  35. import com.healthmarketscience.jackcess.expr.Function;
  36. import com.healthmarketscience.jackcess.expr.Identifier;
  37. import com.healthmarketscience.jackcess.expr.ParseException;
  38. import com.healthmarketscience.jackcess.expr.TemporalConfig;
  39. import com.healthmarketscience.jackcess.expr.Value;
  40. import com.healthmarketscience.jackcess.impl.expr.ExpressionTokenizer.Token;
  41. import com.healthmarketscience.jackcess.impl.expr.ExpressionTokenizer.TokenType;
  42. /**
  43. *
  44. * @author James Ahlborn
  45. */
  46. public class Expressionator
  47. {
  48. // Useful links:
  49. // - syntax: https://support.office.com/en-us/article/Guide-to-expression-syntax-ebc770bc-8486-4adc-a9ec-7427cce39a90
  50. // - examples: https://support.office.com/en-us/article/Examples-of-expressions-d3901e11-c04e-4649-b40b-8b6ec5aed41f
  51. // - validation rule usage: https://support.office.com/en-us/article/Restrict-data-input-by-using-a-validation-rule-6c0b2ce1-76fa-4be0-8ae9-038b52652320
  52. public enum Type {
  53. DEFAULT_VALUE, EXPRESSION, FIELD_VALIDATOR, RECORD_VALIDATOR;
  54. }
  55. public interface ParseContext {
  56. public TemporalConfig getTemporalConfig();
  57. public SimpleDateFormat createDateFormat(String formatStr);
  58. public Function getExpressionFunction(String name);
  59. }
  60. private enum WordType {
  61. OP, COMP, LOG_OP, CONST, SPEC_OP_PREFIX, DELIM;
  62. }
  63. private static final String FUNC_START_DELIM = "(";
  64. private static final String FUNC_END_DELIM = ")";
  65. private static final String OPEN_PAREN = "(";
  66. private static final String CLOSE_PAREN = ")";
  67. private static final String FUNC_PARAM_SEP = ",";
  68. private static final Map<String,WordType> WORD_TYPES =
  69. new HashMap<String,WordType>();
  70. static {
  71. setWordType(WordType.OP, "+", "-", "*", "/", "\\", "^", "&", "mod");
  72. setWordType(WordType.COMP, "<", "<=", ">", ">=", "=", "<>");
  73. setWordType(WordType.LOG_OP, "and", "or", "eqv", "xor", "imp");
  74. setWordType(WordType.CONST, "true", "false", "null");
  75. setWordType(WordType.SPEC_OP_PREFIX, "is", "like", "between", "in", "not");
  76. // "X is null", "X is not null", "X like P", "X between A and B",
  77. // "X not between A and B", "X in (A, B, C...)", "X not in (A, B, C...)",
  78. // "not X"
  79. setWordType(WordType.DELIM, ".", "!", ",", "(", ")");
  80. }
  81. private interface OpType {}
  82. private enum UnaryOp implements OpType {
  83. NEG("-", false) {
  84. @Override public Value eval(EvalContext ctx, Value param1) {
  85. return BuiltinOperators.negate(ctx, param1);
  86. }
  87. @Override public UnaryOp getUnaryNumOp() {
  88. return UnaryOp.NEG_NUM;
  89. }
  90. },
  91. POS("+", false) {
  92. @Override public Value eval(EvalContext ctx, Value param1) {
  93. // basically a no-op
  94. return param1;
  95. }
  96. @Override public UnaryOp getUnaryNumOp() {
  97. return UnaryOp.POS_NUM;
  98. }
  99. },
  100. NOT("Not", true) {
  101. @Override public Value eval(EvalContext ctx, Value param1) {
  102. return BuiltinOperators.not(param1);
  103. }
  104. },
  105. // when a '-' immediately precedes a number, it needs "highest" precedence
  106. NEG_NUM("-", false) {
  107. @Override public Value eval(EvalContext ctx, Value param1) {
  108. return BuiltinOperators.negate(ctx, param1);
  109. }
  110. },
  111. // when a '+' immediately precedes a number, it needs "highest" precedence
  112. POS_NUM("+", false) {
  113. @Override public Value eval(EvalContext ctx, Value param1) {
  114. // basically a no-op
  115. return param1;
  116. }
  117. };
  118. private final String _str;
  119. private final boolean _needSpace;
  120. private UnaryOp(String str, boolean needSpace) {
  121. _str = str;
  122. _needSpace = needSpace;
  123. }
  124. public boolean needsSpace() {
  125. return _needSpace;
  126. }
  127. @Override
  128. public String toString() {
  129. return _str;
  130. }
  131. public UnaryOp getUnaryNumOp() {
  132. return null;
  133. }
  134. public abstract Value eval(EvalContext ctx, Value param1);
  135. }
  136. private enum BinaryOp implements OpType {
  137. PLUS("+") {
  138. @Override public Value eval(EvalContext ctx, Value param1, Value param2) {
  139. return BuiltinOperators.add(ctx, param1, param2);
  140. }
  141. },
  142. MINUS("-") {
  143. @Override public Value eval(EvalContext ctx, Value param1, Value param2) {
  144. return BuiltinOperators.subtract(ctx, param1, param2);
  145. }
  146. },
  147. MULT("*") {
  148. @Override public Value eval(EvalContext ctx, Value param1, Value param2) {
  149. return BuiltinOperators.multiply(param1, param2);
  150. }
  151. },
  152. DIV("/") {
  153. @Override public Value eval(EvalContext ctx, Value param1, Value param2) {
  154. return BuiltinOperators.divide(param1, param2);
  155. }
  156. },
  157. INT_DIV("\\") {
  158. @Override public Value eval(EvalContext ctx, Value param1, Value param2) {
  159. return BuiltinOperators.intDivide(param1, param2);
  160. }
  161. },
  162. EXP("^") {
  163. @Override public Value eval(EvalContext ctx, Value param1, Value param2) {
  164. return BuiltinOperators.exp(param1, param2);
  165. }
  166. },
  167. CONCAT("&") {
  168. @Override public Value eval(EvalContext ctx, Value param1, Value param2) {
  169. return BuiltinOperators.concat(param1, param2);
  170. }
  171. },
  172. MOD("Mod") {
  173. @Override public Value eval(EvalContext ctx, Value param1, Value param2) {
  174. return BuiltinOperators.mod(param1, param2);
  175. }
  176. };
  177. private final String _str;
  178. private BinaryOp(String str) {
  179. _str = str;
  180. }
  181. @Override
  182. public String toString() {
  183. return _str;
  184. }
  185. public abstract Value eval(EvalContext ctx, Value param1, Value param2);
  186. }
  187. private enum CompOp implements OpType {
  188. LT("<") {
  189. @Override public Value eval(Value param1, Value param2) {
  190. return BuiltinOperators.lessThan(param1, param2);
  191. }
  192. },
  193. LTE("<=") {
  194. @Override public Value eval(Value param1, Value param2) {
  195. return BuiltinOperators.lessThanEq(param1, param2);
  196. }
  197. },
  198. GT(">") {
  199. @Override public Value eval(Value param1, Value param2) {
  200. return BuiltinOperators.greaterThan(param1, param2);
  201. }
  202. },
  203. GTE(">=") {
  204. @Override public Value eval(Value param1, Value param2) {
  205. return BuiltinOperators.greaterThanEq(param1, param2);
  206. }
  207. },
  208. EQ("=") {
  209. @Override public Value eval(Value param1, Value param2) {
  210. return BuiltinOperators.equals(param1, param2);
  211. }
  212. },
  213. NE("<>") {
  214. @Override public Value eval(Value param1, Value param2) {
  215. return BuiltinOperators.notEquals(param1, param2);
  216. }
  217. };
  218. private final String _str;
  219. private CompOp(String str) {
  220. _str = str;
  221. }
  222. @Override
  223. public String toString() {
  224. return _str;
  225. }
  226. public abstract Value eval(Value param1, Value param2);
  227. }
  228. private enum LogOp implements OpType {
  229. AND("And") {
  230. @Override public Value eval(Value param1, Value param2) {
  231. return BuiltinOperators.and(param1, param2);
  232. }
  233. },
  234. OR("Or") {
  235. @Override public Value eval(Value param1, Value param2) {
  236. return BuiltinOperators.or(param1, param2);
  237. }
  238. },
  239. EQV("Eqv") {
  240. @Override public Value eval(Value param1, Value param2) {
  241. return BuiltinOperators.eqv(param1, param2);
  242. }
  243. },
  244. XOR("Xor") {
  245. @Override public Value eval(Value param1, Value param2) {
  246. return BuiltinOperators.xor(param1, param2);
  247. }
  248. },
  249. IMP("Imp") {
  250. @Override public Value eval(Value param1, Value param2) {
  251. return BuiltinOperators.imp(param1, param2);
  252. }
  253. };
  254. private final String _str;
  255. private LogOp(String str) {
  256. _str = str;
  257. }
  258. @Override
  259. public String toString() {
  260. return _str;
  261. }
  262. public abstract Value eval(Value param1, Value param2);
  263. }
  264. private enum SpecOp implements OpType {
  265. // note, "NOT" is not actually used as a special operation, always
  266. // replaced with UnaryOp.NOT
  267. NOT("Not") {
  268. @Override public Value eval(Value param1, Object param2, Object param3) {
  269. throw new UnsupportedOperationException();
  270. }
  271. },
  272. IS_NULL("Is Null") {
  273. @Override public Value eval(Value param1, Object param2, Object param3) {
  274. return BuiltinOperators.isNull(param1);
  275. }
  276. },
  277. IS_NOT_NULL("Is Not Null") {
  278. @Override public Value eval(Value param1, Object param2, Object param3) {
  279. return BuiltinOperators.isNotNull(param1);
  280. }
  281. },
  282. LIKE("Like") {
  283. @Override public Value eval(Value param1, Object param2, Object param3) {
  284. return BuiltinOperators.like(param1, (Pattern)param2);
  285. }
  286. },
  287. BETWEEN("Between") {
  288. @Override public Value eval(Value param1, Object param2, Object param3) {
  289. return BuiltinOperators.between(param1, (Value)param2, (Value)param3);
  290. }
  291. },
  292. NOT_BETWEEN("Not Between") {
  293. @Override public Value eval(Value param1, Object param2, Object param3) {
  294. return BuiltinOperators.notBetween(param1, (Value)param2, (Value)param3);
  295. }
  296. },
  297. IN("In") {
  298. @Override public Value eval(Value param1, Object param2, Object param3) {
  299. return BuiltinOperators.in(param1, (Value[])param2);
  300. }
  301. },
  302. NOT_IN("Not In") {
  303. @Override public Value eval(Value param1, Object param2, Object param3) {
  304. return BuiltinOperators.notIn(param1, (Value[])param2);
  305. }
  306. };
  307. private final String _str;
  308. private SpecOp(String str) {
  309. _str = str;
  310. }
  311. @Override
  312. public String toString() {
  313. return _str;
  314. }
  315. public abstract Value eval(Value param1, Object param2, Object param3);
  316. }
  317. private static final Map<OpType, Integer> PRECENDENCE =
  318. buildPrecedenceMap(
  319. new OpType[]{UnaryOp.NEG_NUM, UnaryOp.POS_NUM},
  320. new OpType[]{BinaryOp.EXP},
  321. new OpType[]{UnaryOp.NEG, UnaryOp.POS},
  322. new OpType[]{BinaryOp.MULT, BinaryOp.DIV},
  323. new OpType[]{BinaryOp.INT_DIV},
  324. new OpType[]{BinaryOp.MOD},
  325. new OpType[]{BinaryOp.PLUS, BinaryOp.MINUS},
  326. new OpType[]{BinaryOp.CONCAT},
  327. new OpType[]{CompOp.LT, CompOp.GT, CompOp.NE, CompOp.LTE, CompOp.GTE,
  328. CompOp.EQ, SpecOp.LIKE, SpecOp.IS_NULL, SpecOp.IS_NOT_NULL},
  329. new OpType[]{UnaryOp.NOT},
  330. new OpType[]{LogOp.AND},
  331. new OpType[]{LogOp.OR},
  332. new OpType[]{LogOp.XOR},
  333. new OpType[]{LogOp.EQV},
  334. new OpType[]{LogOp.IMP},
  335. new OpType[]{SpecOp.IN, SpecOp.NOT_IN, SpecOp.BETWEEN,
  336. SpecOp.NOT_BETWEEN});
  337. private static final Set<Character> REGEX_SPEC_CHARS = new HashSet<Character>(
  338. Arrays.asList('\\','.','%','=','+', '$','^','|','(',')','{','}','&'));
  339. // this is a regular expression which will never match any string
  340. private static final Pattern UNMATCHABLE_REGEX = Pattern.compile("(?!)");
  341. private static final Expr THIS_COL_VALUE = new EThisValue();
  342. private static final Expr NULL_VALUE = new EConstValue(
  343. BuiltinOperators.NULL_VAL, "Null");
  344. private static final Expr TRUE_VALUE = new EConstValue(
  345. BuiltinOperators.TRUE_VAL, "True");
  346. private static final Expr FALSE_VALUE = new EConstValue(
  347. BuiltinOperators.FALSE_VAL, "False");
  348. private Expressionator() {}
  349. public static Expression parse(Type exprType, String exprStr,
  350. Value.Type resultType,
  351. ParseContext context) {
  352. List<Token> tokens = trimSpaces(
  353. ExpressionTokenizer.tokenize(exprType, exprStr, context));
  354. if(tokens == null) {
  355. throw new ParseException("null/empty expression");
  356. }
  357. TokBuf buf = new TokBuf(exprType, tokens, context);
  358. if(isLiteralDefaultValue(buf, resultType, exprStr)) {
  359. // this is handled as a literal string value, not an expression. no
  360. // need to memo-ize cause it's a simple literal value
  361. return new ExprWrapper(
  362. new ELiteralValue(Value.Type.STRING, exprStr, null), resultType);
  363. }
  364. // normal expression handling
  365. Expr expr = parseExpression(buf, false);
  366. if((exprType == Type.FIELD_VALIDATOR) && !expr.isConditionalExpr()) {
  367. // a non-conditional expression for a FIELD_VALIDATOR treats the result
  368. // as an equality comparison with the field in question. so, transform
  369. // the expression accordingly
  370. expr = new EImplicitCompOp(expr);
  371. }
  372. switch(exprType) {
  373. case DEFAULT_VALUE:
  374. case EXPRESSION:
  375. return (expr.isConstant() ?
  376. // for now, just cache at top-level for speed (could in theory
  377. // cache intermediate values?)
  378. new MemoizedExprWrapper(expr, resultType) :
  379. new ExprWrapper(expr, resultType));
  380. case FIELD_VALIDATOR:
  381. case RECORD_VALIDATOR:
  382. return (expr.isConstant() ?
  383. // for now, just cache at top-level for speed (could in theory
  384. // cache intermediate values?)
  385. new MemoizedCondExprWrapper(expr) :
  386. new CondExprWrapper(expr));
  387. default:
  388. throw new ParseException("unexpected expression type " + exprType);
  389. }
  390. }
  391. private static List<Token> trimSpaces(List<Token> tokens) {
  392. if(tokens == null) {
  393. return null;
  394. }
  395. // for the most part, spaces are superfluous except for one situation(?).
  396. // when they appear between a string literal and '(' they help distinguish
  397. // a function call from another expression form
  398. for(int i = 1; i < (tokens.size() - 1); ++i) {
  399. Token t = tokens.get(i);
  400. if(t.getType() == TokenType.SPACE) {
  401. if((tokens.get(i - 1).getType() == TokenType.STRING) &&
  402. isDelim(tokens.get(i + 1), FUNC_START_DELIM)) {
  403. // we want to keep this space
  404. } else {
  405. tokens.remove(i);
  406. --i;
  407. }
  408. }
  409. }
  410. return tokens;
  411. }
  412. private static Expr parseExpression(TokBuf buf, boolean singleExpr)
  413. {
  414. while(buf.hasNext()) {
  415. Token t = buf.next();
  416. switch(t.getType()) {
  417. case OBJ_NAME:
  418. parseObjectRefExpression(t, buf);
  419. break;
  420. case LITERAL:
  421. buf.setPendingExpr(new ELiteralValue(t.getValueType(), t.getValue(),
  422. t.getDateFormat()));
  423. break;
  424. case OP:
  425. WordType wordType = getWordType(t);
  426. if(wordType == null) {
  427. // shouldn't happen
  428. throw new ParseException("Invalid operator " + t);
  429. }
  430. // this can only be an OP or a COMP (those are the only words that the
  431. // tokenizer would define as TokenType.OP)
  432. switch(wordType) {
  433. case OP:
  434. parseOperatorExpression(t, buf);
  435. break;
  436. case COMP:
  437. parseCompOpExpression(t, buf);
  438. break;
  439. default:
  440. throw new ParseException("Unexpected OP word type " + wordType);
  441. }
  442. break;
  443. case DELIM:
  444. parseDelimExpression(t, buf);
  445. break;
  446. case STRING:
  447. // see if it's a special word?
  448. wordType = getWordType(t);
  449. if(wordType == null) {
  450. // is it a function call?
  451. if(!maybeParseFuncCallExpression(t, buf)) {
  452. // is it an object name?
  453. Token next = buf.peekNext();
  454. if((next != null) && isObjNameSep(next)) {
  455. parseObjectRefExpression(t, buf);
  456. } else {
  457. // FIXME maybe bare obj name, maybe string literal?
  458. throw new UnsupportedOperationException("FIXME");
  459. }
  460. }
  461. } else {
  462. // this could be anything but COMP or DELIM (all COMPs would be
  463. // returned as TokenType.OP and all DELIMs would be TokenType.DELIM)
  464. switch(wordType) {
  465. case OP:
  466. parseOperatorExpression(t, buf);
  467. break;
  468. case LOG_OP:
  469. parseLogicalOpExpression(t, buf);
  470. break;
  471. case CONST:
  472. parseConstExpression(t, buf);
  473. break;
  474. case SPEC_OP_PREFIX:
  475. parseSpecOpExpression(t, buf);
  476. break;
  477. default:
  478. throw new ParseException("Unexpected STRING word type "
  479. + wordType);
  480. }
  481. }
  482. break;
  483. case SPACE:
  484. // top-level space is irrelevant (and we strip them anyway)
  485. break;
  486. default:
  487. throw new ParseException("unknown token type " + t);
  488. }
  489. if(singleExpr && buf.hasPendingExpr()) {
  490. break;
  491. }
  492. }
  493. Expr expr = buf.takePendingExpr();
  494. if(expr == null) {
  495. throw new ParseException("No expression found? " + buf);
  496. }
  497. return expr;
  498. }
  499. private static void parseObjectRefExpression(Token firstTok, TokBuf buf) {
  500. // object references may be joined by '.' or '!'. access syntac docs claim
  501. // object identifiers can be formatted like:
  502. // "[Collection name]![Object name].[Property name]"
  503. // However, in practice, they only ever seem to be (at most) two levels
  504. // and only use '.'. Apparently '!' is actually a special late-bind
  505. // operator (not sure it makes a difference for this code?), see:
  506. // http://bytecomb.com/the-bang-exclamation-operator-in-vba/
  507. Deque<String> objNames = new LinkedList<String>();
  508. objNames.add(firstTok.getValueStr());
  509. Token t = null;
  510. boolean atSep = false;
  511. while((t = buf.peekNext()) != null) {
  512. if(!atSep) {
  513. if(isObjNameSep(t)) {
  514. buf.next();
  515. atSep = true;
  516. continue;
  517. }
  518. } else {
  519. if((t.getType() == TokenType.OBJ_NAME) ||
  520. (t.getType() == TokenType.STRING)) {
  521. buf.next();
  522. // always insert at beginning of list so names are in reverse order
  523. objNames.addFirst(t.getValueStr());
  524. atSep = false;
  525. continue;
  526. }
  527. }
  528. break;
  529. }
  530. int numNames = objNames.size();
  531. if(atSep || (numNames > 3)) {
  532. throw new ParseException("Invalid object reference " + buf);
  533. }
  534. // names are in reverse order
  535. String propName = null;
  536. if(numNames == 3) {
  537. propName = objNames.poll();
  538. }
  539. String objName = objNames.poll();
  540. String collectionName = objNames.poll();
  541. buf.setPendingExpr(
  542. new EObjValue(new Identifier(collectionName, objName, propName)));
  543. }
  544. private static void parseDelimExpression(Token firstTok, TokBuf buf) {
  545. // the only "top-level" delim we expect to find is open paren, and
  546. // there shouldn't be any pending expression
  547. if(!isDelim(firstTok, OPEN_PAREN) || buf.hasPendingExpr()) {
  548. throw new ParseException("Unexpected delimiter " +
  549. firstTok.getValue() + " " + buf);
  550. }
  551. Expr subExpr = findParenExprs(buf, false).get(0);
  552. buf.setPendingExpr(new EParen(subExpr));
  553. }
  554. private static boolean maybeParseFuncCallExpression(
  555. Token firstTok, TokBuf buf) {
  556. int startPos = buf.curPos();
  557. boolean foundFunc = false;
  558. try {
  559. Token t = buf.peekNext();
  560. if(!isDelim(t, FUNC_START_DELIM)) {
  561. // not a function call
  562. return false;
  563. }
  564. buf.next();
  565. List<Expr> params = findParenExprs(buf, true);
  566. String funcName = firstTok.getValueStr();
  567. Function func = buf.getFunction(funcName);
  568. if(func == null) {
  569. throw new ParseException("Could not find function '" +
  570. funcName + "' " + buf);
  571. }
  572. buf.setPendingExpr(new EFunc(func, params));
  573. foundFunc = true;
  574. return true;
  575. } finally {
  576. if(!foundFunc) {
  577. buf.reset(startPos);
  578. }
  579. }
  580. }
  581. private static List<Expr> findParenExprs(
  582. TokBuf buf, boolean allowMulti) {
  583. if(allowMulti) {
  584. // simple case, no nested expr
  585. Token t = buf.peekNext();
  586. if(isDelim(t, CLOSE_PAREN)) {
  587. buf.next();
  588. return Collections.emptyList();
  589. }
  590. }
  591. // find closing ")", handle nested parens
  592. List<Expr> exprs = new ArrayList<Expr>(3);
  593. int level = 1;
  594. int startPos = buf.curPos();
  595. while(buf.hasNext()) {
  596. Token t = buf.next();
  597. if(isDelim(t, OPEN_PAREN)) {
  598. ++level;
  599. } else if(isDelim(t, CLOSE_PAREN)) {
  600. --level;
  601. if(level == 0) {
  602. TokBuf subBuf = buf.subBuf(startPos, buf.prevPos());
  603. exprs.add(parseExpression(subBuf, false));
  604. return exprs;
  605. }
  606. } else if(allowMulti && (level == 1) && isDelim(t, FUNC_PARAM_SEP)) {
  607. TokBuf subBuf = buf.subBuf(startPos, buf.prevPos());
  608. exprs.add(parseExpression(subBuf, false));
  609. startPos = buf.curPos();
  610. }
  611. }
  612. throw new ParseException("Missing closing '" + CLOSE_PAREN
  613. + " " + buf);
  614. }
  615. private static void parseOperatorExpression(Token t, TokBuf buf) {
  616. // most ops are two argument except that '-' could be negation, "+" could
  617. // be pos-ation
  618. if(buf.hasPendingExpr()) {
  619. parseBinaryOpExpression(t, buf);
  620. } else if(isEitherOp(t, "-", "+")) {
  621. parseUnaryOpExpression(t, buf);
  622. } else {
  623. throw new ParseException(
  624. "Missing left expression for binary operator " + t.getValue() +
  625. " " + buf);
  626. }
  627. }
  628. private static void parseBinaryOpExpression(Token firstTok, TokBuf buf) {
  629. BinaryOp op = getOpType(firstTok, BinaryOp.class);
  630. Expr leftExpr = buf.takePendingExpr();
  631. Expr rightExpr = parseExpression(buf, true);
  632. buf.setPendingExpr(new EBinaryOp(op, leftExpr, rightExpr));
  633. }
  634. private static void parseUnaryOpExpression(Token firstTok, TokBuf buf) {
  635. UnaryOp op = getOpType(firstTok, UnaryOp.class);
  636. UnaryOp numOp = op.getUnaryNumOp();
  637. if(numOp != null) {
  638. // if this operator is immediately preceding a number, it has a higher
  639. // precedence
  640. Token nextTok = buf.peekNext();
  641. if((nextTok != null) && (nextTok.getType() == TokenType.LITERAL) &&
  642. nextTok.getValueType().isNumeric()) {
  643. op = numOp;
  644. }
  645. }
  646. Expr val = parseExpression(buf, true);
  647. buf.setPendingExpr(new EUnaryOp(op, val));
  648. }
  649. private static void parseCompOpExpression(Token firstTok, TokBuf buf) {
  650. if(!buf.hasPendingExpr()) {
  651. if(buf.getExprType() == Type.FIELD_VALIDATOR) {
  652. // comparison operators for field validators can implicitly use
  653. // the current field value for the left value
  654. buf.setPendingExpr(THIS_COL_VALUE);
  655. } else {
  656. throw new ParseException(
  657. "Missing left expression for comparison operator " +
  658. firstTok.getValue() + " " + buf);
  659. }
  660. }
  661. CompOp op = getOpType(firstTok, CompOp.class);
  662. Expr leftExpr = buf.takePendingExpr();
  663. Expr rightExpr = parseExpression(buf, true);
  664. buf.setPendingExpr(new ECompOp(op, leftExpr, rightExpr));
  665. }
  666. private static void parseLogicalOpExpression(Token firstTok, TokBuf buf) {
  667. if(!buf.hasPendingExpr()) {
  668. throw new ParseException(
  669. "Missing left expression for logical operator " +
  670. firstTok.getValue() + " " + buf);
  671. }
  672. LogOp op = getOpType(firstTok, LogOp.class);
  673. Expr leftExpr = buf.takePendingExpr();
  674. Expr rightExpr = parseExpression(buf, true);
  675. buf.setPendingExpr(new ELogicalOp(op, leftExpr, rightExpr));
  676. }
  677. private static void parseSpecOpExpression(Token firstTok, TokBuf buf) {
  678. SpecOp specOp = getSpecialOperator(firstTok, buf);
  679. if(specOp == SpecOp.NOT) {
  680. // this is the unary prefix operator
  681. parseUnaryOpExpression(firstTok, buf);
  682. return;
  683. }
  684. if(!buf.hasPendingExpr()) {
  685. if(buf.getExprType() == Type.FIELD_VALIDATOR) {
  686. // comparison operators for field validators can implicitly use
  687. // the current field value for the left value
  688. buf.setPendingExpr(THIS_COL_VALUE);
  689. } else {
  690. throw new ParseException(
  691. "Missing left expression for comparison operator " +
  692. specOp + " " + buf);
  693. }
  694. }
  695. Expr expr = buf.takePendingExpr();
  696. Expr specOpExpr = null;
  697. switch(specOp) {
  698. case IS_NULL:
  699. case IS_NOT_NULL:
  700. specOpExpr = new ENullOp(specOp, expr);
  701. break;
  702. case LIKE:
  703. Token t = buf.next();
  704. if((t.getType() != TokenType.LITERAL) ||
  705. (t.getValueType() != Value.Type.STRING)) {
  706. throw new ParseException("Missing Like pattern " + buf);
  707. }
  708. String patternStr = t.getValueStr();
  709. specOpExpr = new ELikeOp(specOp, expr, patternStr);
  710. break;
  711. case BETWEEN:
  712. case NOT_BETWEEN:
  713. // the "rest" of a between expression is of the form "X And Y". we are
  714. // going to speculatively parse forward until we find the "And"
  715. // operator.
  716. Expr startRangeExpr = null;
  717. while(true) {
  718. Expr tmpExpr = parseExpression(buf, true);
  719. Token tmpT = buf.peekNext();
  720. if(tmpT == null) {
  721. // ran out of expression?
  722. throw new ParseException(
  723. "Missing 'And' for 'Between' expression " + buf);
  724. }
  725. if(isString(tmpT, "and")) {
  726. buf.next();
  727. startRangeExpr = tmpExpr;
  728. break;
  729. }
  730. // put the pending expression back and try parsing some more
  731. buf.restorePendingExpr(tmpExpr);
  732. }
  733. Expr endRangeExpr = parseExpression(buf, true);
  734. specOpExpr = new EBetweenOp(specOp, expr, startRangeExpr, endRangeExpr);
  735. break;
  736. case IN:
  737. case NOT_IN:
  738. // there might be a space before open paren
  739. t = buf.next();
  740. if(t.getType() == TokenType.SPACE) {
  741. t = buf.next();
  742. }
  743. if(!isDelim(t, OPEN_PAREN)) {
  744. throw new ParseException("Malformed In expression " + buf);
  745. }
  746. List<Expr> exprs = findParenExprs(buf, true);
  747. specOpExpr = new EInOp(specOp, expr, exprs);
  748. break;
  749. default:
  750. throw new ParseException("Unexpected special op " + specOp);
  751. }
  752. buf.setPendingExpr(specOpExpr);
  753. }
  754. private static SpecOp getSpecialOperator(Token firstTok, TokBuf buf) {
  755. String opStr = firstTok.getValueStr().toLowerCase();
  756. if("is".equals(opStr)) {
  757. Token t = buf.peekNext();
  758. if(isString(t, "null")) {
  759. buf.next();
  760. return SpecOp.IS_NULL;
  761. } else if(isString(t, "not")) {
  762. buf.next();
  763. t = buf.peekNext();
  764. if(isString(t, "null")) {
  765. return SpecOp.IS_NOT_NULL;
  766. }
  767. }
  768. } else if("like".equals(opStr)) {
  769. return SpecOp.LIKE;
  770. } else if("between".equals(opStr)) {
  771. return SpecOp.BETWEEN;
  772. } else if("in".equals(opStr)) {
  773. return SpecOp.IN;
  774. } else if("not".equals(opStr)) {
  775. Token t = buf.peekNext();
  776. if(isString(t, "between")) {
  777. buf.next();
  778. return SpecOp.NOT_BETWEEN;
  779. } else if(isString(t, "in")) {
  780. buf.next();
  781. return SpecOp.NOT_IN;
  782. }
  783. return SpecOp.NOT;
  784. }
  785. throw new ParseException(
  786. "Malformed special operator " + opStr + " " + buf);
  787. }
  788. private static void parseConstExpression(Token firstTok, TokBuf buf) {
  789. Expr constExpr = null;
  790. if("true".equalsIgnoreCase(firstTok.getValueStr())) {
  791. constExpr = TRUE_VALUE;
  792. } else if("false".equalsIgnoreCase(firstTok.getValueStr())) {
  793. constExpr = FALSE_VALUE;
  794. } else if("null".equalsIgnoreCase(firstTok.getValueStr())) {
  795. constExpr = NULL_VALUE;
  796. } else {
  797. throw new ParseException("Unexpected CONST word "
  798. + firstTok.getValue());
  799. }
  800. buf.setPendingExpr(constExpr);
  801. }
  802. private static boolean isObjNameSep(Token t) {
  803. return (isDelim(t, ".") || isDelim(t, "!"));
  804. }
  805. private static boolean isOp(Token t, String opStr) {
  806. return ((t != null) && (t.getType() == TokenType.OP) &&
  807. opStr.equalsIgnoreCase(t.getValueStr()));
  808. }
  809. private static boolean isEitherOp(Token t, String opStr1, String opStr2) {
  810. return ((t != null) && (t.getType() == TokenType.OP) &&
  811. (opStr1.equalsIgnoreCase(t.getValueStr()) ||
  812. opStr2.equalsIgnoreCase(t.getValueStr())));
  813. }
  814. private static boolean isDelim(Token t, String opStr) {
  815. return ((t != null) && (t.getType() == TokenType.DELIM) &&
  816. opStr.equalsIgnoreCase(t.getValueStr()));
  817. }
  818. private static boolean isString(Token t, String opStr) {
  819. return ((t != null) && (t.getType() == TokenType.STRING) &&
  820. opStr.equalsIgnoreCase(t.getValueStr()));
  821. }
  822. private static WordType getWordType(Token t) {
  823. return WORD_TYPES.get(t.getValueStr().toLowerCase());
  824. }
  825. private static void setWordType(WordType type, String... words) {
  826. for(String w : words) {
  827. WORD_TYPES.put(w, type);
  828. }
  829. }
  830. private static <T extends Enum<T>> T getOpType(Token t, Class<T> opClazz) {
  831. String str = t.getValueStr();
  832. for(T op : opClazz.getEnumConstants()) {
  833. if(str.equalsIgnoreCase(op.toString())) {
  834. return op;
  835. }
  836. }
  837. throw new ParseException("Unexpected op string " + t.getValueStr());
  838. }
  839. private static final class TokBuf
  840. {
  841. private final Type _exprType;
  842. private final List<Token> _tokens;
  843. private final TokBuf _parent;
  844. private final int _parentOff;
  845. private final ParseContext _context;
  846. private int _pos;
  847. private Expr _pendingExpr;
  848. private TokBuf(Type exprType, List<Token> tokens, ParseContext context) {
  849. this(exprType, tokens, null, 0, context);
  850. }
  851. private TokBuf(List<Token> tokens, TokBuf parent, int parentOff) {
  852. this(parent._exprType, tokens, parent, parentOff, parent._context);
  853. }
  854. private TokBuf(Type exprType, List<Token> tokens, TokBuf parent,
  855. int parentOff, ParseContext context) {
  856. _exprType = exprType;
  857. _tokens = tokens;
  858. _parent = parent;
  859. _parentOff = parentOff;
  860. _context = context;
  861. }
  862. public Type getExprType() {
  863. return _exprType;
  864. }
  865. public int curPos() {
  866. return _pos;
  867. }
  868. public int prevPos() {
  869. return _pos - 1;
  870. }
  871. public boolean hasNext() {
  872. return (_pos < _tokens.size());
  873. }
  874. public Token peekNext() {
  875. if(!hasNext()) {
  876. return null;
  877. }
  878. return _tokens.get(_pos);
  879. }
  880. public Token next() {
  881. if(!hasNext()) {
  882. throw new ParseException(
  883. "Unexpected end of expression " + this);
  884. }
  885. return _tokens.get(_pos++);
  886. }
  887. public void reset(int pos) {
  888. _pos = pos;
  889. }
  890. public TokBuf subBuf(int start, int end) {
  891. return new TokBuf(_tokens.subList(start, end), this, start);
  892. }
  893. public void setPendingExpr(Expr expr) {
  894. if(_pendingExpr != null) {
  895. throw new ParseException(
  896. "Found multiple expressions with no operator " + this);
  897. }
  898. _pendingExpr = expr.resolveOrderOfOperations();
  899. }
  900. public void restorePendingExpr(Expr expr) {
  901. // this is an expression which was previously set, so no need to re-resolve
  902. _pendingExpr = expr;
  903. }
  904. public Expr takePendingExpr() {
  905. Expr expr = _pendingExpr;
  906. _pendingExpr = null;
  907. return expr;
  908. }
  909. public boolean hasPendingExpr() {
  910. return (_pendingExpr != null);
  911. }
  912. private Map.Entry<Integer,List<Token>> getTopPos() {
  913. int pos = _pos;
  914. List<Token> toks = _tokens;
  915. TokBuf cur = this;
  916. while(cur._parent != null) {
  917. pos += cur._parentOff;
  918. cur = cur._parent;
  919. toks = cur._tokens;
  920. }
  921. return ExpressionTokenizer.newEntry(pos, toks);
  922. }
  923. public Function getFunction(String funcName) {
  924. return _context.getExpressionFunction(funcName);
  925. }
  926. @Override
  927. public String toString() {
  928. Map.Entry<Integer,List<Token>> e = getTopPos();
  929. // TODO actually format expression?
  930. StringBuilder sb = new StringBuilder()
  931. .append("[token ").append(e.getKey()).append("] (");
  932. for(Iterator<Token> iter = e.getValue().iterator(); iter.hasNext(); ) {
  933. Token t = iter.next();
  934. sb.append("'").append(t.getValueStr()).append("'");
  935. if(iter.hasNext()) {
  936. sb.append(",");
  937. }
  938. }
  939. sb.append(")");
  940. if(_pendingExpr != null) {
  941. sb.append(" [pending '").append(_pendingExpr.toDebugString())
  942. .append("']");
  943. }
  944. return sb.toString();
  945. }
  946. }
  947. private static boolean isHigherPrecendence(OpType op1, OpType op2) {
  948. int prec1 = PRECENDENCE.get(op1);
  949. int prec2 = PRECENDENCE.get(op2);
  950. // higher preceendence ops have lower numbers
  951. return (prec1 < prec2);
  952. }
  953. private static final Map<OpType, Integer> buildPrecedenceMap(
  954. OpType[]... opArrs) {
  955. Map<OpType, Integer> prec = new HashMap<OpType, Integer>();
  956. int level = 0;
  957. for(OpType[] ops : opArrs) {
  958. for(OpType op : ops) {
  959. prec.put(op, level);
  960. }
  961. ++level;
  962. }
  963. return prec;
  964. }
  965. private static void exprListToString(
  966. List<Expr> exprs, String sep, StringBuilder sb, boolean isDebug) {
  967. Iterator<Expr> iter = exprs.iterator();
  968. iter.next().toString(sb, isDebug);
  969. while(iter.hasNext()) {
  970. sb.append(sep);
  971. iter.next().toString(sb, isDebug);
  972. }
  973. }
  974. private static Value[] exprListToValues(
  975. List<Expr> exprs, EvalContext ctx) {
  976. Value[] paramVals = new Value[exprs.size()];
  977. for(int i = 0; i < exprs.size(); ++i) {
  978. paramVals[i] = exprs.get(i).eval(ctx);
  979. }
  980. return paramVals;
  981. }
  982. private static Value[] exprListToDelayedValues(
  983. List<Expr> exprs, EvalContext ctx) {
  984. Value[] paramVals = new Value[exprs.size()];
  985. for(int i = 0; i < exprs.size(); ++i) {
  986. paramVals[i] = new DelayedValue(exprs.get(i), ctx);
  987. }
  988. return paramVals;
  989. }
  990. private static boolean areConstant(List<Expr> exprs) {
  991. for(Expr expr : exprs) {
  992. if(!expr.isConstant()) {
  993. return false;
  994. }
  995. }
  996. return true;
  997. }
  998. private static boolean areConstant(Expr... exprs) {
  999. for(Expr expr : exprs) {
  1000. if(!expr.isConstant()) {
  1001. return false;
  1002. }
  1003. }
  1004. return true;
  1005. }
  1006. private static void literalStrToString(String str, StringBuilder sb) {
  1007. sb.append("\"")
  1008. .append(str.replace("\"", "\"\""))
  1009. .append("\"");
  1010. }
  1011. private static Pattern likePatternToRegex(String pattern) {
  1012. StringBuilder sb = new StringBuilder(pattern.length());
  1013. // Access LIKE pattern supports (note, matching is case-insensitive):
  1014. // - '*' -> 0 or more chars
  1015. // - '?' -> single character
  1016. // - '#' -> single digit
  1017. // - '[...]' -> character class, '[!...]' -> not in char class
  1018. for(int i = 0; i < pattern.length(); ++i) {
  1019. char c = pattern.charAt(i);
  1020. if(c == '*') {
  1021. sb.append(".*");
  1022. } else if(c == '?') {
  1023. sb.append('.');
  1024. } else if(c == '#') {
  1025. sb.append("\\d");
  1026. } else if(c == '[') {
  1027. // find closing brace
  1028. int startPos = i + 1;
  1029. int endPos = -1;
  1030. for(int j = startPos; j < pattern.length(); ++j) {
  1031. if(pattern.charAt(j) == ']') {
  1032. endPos = j;
  1033. break;
  1034. }
  1035. }
  1036. // access treats invalid expression like "unmatchable"
  1037. if(endPos == -1) {
  1038. return UNMATCHABLE_REGEX;
  1039. }
  1040. String charClass = pattern.substring(startPos, endPos);
  1041. if((charClass.length() > 0) && (charClass.charAt(0) == '!')) {
  1042. // this is a negated char class
  1043. charClass = '^' + charClass.substring(1);
  1044. }
  1045. sb.append('[').append(charClass).append(']');
  1046. i += (endPos - startPos) + 1;
  1047. } else if(REGEX_SPEC_CHARS.contains(c)) {
  1048. // this char is special in regexes, so escape it
  1049. sb.append('\\').append(c);
  1050. } else {
  1051. sb.append(c);
  1052. }
  1053. }
  1054. try {
  1055. return Pattern.compile(sb.toString(),
  1056. Pattern.CASE_INSENSITIVE | Pattern.DOTALL |
  1057. Pattern.UNICODE_CASE);
  1058. } catch(PatternSyntaxException ignored) {
  1059. return UNMATCHABLE_REGEX;
  1060. }
  1061. }
  1062. private static Value toLiteralValue(Value.Type valType, Object value,
  1063. DateFormat sdf)
  1064. {
  1065. switch(valType) {
  1066. case STRING:
  1067. return BuiltinOperators.toValue((String)value);
  1068. case DATE:
  1069. return new DateValue((Date)value, sdf);
  1070. case TIME:
  1071. return new TimeValue((Date)value, sdf);
  1072. case DATE_TIME:
  1073. return new DateTimeValue((Date)value, sdf);
  1074. case LONG:
  1075. return BuiltinOperators.toValue((Integer)value);
  1076. case DOUBLE:
  1077. return BuiltinOperators.toValue((Double)value);
  1078. case BIG_DEC:
  1079. return BuiltinOperators.toValue((BigDecimal)value);
  1080. default:
  1081. throw new ParseException("unexpected literal type " + valType);
  1082. }
  1083. }
  1084. private static boolean isLiteralDefaultValue(
  1085. TokBuf buf, Value.Type resultType, String exprStr) {
  1086. // if a default value expression does not start with an '=' and is used in
  1087. // a string context, then it is taken as a literal value unless it starts
  1088. // with a " char
  1089. if(buf.getExprType() != Type.DEFAULT_VALUE) {
  1090. return false;
  1091. }
  1092. // a leading "=" indicates "full" expression handling for a DEFAULT_VALUE
  1093. // (consume this value once we detect it)
  1094. if(isOp(buf.peekNext(), "=")) {
  1095. buf.next();
  1096. return false;
  1097. }
  1098. return((resultType == Value.Type.STRING) &&
  1099. ((exprStr.length() == 0) ||
  1100. (exprStr.charAt(0) != ExpressionTokenizer.QUOTED_STR_CHAR)));
  1101. }
  1102. private interface LeftAssocExpr {
  1103. public OpType getOp();
  1104. public Expr getLeft();
  1105. public void setLeft(Expr left);
  1106. }
  1107. private interface RightAssocExpr {
  1108. public OpType getOp();
  1109. public Expr getRight();
  1110. public void setRight(Expr right);
  1111. }
  1112. private static final class DelayedValue extends BaseDelayedValue
  1113. {
  1114. private final Expr _expr;
  1115. private final EvalContext _ctx;
  1116. private DelayedValue(Expr expr, EvalContext ctx) {
  1117. _expr = expr;
  1118. _ctx = ctx;
  1119. }
  1120. @Override
  1121. public Value eval() {
  1122. return _expr.eval(_ctx);
  1123. }
  1124. }
  1125. private static abstract class Expr
  1126. {
  1127. @Override
  1128. public String toString() {
  1129. StringBuilder sb = new StringBuilder();
  1130. toString(sb, false);
  1131. return sb.toString();
  1132. }
  1133. public String toDebugString() {
  1134. StringBuilder sb = new StringBuilder();
  1135. toString(sb, true);
  1136. return sb.toString();
  1137. }
  1138. protected boolean isConditionalExpr() {
  1139. return false;
  1140. }
  1141. protected void toString(StringBuilder sb, boolean isDebug) {
  1142. if(isDebug) {
  1143. sb.append("<").append(getClass().getSimpleName()).append(">{");
  1144. }
  1145. toExprString(sb, isDebug);
  1146. if(isDebug) {
  1147. sb.append("}");
  1148. }
  1149. }
  1150. protected Expr resolveOrderOfOperations() {
  1151. if(!(this instanceof LeftAssocExpr)) {
  1152. // nothing we can do
  1153. return this;
  1154. }
  1155. // in order to get the precedence right, we need to first associate this
  1156. // expression with the "rightmost" expression preceding it, then adjust
  1157. // this expression "down" (lower precedence) as the precedence of the
  1158. // operations dictates. since we parse from left to right, the initial
  1159. // "left" value isn't the immediate left expression, instead it's based
  1160. // on how the preceding operator precedence worked out. we need to
  1161. // adjust "this" expression to the closest preceding expression before
  1162. // we can correctly resolve precedence.
  1163. Expr outerExpr = this;
  1164. final LeftAssocExpr thisExpr = (LeftAssocExpr)this;
  1165. final Expr thisLeft = thisExpr.getLeft();
  1166. // current: <this>{<left>{A op1 B} op2 <right>{C}}
  1167. if(thisLeft instanceof RightAssocExpr) {
  1168. RightAssocExpr leftOp = (RightAssocExpr)thisLeft;
  1169. // target: <left>{A op1 <this>{B op2 <right>{C}}}
  1170. thisExpr.setLeft(leftOp.getRight());
  1171. // give the new version of this expression an opportunity to further
  1172. // swap (since the swapped expression may itself be a binary
  1173. // expression)
  1174. leftOp.setRight(resolveOrderOfOperations());
  1175. outerExpr = thisLeft;
  1176. // at this point, this expression has been pushed all the way to the
  1177. // rightmost preceding expression (we artifically gave "this" the
  1178. // highest precedence). now, we want to adjust precedence as
  1179. // necessary (shift it back down if the operator precedence is
  1180. // incorrect). note, we only need to check precedence against "this",
  1181. // as all other precedence has been resolved in previous parsing
  1182. // rounds.
  1183. if((leftOp.getRight() == this) &&
  1184. !isHigherPrecendence(thisExpr.getOp(), leftOp.getOp())) {
  1185. // doh, "this" is lower (or the same) precedence, restore the
  1186. // original order of things
  1187. leftOp.setRight(thisExpr.getLeft());
  1188. thisExpr.setLeft(thisLeft);
  1189. outerExpr = this;
  1190. }
  1191. }
  1192. return outerExpr;
  1193. }
  1194. public abstract boolean isConstant();
  1195. public abstract Value eval(EvalContext ctx);
  1196. public abstract void collectIdentifiers(Collection<Identifier> identifiers);
  1197. protected abstract void toExprString(StringBuilder sb, boolean isDebug);
  1198. }
  1199. private static final class EConstValue extends Expr
  1200. {
  1201. private final Value _val;
  1202. private final String _str;
  1203. private EConstValue(Value val, String str) {
  1204. _val = val;
  1205. _str = str;
  1206. }
  1207. @Override
  1208. public boolean isConstant() {
  1209. return true;
  1210. }
  1211. @Override
  1212. public Value eval(EvalContext ctx) {
  1213. return _val;
  1214. }
  1215. @Override
  1216. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1217. // none
  1218. }
  1219. @Override
  1220. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1221. sb.append(_str);
  1222. }
  1223. }
  1224. private static final class EThisValue extends Expr
  1225. {
  1226. @Override
  1227. public boolean isConstant() {
  1228. return false;
  1229. }
  1230. @Override
  1231. public Value eval(EvalContext ctx) {
  1232. return ctx.getThisColumnValue();
  1233. }
  1234. @Override
  1235. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1236. // none
  1237. }
  1238. @Override
  1239. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1240. sb.append("<THIS_COL>");
  1241. }
  1242. }
  1243. private static final class ELiteralValue extends Expr
  1244. {
  1245. private final Value _val;
  1246. private ELiteralValue(Value.Type valType, Object value,
  1247. DateFormat sdf) {
  1248. _val = toLiteralValue(valType, value, sdf);
  1249. }
  1250. @Override
  1251. public boolean isConstant() {
  1252. return true;
  1253. }
  1254. @Override
  1255. public Value eval(EvalContext ctx) {
  1256. return _val;
  1257. }
  1258. @Override
  1259. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1260. // none
  1261. }
  1262. @Override
  1263. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1264. if(_val.getType() == Value.Type.STRING) {
  1265. literalStrToString((String)_val.get(), sb);
  1266. } else if(_val.getType().isTemporal()) {
  1267. sb.append("#").append(_val.getAsString()).append("#");
  1268. } else {
  1269. sb.append(_val.get());
  1270. }
  1271. }
  1272. }
  1273. private static final class EObjValue extends Expr
  1274. {
  1275. private final Identifier _identifier;
  1276. private EObjValue(Identifier identifier) {
  1277. _identifier = identifier;
  1278. }
  1279. @Override
  1280. public boolean isConstant() {
  1281. return false;
  1282. }
  1283. @Override
  1284. public Value eval(EvalContext ctx) {
  1285. return ctx.getIdentifierValue(_identifier);
  1286. }
  1287. @Override
  1288. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1289. identifiers.add(_identifier);
  1290. }
  1291. @Override
  1292. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1293. sb.append(_identifier);
  1294. }
  1295. }
  1296. private static class EParen extends Expr
  1297. {
  1298. private final Expr _expr;
  1299. private EParen(Expr expr) {
  1300. _expr = expr;
  1301. }
  1302. @Override
  1303. public boolean isConstant() {
  1304. return _expr.isConstant();
  1305. }
  1306. @Override
  1307. protected boolean isConditionalExpr() {
  1308. return _expr.isConditionalExpr();
  1309. }
  1310. @Override
  1311. public Value eval(EvalContext ctx) {
  1312. return _expr.eval(ctx);
  1313. }
  1314. @Override
  1315. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1316. _expr.collectIdentifiers(identifiers);
  1317. }
  1318. @Override
  1319. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1320. sb.append("(");
  1321. _expr.toString(sb, isDebug);
  1322. sb.append(")");
  1323. }
  1324. }
  1325. private static class EFunc extends Expr
  1326. {
  1327. private final Function _func;
  1328. private final List<Expr> _params;
  1329. private EFunc(Function func, List<Expr> params) {
  1330. _func = func;
  1331. _params = params;
  1332. }
  1333. @Override
  1334. public boolean isConstant() {
  1335. return _func.isPure() && areConstant(_params);
  1336. }
  1337. @Override
  1338. public Value eval(EvalContext ctx) {
  1339. return _func.eval(ctx, exprListToValues(_params, ctx));
  1340. }
  1341. @Override
  1342. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1343. for(Expr param : _params) {
  1344. param.collectIdentifiers(identifiers);
  1345. }
  1346. }
  1347. @Override
  1348. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1349. sb.append(_func.getName()).append("(");
  1350. if(!_params.isEmpty()) {
  1351. exprListToString(_params, ",", sb, isDebug);
  1352. }
  1353. sb.append(")");
  1354. }
  1355. }
  1356. private static abstract class EBaseBinaryOp extends Expr
  1357. implements LeftAssocExpr, RightAssocExpr
  1358. {
  1359. protected final OpType _op;
  1360. protected Expr _left;
  1361. protected Expr _right;
  1362. private EBaseBinaryOp(OpType op, Expr left, Expr right) {
  1363. _op = op;
  1364. _left = left;
  1365. _right = right;
  1366. }
  1367. @Override
  1368. public boolean isConstant() {
  1369. return areConstant(_left, _right);
  1370. }
  1371. public OpType getOp() {
  1372. return _op;
  1373. }
  1374. public Expr getLeft() {
  1375. return _left;
  1376. }
  1377. public void setLeft(Expr left) {
  1378. _left = left;
  1379. }
  1380. public Expr getRight() {
  1381. return _right;
  1382. }
  1383. public void setRight(Expr right) {
  1384. _right = right;
  1385. }
  1386. @Override
  1387. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1388. _left.collectIdentifiers(identifiers);
  1389. _right.collectIdentifiers(identifiers);
  1390. }
  1391. @Override
  1392. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1393. _left.toString(sb, isDebug);
  1394. sb.append(" ").append(_op).append(" ");
  1395. _right.toString(sb, isDebug);
  1396. }
  1397. }
  1398. private static class EBinaryOp extends EBaseBinaryOp
  1399. {
  1400. private EBinaryOp(BinaryOp op, Expr left, Expr right) {
  1401. super(op, left, right);
  1402. }
  1403. @Override
  1404. public Value eval(EvalContext ctx) {
  1405. return ((BinaryOp)_op).eval(ctx, _left.eval(ctx), _right.eval(ctx));
  1406. }
  1407. }
  1408. private static class EUnaryOp extends Expr
  1409. implements RightAssocExpr
  1410. {
  1411. private final OpType _op;
  1412. private Expr _expr;
  1413. private EUnaryOp(UnaryOp op, Expr expr) {
  1414. _op = op;
  1415. _expr = expr;
  1416. }
  1417. @Override
  1418. public boolean isConstant() {
  1419. return _expr.isConstant();
  1420. }
  1421. public OpType getOp() {
  1422. return _op;
  1423. }
  1424. public Expr getRight() {
  1425. return _expr;
  1426. }
  1427. public void setRight(Expr right) {
  1428. _expr = right;
  1429. }
  1430. @Override
  1431. public Value eval(EvalContext ctx) {
  1432. return ((UnaryOp)_op).eval(ctx, _expr.eval(ctx));
  1433. }
  1434. @Override
  1435. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1436. _expr.collectIdentifiers(identifiers);
  1437. }
  1438. @Override
  1439. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1440. sb.append(_op);
  1441. if(isDebug || ((UnaryOp)_op).needsSpace()) {
  1442. sb.append(" ");
  1443. }
  1444. _expr.toString(sb, isDebug);
  1445. }
  1446. }
  1447. private static class ECompOp extends EBaseBinaryOp
  1448. {
  1449. private ECompOp(CompOp op, Expr left, Expr right) {
  1450. super(op, left, right);
  1451. }
  1452. @Override
  1453. protected boolean isConditionalExpr() {
  1454. return true;
  1455. }
  1456. @Override
  1457. public Value eval(EvalContext ctx) {
  1458. return ((CompOp)_op).eval(_left.eval(ctx), _right.eval(ctx));
  1459. }
  1460. }
  1461. private static class EImplicitCompOp extends ECompOp
  1462. {
  1463. private EImplicitCompOp(Expr right) {
  1464. super(CompOp.EQ, THIS_COL_VALUE, right);
  1465. }
  1466. @Override
  1467. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1468. // only output the full "implicit" comparison in debug mode
  1469. if(isDebug) {
  1470. super.toExprString(sb, isDebug);
  1471. } else {
  1472. // just output the explicit part of the expression
  1473. _right.toString(sb, isDebug);
  1474. }
  1475. }
  1476. }
  1477. private static class ELogicalOp extends EBaseBinaryOp
  1478. {
  1479. private ELogicalOp(LogOp op, Expr left, Expr right) {
  1480. super(op, left, right);
  1481. }
  1482. @Override
  1483. public Value eval(final EvalContext ctx) {
  1484. // logical operations do short circuit evaluation, so we need to delay
  1485. // computing results until necessary
  1486. return ((LogOp)_op).eval(new DelayedValue(_left, ctx),
  1487. new DelayedValue(_right, ctx));
  1488. }
  1489. }
  1490. private static abstract class ESpecOp extends Expr
  1491. implements LeftAssocExpr
  1492. {
  1493. protected final SpecOp _op;
  1494. protected Expr _expr;
  1495. private ESpecOp(SpecOp op, Expr expr) {
  1496. _op = op;
  1497. _expr = expr;
  1498. }
  1499. @Override
  1500. public boolean isConstant() {
  1501. return _expr.isConstant();
  1502. }
  1503. public OpType getOp() {
  1504. return _op;
  1505. }
  1506. public Expr getLeft() {
  1507. return _expr;
  1508. }
  1509. public void setLeft(Expr left) {
  1510. _expr = left;
  1511. }
  1512. @Override
  1513. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1514. _expr.collectIdentifiers(identifiers);
  1515. }
  1516. @Override
  1517. protected boolean isConditionalExpr() {
  1518. return true;
  1519. }
  1520. }
  1521. private static class ENullOp extends ESpecOp
  1522. {
  1523. private ENullOp(SpecOp op, Expr expr) {
  1524. super(op, expr);
  1525. }
  1526. @Override
  1527. public Value eval(EvalContext ctx) {
  1528. return _op.eval(_expr.eval(ctx), null, null);
  1529. }
  1530. @Override
  1531. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1532. _expr.toString(sb, isDebug);
  1533. sb.append(" ").append(_op);
  1534. }
  1535. }
  1536. private static class ELikeOp extends ESpecOp
  1537. {
  1538. private final String _patternStr;
  1539. private Pattern _pattern;
  1540. private ELikeOp(SpecOp op, Expr expr, String patternStr) {
  1541. super(op, expr);
  1542. _patternStr = patternStr;
  1543. }
  1544. private Pattern getPattern()
  1545. {
  1546. if(_pattern == null) {
  1547. _pattern = likePatternToRegex(_patternStr);
  1548. }
  1549. return _pattern;
  1550. }
  1551. @Override
  1552. public Value eval(EvalContext ctx) {
  1553. return _op.eval(_expr.eval(ctx), getPattern(), null);
  1554. }
  1555. @Override
  1556. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1557. _expr.toString(sb, isDebug);
  1558. sb.append(" ").append(_op).append(" ");
  1559. literalStrToString(_patternStr, sb);
  1560. if(isDebug) {
  1561. sb.append("(").append(getPattern()).append(")");
  1562. }
  1563. }
  1564. }
  1565. private static class EInOp extends ESpecOp
  1566. {
  1567. private final List<Expr> _exprs;
  1568. private EInOp(SpecOp op, Expr expr, List<Expr> exprs) {
  1569. super(op, expr);
  1570. _exprs = exprs;
  1571. }
  1572. @Override
  1573. public boolean isConstant() {
  1574. return super.isConstant() && areConstant(_exprs);
  1575. }
  1576. @Override
  1577. public Value eval(EvalContext ctx) {
  1578. return _op.eval(_expr.eval(ctx),
  1579. exprListToDelayedValues(_exprs, ctx), null);
  1580. }
  1581. @Override
  1582. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1583. for(Expr expr : _exprs) {
  1584. expr.collectIdentifiers(identifiers);
  1585. }
  1586. }
  1587. @Override
  1588. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1589. _expr.toString(sb, isDebug);
  1590. sb.append(" ").append(_op).append(" (");
  1591. exprListToString(_exprs, ",", sb, isDebug);
  1592. sb.append(")");
  1593. }
  1594. }
  1595. private static class EBetweenOp extends ESpecOp
  1596. implements RightAssocExpr
  1597. {
  1598. private final Expr _startRangeExpr;
  1599. private Expr _endRangeExpr;
  1600. private EBetweenOp(SpecOp op, Expr expr, Expr startRangeExpr,
  1601. Expr endRangeExpr) {
  1602. super(op, expr);
  1603. _startRangeExpr = startRangeExpr;
  1604. _endRangeExpr = endRangeExpr;
  1605. }
  1606. @Override
  1607. public boolean isConstant() {
  1608. return _expr.isConstant() && areConstant(_startRangeExpr, _endRangeExpr);
  1609. }
  1610. public Expr getRight() {
  1611. return _endRangeExpr;
  1612. }
  1613. public void setRight(Expr right) {
  1614. _endRangeExpr = right;
  1615. }
  1616. @Override
  1617. public Value eval(EvalContext ctx) {
  1618. return _op.eval(_expr.eval(ctx),
  1619. new DelayedValue(_startRangeExpr, ctx),
  1620. new DelayedValue(_endRangeExpr, ctx));
  1621. }
  1622. @Override
  1623. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1624. super.collectIdentifiers(identifiers);
  1625. _startRangeExpr.collectIdentifiers(identifiers);
  1626. _endRangeExpr.collectIdentifiers(identifiers);
  1627. }
  1628. @Override
  1629. protected void toExprString(StringBuilder sb, boolean isDebug) {
  1630. _expr.toString(sb, isDebug);
  1631. sb.append(" ").append(_op).append(" ");
  1632. _startRangeExpr.toString(sb, isDebug);
  1633. sb.append(" And ");
  1634. _endRangeExpr.toString(sb, isDebug);
  1635. }
  1636. }
  1637. /**
  1638. * Base Expression wrapper for an Expr.
  1639. */
  1640. private static abstract class BaseExprWrapper implements Expression
  1641. {
  1642. private final Expr _expr;
  1643. private BaseExprWrapper(Expr expr) {
  1644. _expr = expr;
  1645. }
  1646. public String toDebugString() {
  1647. return _expr.toDebugString();
  1648. }
  1649. public boolean isConstant() {
  1650. return _expr.isConstant();
  1651. }
  1652. public void collectIdentifiers(Collection<Identifier> identifiers) {
  1653. _expr.collectIdentifiers(identifiers);
  1654. }
  1655. @Override
  1656. public String toString() {
  1657. return _expr.toString();
  1658. }
  1659. protected Object evalValue(Value.Type resultType, EvalContext ctx) {
  1660. Value val = _expr.eval(ctx);
  1661. if(val.isNull()) {
  1662. return null;
  1663. }
  1664. if(resultType == null) {
  1665. // return as "native" type
  1666. return val.get();
  1667. }
  1668. // FIXME possibly do some type coercion. are there conversions here which don't work elsewhere? (string -> date, string -> number)?
  1669. switch(resultType) {
  1670. case STRING:
  1671. return val.getAsString();
  1672. case DATE:
  1673. case TIME:
  1674. case DATE_TIME:
  1675. return val.getAsDateTime(ctx);
  1676. case LONG:
  1677. return val.getAsLongInt();
  1678. case DOUBLE:
  1679. return val.getAsDouble();
  1680. case BIG_DEC:
  1681. return val.getAsBigDecimal();
  1682. default:
  1683. throw new IllegalStateException("unexpected result type " + resultType);
  1684. }
  1685. }
  1686. protected Boolean evalCondition(EvalContext ctx) {
  1687. Value val = _expr.eval(ctx);
  1688. if(val.isNull()) {
  1689. // null can't be coerced to a boolean
  1690. throw new EvalException("Condition evaluated to Null");
  1691. }
  1692. return val.getAsBoolean();
  1693. }
  1694. }
  1695. /**
  1696. * Expression wrapper for an Expr which returns a value.
  1697. */
  1698. private static class ExprWrapper extends BaseExprWrapper
  1699. {
  1700. private final Value.Type _resultType;
  1701. private ExprWrapper(Expr expr, Value.Type resultType) {
  1702. super(expr);
  1703. _resultType = resultType;
  1704. }
  1705. public Object eval(EvalContext ctx) {
  1706. return evalValue(_resultType, ctx);
  1707. }
  1708. }
  1709. /**
  1710. * Expression wrapper for an Expr which returns a Boolean from a conditional
  1711. * expression.
  1712. */
  1713. private static class CondExprWrapper extends BaseExprWrapper
  1714. {
  1715. private CondExprWrapper(Expr expr) {
  1716. super(expr);
  1717. }
  1718. public Object eval(EvalContext ctx) {
  1719. return evalCondition(ctx);
  1720. }
  1721. }
  1722. /**
  1723. * Expression wrapper for a <i>pure</i> Expr which caches the result of
  1724. * evaluation.
  1725. */
  1726. private static final class MemoizedExprWrapper extends ExprWrapper
  1727. {
  1728. private Object _val;
  1729. private MemoizedExprWrapper(Expr expr, Value.Type resultType) {
  1730. super(expr, resultType);
  1731. }
  1732. @Override
  1733. public Object eval(EvalContext ctx) {
  1734. if(_val == null) {
  1735. _val = super.eval(ctx);
  1736. }
  1737. return _val;
  1738. }
  1739. }
  1740. /**
  1741. * Expression wrapper for a <i>pure</i> conditional Expr which caches the
  1742. * result of evaluation.
  1743. */
  1744. private static final class MemoizedCondExprWrapper extends CondExprWrapper
  1745. {
  1746. private Object _val;
  1747. private MemoizedCondExprWrapper(Expr expr) {
  1748. super(expr);
  1749. }
  1750. @Override
  1751. public Object eval(EvalContext ctx) {
  1752. if(_val == null) {
  1753. _val = super.eval(ctx);
  1754. }
  1755. return _val;
  1756. }
  1757. }
  1758. }