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

Expressionator.java 59KB

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