LogicalExpression.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. #pragma once
  2. //FIXME: move some of code into .cpp to avoid this include?
  3. #include "JsonNode.h"
  4. namespace LogicalExpressionDetail
  5. {
  6. /// class that defines required types for logical expressions
  7. template<typename ContainedClass>
  8. class ExpressionBase
  9. {
  10. public:
  11. /// Possible logical operations, mostly needed to create different types for boost::variant
  12. enum EOperations
  13. {
  14. ANY_OF,
  15. ALL_OF,
  16. NONE_OF
  17. };
  18. template<EOperations tag> class Element;
  19. typedef Element<ANY_OF> OperatorAny;
  20. typedef Element<ALL_OF> OperatorAll;
  21. typedef Element<NONE_OF> OperatorNone;
  22. typedef ContainedClass Value;
  23. /// Variant that contains all possible elements from logical expression
  24. typedef boost::variant<
  25. OperatorAll,
  26. OperatorAny,
  27. OperatorNone,
  28. Value
  29. > Variant;
  30. /// Variant element, contains list of expressions to which operation "tag" should be applied
  31. template<EOperations tag>
  32. class Element
  33. {
  34. public:
  35. Element() {}
  36. Element(std::vector<Variant> expressions):
  37. expressions(expressions)
  38. {}
  39. std::vector<Variant> expressions;
  40. bool operator == (const Element & other) const
  41. {
  42. return expressions == other.expressions;
  43. }
  44. template <typename Handler>
  45. void serialize(Handler & h, const int version)
  46. {
  47. h & expressions;
  48. }
  49. };
  50. };
  51. /// Visitor to test result (true/false) of the expression
  52. template <typename ContainedClass>
  53. class TestVisitor : public boost::static_visitor<bool>
  54. {
  55. typedef ExpressionBase<ContainedClass> Base;
  56. std::function<bool(const typename Base::Value &)> classTest;
  57. size_t countPassed(const std::vector<typename Base::Variant> & element) const
  58. {
  59. return boost::range::count_if(element, [&](const typename Base::Variant & expr)
  60. {
  61. return boost::apply_visitor(*this, expr);
  62. });
  63. }
  64. public:
  65. TestVisitor(std::function<bool (const typename Base::Value &)> classTest):
  66. classTest(classTest)
  67. {}
  68. bool operator()(const typename Base::OperatorAny & element) const
  69. {
  70. return countPassed(element.expressions) != 0;
  71. }
  72. bool operator()(const typename Base::OperatorAll & element) const
  73. {
  74. return countPassed(element.expressions) == element.expressions.size();
  75. }
  76. bool operator()(const typename Base::OperatorNone & element) const
  77. {
  78. return countPassed(element.expressions) == 0;
  79. }
  80. bool operator()(const typename Base::Value & element) const
  81. {
  82. return classTest(element);
  83. }
  84. };
  85. /// visitor that is trying to generates candidates that must be fulfilled
  86. /// to complete this expression
  87. template <typename ContainedClass>
  88. class CandidatesVisitor : public boost::static_visitor<std::vector<ContainedClass> >
  89. {
  90. typedef ExpressionBase<ContainedClass> Base;
  91. typedef std::vector<typename Base::Value> TValueList;
  92. TestVisitor<ContainedClass> classTest;
  93. public:
  94. CandidatesVisitor(std::function<bool(const typename Base::Value &)> classTest):
  95. classTest(classTest)
  96. {}
  97. TValueList operator()(const typename Base::OperatorAny & element) const
  98. {
  99. TValueList ret;
  100. if (!classTest(element))
  101. {
  102. for (auto & elem : element.expressions)
  103. boost::range::copy(boost::apply_visitor(*this, elem), std::back_inserter(ret));
  104. }
  105. return ret;
  106. }
  107. TValueList operator()(const typename Base::OperatorAll & element) const
  108. {
  109. TValueList ret;
  110. if (!classTest(element))
  111. {
  112. for (auto & elem : element.expressions)
  113. boost::range::copy(boost::apply_visitor(*this, elem), std::back_inserter(ret));
  114. }
  115. return ret;
  116. }
  117. TValueList operator()(const typename Base::OperatorNone & element) const
  118. {
  119. return TValueList(); //TODO. Implementing this one is not straightforward, if ever possible
  120. }
  121. TValueList operator()(const typename Base::Value & element) const
  122. {
  123. if (classTest(element))
  124. return TValueList();
  125. else
  126. return TValueList(1, element);
  127. }
  128. };
  129. /// Simple foreach visitor
  130. template <typename ContainedClass>
  131. class ForEachVisitor : public boost::static_visitor<typename ExpressionBase<ContainedClass>::Variant>
  132. {
  133. typedef ExpressionBase<ContainedClass> Base;
  134. std::function<typename Base::Variant(const typename Base::Value &)> visitor;
  135. public:
  136. ForEachVisitor(std::function<typename Base::Variant(const typename Base::Value &)> visitor):
  137. visitor(visitor)
  138. {}
  139. typename Base::Variant operator()(const typename Base::Value & element) const
  140. {
  141. return visitor(element);
  142. }
  143. template <typename Type>
  144. typename Base::Variant operator()(Type element) const
  145. {
  146. for (auto & entry : element.expressions)
  147. entry = boost::apply_visitor(*this, entry);
  148. return element;
  149. }
  150. };
  151. /// Minimizing visitor that removes all redundant elements from variant (e.g. AllOf inside another AllOf can be merged safely)
  152. template <typename ContainedClass>
  153. class MinimizingVisitor : public boost::static_visitor<typename ExpressionBase<ContainedClass>::Variant>
  154. {
  155. typedef ExpressionBase<ContainedClass> Base;
  156. public:
  157. typename Base::Variant operator()(const typename Base::Value & element) const
  158. {
  159. return element;
  160. }
  161. template <typename Type>
  162. typename Base::Variant operator()(const Type & element) const
  163. {
  164. Type ret;
  165. for (auto & entryRO : element.expressions)
  166. {
  167. auto entry = boost::apply_visitor(*this, entryRO);
  168. try
  169. {
  170. // copy entries from child of this type
  171. auto sublist = boost::get<Type>(entry).expressions;
  172. std::move(sublist.begin(), sublist.end(), std::back_inserter(ret.expressions));
  173. }
  174. catch (boost::bad_get &)
  175. {
  176. // different type (e.g. allOf vs oneOf) just copy
  177. ret.expressions.push_back(entry);
  178. }
  179. }
  180. for ( auto it = ret.expressions.begin(); it != ret.expressions.end();)
  181. {
  182. if (std::find(ret.expressions.begin(), it, *it) != it)
  183. it = ret.expressions.erase(it); // erase duplicate
  184. else
  185. it++; // goto next
  186. }
  187. return ret;
  188. }
  189. };
  190. /// Json parser for expressions
  191. template <typename ContainedClass>
  192. class Reader
  193. {
  194. typedef ExpressionBase<ContainedClass> Base;
  195. std::function<typename Base::Value(const JsonNode &)> classParser;
  196. typename Base::Variant readExpression(const JsonNode & node)
  197. {
  198. assert(!node.Vector().empty());
  199. std::string type = node.Vector()[0].String();
  200. if (type == "anyOf")
  201. return typename Base::OperatorAny(readVector(node));
  202. if (type == "allOf")
  203. return typename Base::OperatorAll(readVector(node));
  204. if (type == "noneOf")
  205. return typename Base::OperatorNone(readVector(node));
  206. return classParser(node);
  207. }
  208. std::vector<typename Base::Variant> readVector(const JsonNode & node)
  209. {
  210. std::vector<typename Base::Variant> ret;
  211. ret.reserve(node.Vector().size()-1);
  212. for (size_t i=1; i < node.Vector().size(); i++)
  213. ret.push_back(readExpression(node.Vector()[i]));
  214. return ret;
  215. }
  216. public:
  217. Reader(std::function<typename Base::Value(const JsonNode &)> classParser):
  218. classParser(classParser)
  219. {}
  220. typename Base::Variant operator ()(const JsonNode & node)
  221. {
  222. return readExpression(node);
  223. }
  224. };
  225. /// Serializes expression in JSON format. Part of map format.
  226. template <typename ContainedClass>
  227. class Writer : public boost::static_visitor<JsonNode>
  228. {
  229. typedef ExpressionBase<ContainedClass> Base;
  230. std::function<JsonNode(const typename Base::Value &)> classPrinter;
  231. JsonNode printExpressionList(std::string name, const std::vector<typename Base::Variant> & element) const
  232. {
  233. JsonNode ret;
  234. ret.Vector().resize(1);
  235. ret.Vector().back().String() = name;
  236. for (auto & expr : element)
  237. ret.Vector().push_back(boost::apply_visitor(*this, expr));
  238. return ret;
  239. }
  240. public:
  241. Writer(std::function<JsonNode(const typename Base::Value &)> classPrinter):
  242. classPrinter(classPrinter)
  243. {}
  244. JsonNode operator()(const typename Base::OperatorAny & element) const
  245. {
  246. return printExpressionList("anyOf", element.expressions);
  247. }
  248. JsonNode operator()(const typename Base::OperatorAll & element) const
  249. {
  250. return printExpressionList("allOf", element.expressions);
  251. }
  252. JsonNode operator()(const typename Base::OperatorNone & element) const
  253. {
  254. return printExpressionList("noneOf", element.expressions);
  255. }
  256. JsonNode operator()(const typename Base::Value & element) const
  257. {
  258. return classPrinter(element);
  259. }
  260. };
  261. std::string DLL_LINKAGE getTextForOperator(std::string operation);
  262. /// Prints expression in human-readable format
  263. template <typename ContainedClass>
  264. class Printer : public boost::static_visitor<std::string>
  265. {
  266. typedef ExpressionBase<ContainedClass> Base;
  267. std::function<std::string(const typename Base::Value &)> classPrinter;
  268. std::unique_ptr<TestVisitor<ContainedClass>> statusTest;
  269. mutable std::string prefix;
  270. template<typename Operator>
  271. std::string formatString(std::string toFormat, const Operator & expr) const
  272. {
  273. // highlight not fulfilled expressions, if pretty formatting is on
  274. if (statusTest && !(*statusTest)(expr))
  275. return "{" + toFormat + "}";
  276. return toFormat;
  277. }
  278. std::string printExpressionList(const std::vector<typename Base::Variant> & element) const
  279. {
  280. std::string ret;
  281. prefix.push_back('\t');
  282. for (auto & expr : element)
  283. ret += prefix + boost::apply_visitor(*this, expr) + "\n";
  284. prefix.pop_back();
  285. return ret;
  286. }
  287. public:
  288. Printer(std::function<std::string(const typename Base::Value &)> classPrinter):
  289. classPrinter(classPrinter)
  290. {}
  291. Printer(std::function<std::string(const typename Base::Value &)> classPrinter, std::function<bool(const typename Base::Value &)> toBool):
  292. classPrinter(classPrinter),
  293. statusTest(new TestVisitor<ContainedClass>(toBool))
  294. {}
  295. std::string operator()(const typename Base::OperatorAny & element) const
  296. {
  297. return formatString(getTextForOperator("anyOf"), element) + "\n"
  298. + printExpressionList(element.expressions);
  299. }
  300. std::string operator()(const typename Base::OperatorAll & element) const
  301. {
  302. return formatString(getTextForOperator("allOf"), element) + "\n"
  303. + printExpressionList(element.expressions);
  304. }
  305. std::string operator()(const typename Base::OperatorNone & element) const
  306. {
  307. return formatString(getTextForOperator("noneOf"), element) + "\n"
  308. + printExpressionList(element.expressions);
  309. }
  310. std::string operator()(const typename Base::Value & element) const
  311. {
  312. return formatString(classPrinter(element), element);
  313. }
  314. };
  315. }
  316. ///
  317. /// Class for evaluation of logical expressions generated in runtime
  318. ///
  319. template<typename ContainedClass>
  320. class LogicalExpression
  321. {
  322. typedef LogicalExpressionDetail::ExpressionBase<ContainedClass> Base;
  323. public:
  324. /// Type of values used in expressions, same as ContainedClass
  325. typedef typename Base::Value Value;
  326. /// Operators for use in expressions, all include vectors with operands
  327. typedef typename Base::OperatorAny OperatorAny;
  328. typedef typename Base::OperatorAll OperatorAll;
  329. typedef typename Base::OperatorNone OperatorNone;
  330. /// one expression entry
  331. typedef typename Base::Variant Variant;
  332. private:
  333. Variant data;
  334. public:
  335. /// Base constructor
  336. LogicalExpression()
  337. {}
  338. /// Constructor from variant or (implicitly) from Operator* types
  339. LogicalExpression(const Variant & data):
  340. data(data)
  341. {
  342. }
  343. /// Constructor that receives JsonNode as input and function that can parse Value instances
  344. LogicalExpression(const JsonNode & input, std::function<Value(const JsonNode &)> parser)
  345. {
  346. LogicalExpressionDetail::Reader<Value> reader(parser);
  347. LogicalExpression expr(reader(input));
  348. std::swap(data, expr.data);
  349. }
  350. Variant get() const
  351. {
  352. return data;
  353. }
  354. /// Simple visitor that visits all entries in expression
  355. Variant morph(std::function<Variant(const Value &)> morpher) const
  356. {
  357. LogicalExpressionDetail::ForEachVisitor<Value> visitor(morpher);
  358. return boost::apply_visitor(visitor, data);
  359. }
  360. /// Minimizes expression, removing any redundant elements
  361. void minimize()
  362. {
  363. LogicalExpressionDetail::MinimizingVisitor<Value> visitor;
  364. data = boost::apply_visitor(visitor, data);
  365. }
  366. /// calculates if expression evaluates to "true".
  367. /// Note: empty expressions always return true
  368. bool test(std::function<bool(const Value &)> toBool) const
  369. {
  370. LogicalExpressionDetail::TestVisitor<Value> testVisitor(toBool);
  371. return boost::apply_visitor(testVisitor, data);
  372. }
  373. /// generates list of candidates that can be fulfilled by caller (like AI)
  374. std::vector<Value> getFulfillmentCandidates(std::function<bool(const Value &)> toBool) const
  375. {
  376. LogicalExpressionDetail::CandidatesVisitor<Value> candidateVisitor(toBool);
  377. return boost::apply_visitor(candidateVisitor, data);
  378. }
  379. /// Converts expression in human-readable form
  380. /// Second version will try to do some pretty printing using H3 text formatting "{}"
  381. /// to indicate fulfilled components of an expression
  382. std::string toString(std::function<std::string(const Value &)> toStr) const
  383. {
  384. LogicalExpressionDetail::Printer<Value> printVisitor(toStr);
  385. return boost::apply_visitor(printVisitor, data);
  386. }
  387. std::string toString(std::function<std::string(const Value &)> toStr, std::function<bool(const Value &)> toBool) const
  388. {
  389. LogicalExpressionDetail::Printer<Value> printVisitor(toStr, toBool);
  390. return boost::apply_visitor(printVisitor, data);
  391. }
  392. JsonNode toJson(std::function<JsonNode(const Value &)> toJson) const
  393. {
  394. LogicalExpressionDetail::Writer<Value> writeVisitor(toJson);
  395. return boost::apply_visitor(writeVisitor, data);
  396. }
  397. template <typename Handler>
  398. void serialize(Handler & h, const int version)
  399. {
  400. h & data;
  401. }
  402. };