parser.ts 9.7 KB

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