Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

Expressionator.java 56KB

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