parser.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /**
  2. * Copyright (c) 2017-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. * @author Panagiotis Tourlas <panagiot_tourlov@hotmail.com>
  6. * @author Koya Sakuma
  7. */
  8. import * as P from '../../../mol-util/monadic-parser';
  9. import * as h from '../helper';
  10. import { MolScriptBuilder } from '../../../mol-script/language/builder';
  11. const B = MolScriptBuilder;
  12. import { sstrucMap, sstrucDict, properties } from './properties';
  13. import { operators } from './operators';
  14. import { keywords } from './keywords';
  15. import { functions } from './functions';
  16. import { OperatorList } from '../types';
  17. import { Transpiler } from '../transpiler';
  18. // const propertiesDict = h.getPropertyRules(properties)
  19. // <, <=, = or ==, >=, >, and !=
  20. // lt, le, eq, ge, gt, and ne, =~
  21. const valueOperators: OperatorList = [
  22. {
  23. '@desc': 'multiplication, division',
  24. '@examples': [],
  25. name: 'mul-div',
  26. type: h.binaryLeft,
  27. rule: P.MonadicParser.regexp(/\s*(\*|\/)\s*/, 1),
  28. map: (op, e1, e2) => {
  29. switch (op) {
  30. case '*': return B.core.math.mult([e1, e2]);
  31. case '/': return B.core.math.div([e1, e2]);
  32. default: throw new Error(`value operator '${op}' not supported`);
  33. }
  34. }
  35. },
  36. {
  37. '@desc': 'addition, substraction',
  38. '@examples': [],
  39. name: 'add-sub',
  40. type: h.binaryLeft,
  41. rule: P.MonadicParser.regexp(/\s*(-|\+)\s*/, 1),
  42. map: (op, e1, e2) => {
  43. switch (op) {
  44. case '-': return B.core.math.sub([e1, e2]);
  45. case '+': return B.core.math.add([e1, e2]);
  46. default: throw new Error(`value operator '${op}' not supported`);
  47. }
  48. }
  49. },
  50. {
  51. '@desc': 'value comparisons',
  52. '@examples': [],
  53. name: 'comparison',
  54. type: h.binaryLeft,
  55. rule: P.MonadicParser.alt(P.MonadicParser.regexp(/\s*(=~|==|>=|<=|=|!=|>|<)\s*/, 1), P.MonadicParser.whitespace.result('=')),
  56. map: (op, e1, e2) => {
  57. // console.log(op, e1, e2)
  58. let expr;
  59. if (e1.head.name === 'structure-query.atom-property.macromolecular.secondary-structure-flags') {
  60. expr = B.core.flags.hasAny([e1, sstrucMap(e2)]);
  61. } else if (e2.head.name === 'structure-query.atom-property.macromolecular.secondary-structure-flags') {
  62. expr = B.core.flags.hasAny([e2, sstrucMap(e1)]);
  63. } else if (e1.head.name === 'core.type.regex') {
  64. expr = B.core.str.match([e1, B.core.type.str([e2])]);
  65. } else if (e2.head.name === 'core.type.regex') {
  66. expr = B.core.str.match([e2, B.core.type.str([e1])]);
  67. } else if (op === '=~') {
  68. if (e1.head.name) {
  69. expr = B.core.str.match([
  70. B.core.type.regex([`^${e2}$`, 'i']),
  71. B.core.type.str([e1])
  72. ]);
  73. } else {
  74. expr = B.core.str.match([
  75. B.core.type.regex([`^${e1}$`, 'i']),
  76. B.core.type.str([e2])
  77. ]);
  78. }
  79. }
  80. if (!expr) {
  81. if (e1.head.name) e2 = h.wrapValue(e1, e2);
  82. if (e2.head.name) e1 = h.wrapValue(e2, e1);
  83. switch (op) {
  84. case '=':
  85. case '==':
  86. expr = B.core.rel.eq([e1, e2]);
  87. break;
  88. case '!=':
  89. expr = B.core.rel.neq([e1, e2]);
  90. break;
  91. case '>':
  92. expr = B.core.rel.gr([e1, e2]);
  93. break;
  94. case '<':
  95. expr = B.core.rel.lt([e1, e2]);
  96. break;
  97. case '>=':
  98. expr = B.core.rel.gre([e1, e2]);
  99. break;
  100. case '<=':
  101. expr = B.core.rel.lte([e1, e2]);
  102. break;
  103. default: throw new Error(`value operator '${op}' not supported`);
  104. }
  105. }
  106. return B.struct.generator.atomGroups({ 'atom-test': expr });
  107. }
  108. }
  109. ];
  110. const lang = P.MonadicParser.createLanguage({
  111. Parens: function (r: any) {
  112. return P.MonadicParser.alt(
  113. r.Parens,
  114. r.Operator,
  115. r.Expression
  116. ).wrap(P.MonadicParser.string('('), P.MonadicParser.string(')'));
  117. },
  118. Expression: function (r: any) {
  119. return P.MonadicParser.alt(
  120. r.RangeListProperty,
  121. r.NamedAtomProperties,
  122. r.ValueQuery,
  123. r.Keywords,
  124. );
  125. },
  126. NamedAtomProperties: function () {
  127. return P.MonadicParser.alt(...h.getNamedPropertyRules(properties));
  128. },
  129. Keywords: () => P.MonadicParser.alt(...h.getKeywordRules(keywords)),
  130. ValueRange: function (r: any) {
  131. return P.MonadicParser.seq(
  132. r.Value
  133. .skip(P.MonadicParser.regexp(/\s+TO\s+/i)),
  134. r.Value
  135. ).map(x => ({ range: x }));
  136. },
  137. RangeListProperty: function (r: any) {
  138. return P.MonadicParser.seq(
  139. P.MonadicParser.alt(...h.getPropertyNameRules(properties, /\s/))
  140. .skip(P.MonadicParser.whitespace),
  141. P.MonadicParser.alt(
  142. r.ValueRange,
  143. r.Value
  144. ).sepBy1(P.MonadicParser.whitespace)
  145. ).map(x => {
  146. const [property, values] = x;
  147. const listValues: (string | number)[] = [];
  148. const rangeValues: any[] = [];
  149. values.forEach((v: any) => {
  150. if (v.range) {
  151. rangeValues.push(
  152. B.core.rel.inRange([property, v.range[0], v.range[1]])
  153. );
  154. } else {
  155. listValues.push(h.wrapValue(property, v, sstrucDict));
  156. }
  157. });
  158. const rangeTest = h.orExpr(rangeValues);
  159. const listTest = h.valuesTest(property, listValues);
  160. let test;
  161. if (rangeTest && listTest) {
  162. test = B.core.logic.or([rangeTest, listTest]);
  163. } else {
  164. test = rangeTest ? rangeTest : listTest;
  165. }
  166. return B.struct.generator.atomGroups({ [h.testLevel(property)]: test });
  167. // h.testLevel is not working for unknown reason, so relaced it by hardcoded 'atom-test'
  168. // console.log(h.testLevel(property));
  169. // return B.struct.generator.atomGroups({ 'atom-test': test });
  170. });
  171. },
  172. Operator: function (r: any) {
  173. return h.combineOperators(operators, P.MonadicParser.alt(r.Parens, r.Expression, r.ValueQuery));
  174. },
  175. Query: function (r: any) {
  176. return P.MonadicParser.alt(
  177. r.Operator,
  178. r.Parens,
  179. r.Expression
  180. ).trim(P.MonadicParser.optWhitespace);
  181. },
  182. Number: function () {
  183. return P.MonadicParser.regexp(/-?(0|[1-9][0-9]*)([.][0-9]+)?([eE][+-]?[0-9]+)?/)
  184. .map(Number)
  185. .desc('number');
  186. },
  187. String: function () {
  188. const w = h.getReservedWords(properties, keywords, operators)
  189. .sort(h.strLenSortFn).map(h.escapeRegExp).join('|');
  190. return P.MonadicParser.alt(
  191. P.MonadicParser.regexp(new RegExp(`(?!(${w}))[A-Z0-9_]+`, 'i')),
  192. P.MonadicParser.regexp(/'((?:[^"\\]|\\.)*)'/, 1),
  193. P.MonadicParser.regexp(/"((?:[^"\\]|\\.)*)"/, 1).map((x: any) => B.core.type.regex([`^${x}$`, 'i']))
  194. ).desc('string');
  195. },
  196. Value: function (r: any) {
  197. return P.MonadicParser.alt(r.Number, r.String);
  198. },
  199. ValueParens: function (r: any) {
  200. return P.MonadicParser.alt(
  201. r.ValueParens,
  202. r.ValueOperator,
  203. r.ValueExpressions
  204. ).wrap(P.MonadicParser.string('('), P.MonadicParser.string(')'));
  205. },
  206. ValuePropertyNames: function () {
  207. return P.MonadicParser.alt(...h.getPropertyNameRules(properties, /=~|==|>=|<=|=|!=|>|<|\)|\s|\+|-|\*|\//i));
  208. },
  209. ValueOperator: function (r: any) {
  210. return h.combineOperators(valueOperators, P.MonadicParser.alt(r.ValueParens, r.ValueExpressions));
  211. },
  212. ValueExpressions: function (r: any) {
  213. return P.MonadicParser.alt(
  214. r.ValueFunctions,
  215. r.Value,
  216. r.ValuePropertyNames
  217. );
  218. },
  219. ValueFunctions: function (r: any) {
  220. return P.MonadicParser.alt(...h.getFunctionRules(functions, r.ValueOperator));
  221. },
  222. ValueQuery: function (r: any) {
  223. return P.MonadicParser.alt(
  224. r.ValueOperator.map((x: any) => {
  225. // if (!x.head || x.head.startsWith('core.math') || x.head.startsWith('structure-query.atom-property')) {
  226. if (!x.head.name || !x.head.name.startsWith('structure-query.generator')) {
  227. throw new Error(`values must be part of an comparison, value '${x}'`);
  228. } else {
  229. return x as any;
  230. }
  231. })
  232. );
  233. }
  234. });
  235. export const transpiler: Transpiler = str => lang.Query.tryParse(str);