parser.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /**
  2. * Copyright (c) 2017-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. * @author Koya Sakuma < koya.sakuma.work@gmail.com>
  4. * Adapted from MolQL project
  5. **/
  6. import * as P from '../../../mol-util/monadic-parser';
  7. import * as h from '../helper';
  8. import { MolScriptBuilder } from '../../../mol-script/language/builder';
  9. const B = MolScriptBuilder;
  10. import { properties, structureMap } from './properties';
  11. import { operators } from './operators';
  12. import { keywords } from './keywords';
  13. import { AtomGroupArgs } from '../types';
  14. import { Transpiler } from '../transpiler';
  15. import { OperatorList } from '../types';
  16. // <, <=, =, >=, >, !=, and LIKE
  17. const valueOperators: OperatorList = [
  18. {
  19. '@desc': 'value comparisons',
  20. '@examples': [],
  21. name: '=',
  22. abbr: ['=='],
  23. type: h.binaryLeft,
  24. rule: P.MonadicParser.regexp(/\s*(LIKE|>=|<=|=|!=|>|<)\s*/i, 1),
  25. map: (op, e1, e2) => {
  26. let expr;
  27. if (e1 === 'structure') {
  28. expr = B.core.flags.hasAny([B.ammp('secondaryStructureFlags'), structureMap(e2)]);
  29. } else if (e2 === 'structure') {
  30. expr = B.core.flags.hasAny([B.ammp('secondaryStructureFlags'), structureMap(e1)]);
  31. } else if (e1.head !== undefined) {
  32. if (e1.head.name === 'core.type.regex') {
  33. expr = B.core.str.match([e1, B.core.type.str([e2])]);
  34. }
  35. } else if (e2.head !== undefined) {
  36. if (e2.head.name === 'core.type.regex') {
  37. expr = B.core.str.match([e2, B.core.type.str([e1])]);
  38. }
  39. } else if (op.toUpperCase() === 'LIKE') {
  40. if (e1.head) {
  41. expr = B.core.str.match([
  42. B.core.type.regex([`^${e2}$`, 'i']),
  43. B.core.type.str([e1])
  44. ]);
  45. } else {
  46. expr = B.core.str.match([
  47. B.core.type.regex([`^${e1}$`, 'i']),
  48. B.core.type.str([e2])
  49. ]);
  50. }
  51. }
  52. if (!expr) {
  53. if (e1.head) e2 = h.wrapValue(e1, e2);
  54. if (e2.head) e1 = h.wrapValue(e2, e1);
  55. switch (op) {
  56. case '=':
  57. expr = B.core.rel.eq([e1, e2]);
  58. break;
  59. case '!=':
  60. expr = B.core.rel.neq([e1, e2]);
  61. break;
  62. case '>':
  63. expr = B.core.rel.gr([e1, e2]);
  64. break;
  65. case '<':
  66. expr = B.core.rel.lt([e1, e2]);
  67. break;
  68. case '>=':
  69. expr = B.core.rel.gre([e1, e2]);
  70. break;
  71. case '<=':
  72. expr = B.core.rel.lte([e1, e2]);
  73. break;
  74. default: throw new Error(`value operator '${op}' not supported`);
  75. }
  76. }
  77. return B.struct.generator.atomGroups({ 'atom-test': expr });
  78. }
  79. }
  80. ];
  81. function atomExpressionQuery(x: any[]) {
  82. const [resno, inscode, chainname, atomname, altloc] = x[1];
  83. const tests: AtomGroupArgs = {};
  84. if (chainname) {
  85. // should be configurable, there is an option in Jmol to use auth or label
  86. tests['chain-test'] = B.core.rel.eq([B.ammp('auth_asym_id'), chainname]);
  87. }
  88. const resProps = [];
  89. if (resno) resProps.push(B.core.rel.eq([B.ammp('auth_seq_id'), resno]));
  90. if (inscode) resProps.push(B.core.rel.eq([B.ammp('pdbx_PDB_ins_code'), inscode]));
  91. if (resProps.length) tests['residue-test'] = h.andExpr(resProps);
  92. const atomProps = [];
  93. if (atomname) atomProps.push(B.core.rel.eq([B.ammp('auth_atom_id'), atomname]));
  94. if (altloc) atomProps.push(B.core.rel.eq([B.ammp('label_alt_id'), altloc]));
  95. if (atomProps.length) tests['atom-test'] = h.andExpr(atomProps);
  96. return B.struct.generator.atomGroups(tests);
  97. }
  98. const lang = P.MonadicParser.createLanguage({
  99. Integer: () => P.MonadicParser.regexp(/-?[0-9]+/).map(Number).desc('integer'),
  100. Parens: function (r: any) {
  101. return P.MonadicParser.alt(
  102. r.Parens,
  103. r.Operator,
  104. r.Expression
  105. ).wrap(P.MonadicParser.string('('), P.MonadicParser.string(')'));
  106. },
  107. Expression: function (r: any) {
  108. return P.MonadicParser.alt(
  109. r.Keywords,
  110. r.Resno.lookahead(P.MonadicParser.regexp(/\s*(?!(LIKE|>=|<=|!=|[:^%/.=><]))/i)).map((x: any) => B.struct.generator.atomGroups({
  111. 'residue-test': B.core.rel.eq([B.ammp('auth_seq_id'), x])
  112. })),
  113. r.AtomExpression.map(atomExpressionQuery),
  114. r.ValueQuery,
  115. r.Element.map((x: string) => B.struct.generator.atomGroups({
  116. 'atom-test': B.core.rel.eq([B.acp('elementSymbol'), B.struct.type.elementSymbol(x)])
  117. })),
  118. r.Resname.map((x: string) => B.struct.generator.atomGroups({
  119. 'residue-test': B.core.rel.eq([B.ammp('label_comp_id'), x])
  120. })),
  121. );
  122. },
  123. Operator: function (r: any) {
  124. return h.combineOperators(operators, P.MonadicParser.alt(r.Parens, r.Expression));
  125. },
  126. AtomExpression: function (r: any) {
  127. return P.MonadicParser.seq(
  128. P.MonadicParser.lookahead(r.AtomPrefix),
  129. P.MonadicParser.seq(
  130. r.Resno.or(P.MonadicParser.of(null)),
  131. r.Inscode.or(P.MonadicParser.of(null)),
  132. r.Chainname.or(P.MonadicParser.of(null)),
  133. r.Atomname.or(P.MonadicParser.of(null)),
  134. r.Altloc.or(P.MonadicParser.of(null)),
  135. r.Model.or(P.MonadicParser.of(null))
  136. )
  137. );
  138. },
  139. AtomPrefix: () => P.MonadicParser.regexp(/[0-9:^%/.]/).desc('atom-prefix'),
  140. Chainname: () => P.MonadicParser.regexp(/:([A-Za-z]{1,3})/, 1).desc('chainname'),
  141. Model: () => P.MonadicParser.regexp(/\/([0-9]+)/, 1).map(Number).desc('model'),
  142. Element: () => P.MonadicParser.regexp(/_([A-Za-z]{1,3})/, 1).desc('element'),
  143. Atomname: () => P.MonadicParser.regexp(/\.([a-zA-Z0-9]{1,4})/, 1).map(B.atomName).desc('atomname'),
  144. Resname: () => P.MonadicParser.regexp(/[a-zA-Z0-9]{1,4}/).desc('resname'),
  145. Resno: (r: any) => r.Integer.desc('resno'),
  146. Altloc: () => P.MonadicParser.regexp(/%([a-zA-Z0-9])/, 1).desc('altloc'),
  147. Inscode: () => P.MonadicParser.regexp(/\^([a-zA-Z0-9])/, 1).desc('inscode'),
  148. // TODO: Support bracketed resname and resno range.
  149. // BracketedResname: function (r) {
  150. // return P.regex(/\.([a-zA-Z0-9]{1,4})/, 1)
  151. // .desc('bracketed-resname')
  152. // // [0SD]
  153. // },
  154. // ResnoRange: function (r) {
  155. // return P.regex(/\.([\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.name.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);