parser.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /**
  2. * Copyright (c) 2017-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  4. * @author Panagiotis Tourlas <panagiot_tourlov@hotmail.com>
  5. *
  6. * @author Koya Sakuma
  7. * This module was taken from MolQL and modified in similar manner as pymol and vmd tranpilers. **/
  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 { properties, structureMap } from './properties';
  13. import { operators } from './operators';
  14. import { keywords } from './keywords';
  15. import { AtomGroupArgs } from '../types';
  16. import { Transpiler } from '../transpiler';
  17. import { OperatorList } from '../types';
  18. // const propertiesDict = h.getPropertyRules(properties);
  19. // const slash = P.MonadicParser.string('/');
  20. // <, <=, =, >=, >, !=, and LIKE
  21. const valueOperators: OperatorList = [
  22. {
  23. '@desc': 'value comparisons',
  24. '@examples': [],
  25. name: '=',
  26. abbr: ['=='],
  27. type: h.binaryLeft,
  28. rule: P.MonadicParser.regexp(/\s*(LIKE|>=|<=|=|!=|>|<)\s*/i, 1),
  29. map: (op, e1, e2) => {
  30. // console.log(op, e1, e2)
  31. let expr;
  32. if (e1 === 'structure') {
  33. expr = B.core.flags.hasAny([B.ammp('secondaryStructureFlags'), structureMap(e2)]);
  34. } else if (e2 === 'structure') {
  35. expr = B.core.flags.hasAny([B.ammp('secondaryStructureFlags'), structureMap(e1)]);
  36. } else if (e1.head === 'core.type.regex') {
  37. expr = B.core.str.match([e1, B.core.type.str([e2])]);
  38. } else if (e2.head === 'core.type.regex') {
  39. expr = B.core.str.match([e2, B.core.type.str([e1])]);
  40. } else if (op.toUpperCase() === 'LIKE') {
  41. if (e1.head) {
  42. expr = B.core.str.match([
  43. B.core.type.regex([`^${e2}$`, 'i']),
  44. B.core.type.str([e1])
  45. ]);
  46. } else {
  47. expr = B.core.str.match([
  48. B.core.type.regex([`^${e1}$`, 'i']),
  49. B.core.type.str([e2])
  50. ]);
  51. }
  52. }
  53. if (!expr) {
  54. if (e1.head) e2 = h.wrapValue(e1, e2);
  55. if (e2.head) e1 = h.wrapValue(e2, e1);
  56. switch (op) {
  57. case '=':
  58. expr = B.core.rel.eq([e1, e2]);
  59. break;
  60. case '!=':
  61. expr = B.core.rel.neq([e1, e2]);
  62. break;
  63. case '>':
  64. expr = B.core.rel.gr([e1, e2]);
  65. break;
  66. case '<':
  67. expr = B.core.rel.lt([e1, e2]);
  68. break;
  69. case '>=':
  70. expr = B.core.rel.gre([e1, e2]);
  71. break;
  72. case '<=':
  73. expr = B.core.rel.lte([e1, e2]);
  74. break;
  75. default: throw new Error(`value operator '${op}' not supported`);
  76. }
  77. }
  78. return B.struct.generator.atomGroups({ 'atom-test': expr });
  79. }
  80. }
  81. ];
  82. function atomExpressionQuery(x: any[]) {
  83. const [resno, inscode, chainname, atomname, altloc] = x[1];
  84. const tests: AtomGroupArgs = {};
  85. if (chainname) {
  86. // should be configurable, there is an option in Jmol to use auth or label
  87. tests['chain-test'] = B.core.rel.eq([B.ammp('auth_asym_id'), chainname]);
  88. }
  89. const resProps = [];
  90. if (resno) resProps.push(B.core.rel.eq([B.ammp('auth_seq_id'), resno]));
  91. if (inscode) resProps.push(B.core.rel.eq([B.ammp('pdbx_PDB_ins_code'), inscode]));
  92. if (resProps.length) tests['residue-test'] = h.andExpr(resProps);
  93. const atomProps = [];
  94. if (atomname) atomProps.push(B.core.rel.eq([B.ammp('auth_atom_id'), atomname]));
  95. if (altloc) atomProps.push(B.core.rel.eq([B.ammp('label_alt_id'), altloc]));
  96. if (atomProps.length) tests['atom-test'] = h.andExpr(atomProps);
  97. return B.struct.generator.atomGroups(tests);
  98. }
  99. const lang = P.MonadicParser.createLanguage({
  100. Integer: () => P.MonadicParser.regexp(/-?[0-9]+/).map(Number).desc('integer'),
  101. Parens: function (r: any) {
  102. return P.MonadicParser.alt(
  103. r.Parens,
  104. r.Operator,
  105. r.Expression
  106. ).wrap(P.MonadicParser.string('('), P.MonadicParser.string(')'));
  107. },
  108. Expression: function (r: any) {
  109. return P.MonadicParser.alt(
  110. r.Keywords,
  111. r.Resno.lookahead(P.MonadicParser.regexp(/\s*(?!(LIKE|>=|<=|!=|[:^%/.=><]))/i)).map((x: any) => B.struct.generator.atomGroups({
  112. 'residue-test': B.core.rel.eq([B.ammp('auth_seq_id'), x])
  113. })),
  114. r.AtomExpression.map(atomExpressionQuery),
  115. r.ValueQuery,
  116. r.Element.map((x: string) => B.struct.generator.atomGroups({
  117. 'atom-test': B.core.rel.eq([B.acp('elementSymbol'), B.struct.type.elementSymbol(x)])
  118. })),
  119. r.Resname.map((x: string) => B.struct.generator.atomGroups({
  120. 'residue-test': B.core.rel.eq([B.ammp('label_comp_id'), x])
  121. })),
  122. );
  123. },
  124. Operator: function (r: any) {
  125. return h.combineOperators(operators, P.MonadicParser.alt(r.Parens, r.Expression));
  126. },
  127. AtomExpression: function (r: any) {
  128. return P.MonadicParser.seq(
  129. P.MonadicParser.lookahead(r.AtomPrefix),
  130. P.MonadicParser.seq(
  131. r.Resno.or(P.MonadicParser.of(null)),
  132. r.Inscode.or(P.MonadicParser.of(null)),
  133. r.Chainname.or(P.MonadicParser.of(null)),
  134. r.Atomname.or(P.MonadicParser.of(null)),
  135. r.Altloc.or(P.MonadicParser.of(null)),
  136. r.Model.or(P.MonadicParser.of(null))
  137. )
  138. );
  139. },
  140. AtomPrefix: () => P.MonadicParser.regexp(/[0-9:^%/.]/).desc('atom-prefix'),
  141. Chainname: () => P.MonadicParser.regexp(/:([A-Za-z]{1,3})/, 1).desc('chainname'),
  142. Model: () => P.MonadicParser.regexp(/\/([0-9]+)/, 1).map(Number).desc('model'),
  143. Element: () => P.MonadicParser.regexp(/_([A-Za-z]{1,3})/, 1).desc('element'),
  144. Atomname: () => P.MonadicParser.regexp(/\.([a-zA-Z0-9]{1,4})/, 1).map(B.atomName).desc('atomname'),
  145. Resname: () => P.MonadicParser.regexp(/[a-zA-Z0-9]{1,4}/).desc('resname'),
  146. Resno: (r: any) => r.Integer.desc('resno'),
  147. Altloc: () => P.MonadicParser.regexp(/%([a-zA-Z0-9])/, 1).desc('altloc'),
  148. Inscode: () => P.MonadicParser.regexp(/\^([a-zA-Z0-9])/, 1).desc('inscode'),
  149. // BracketedResname: function (r) {
  150. // return P.MonadicParser.regexp(/\.([a-zA-Z0-9]{1,4})/, 1)
  151. // .desc('bracketed-resname')
  152. // // [0SD]
  153. // },
  154. // ResnoRange: function (r) {
  155. // return P.MonadicParser.regexp(/\.([\s]){1,3}/, 1)
  156. // .desc('resno-range')
  157. // // 123-200
  158. // // -12--3
  159. // },
  160. Keywords: () => P.MonadicParser.alt(...h.getKeywordRules(keywords)),
  161. Query: function (r: any) {
  162. return P.MonadicParser.alt(
  163. r.Operator,
  164. r.Parens,
  165. r.Expression
  166. ).trim(P.MonadicParser.optWhitespace);
  167. },
  168. Number: function () {
  169. return P.MonadicParser.regexp(/-?(0|[1-9][0-9]*)([.][0-9]+)?([eE][+-]?[0-9]+)?/)
  170. .map(Number)
  171. .desc('number');
  172. },
  173. String: function () {
  174. const w = h.getReservedWords(properties, keywords, operators)
  175. .sort(h.strLenSortFn).map(h.escapeRegExp).join('|');
  176. return P.MonadicParser.alt(
  177. P.MonadicParser.regexp(new RegExp(`(?!(${w}))[A-Z0-9_]+`, 'i')),
  178. P.MonadicParser.regexp(/'((?:[^"\\]|\\.)*)'/, 1),
  179. P.MonadicParser.regexp(/"((?:[^"\\]|\\.)*)"/, 1).map(x => B.core.type.regex([`^${x}$`, 'i']))
  180. );
  181. },
  182. Value: function (r: any) {
  183. return P.MonadicParser.alt(r.Number, r.String);
  184. },
  185. ValueParens: function (r: any) {
  186. return P.MonadicParser.alt(
  187. r.ValueParens,
  188. r.ValueOperator,
  189. r.ValueExpressions
  190. ).wrap(P.MonadicParser.string('('), P.MonadicParser.string(')'));
  191. },
  192. ValuePropertyNames: function () {
  193. return P.MonadicParser.alt(...h.getPropertyNameRules(properties, /LIKE|>=|<=|=|!=|>|<|\)|\s/i));
  194. },
  195. ValueOperator: function (r: any) {
  196. return h.combineOperators(valueOperators, P.MonadicParser.alt(r.ValueParens, r.ValueExpressions));
  197. },
  198. ValueExpressions: function (r: any) {
  199. return P.MonadicParser.alt(
  200. r.Value,
  201. r.ValuePropertyNames
  202. );
  203. },
  204. ValueQuery: function (r: any) {
  205. return P.MonadicParser.alt(
  206. r.ValueOperator.map((x: any) => {
  207. if (x.head) {
  208. if (x.head.startsWith('structure-query.generator')) return x;
  209. } else {
  210. if (typeof x === 'string' && x.length <= 4) {
  211. return B.struct.generator.atomGroups({
  212. 'residue-test': B.core.rel.eq([B.ammp('label_comp_id'), x])
  213. });
  214. }
  215. }
  216. throw new Error(`values must be part of an comparison, value '${x}'`);
  217. })
  218. );
  219. }
  220. });
  221. export const transpiler: Transpiler = str => lang.Query.tryParse(str);