C++ classes for selection parser symbol table.
[alexxy/gromacs.git] / src / gromacs / selection / selmethod.cpp
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11  * Copyright (c) 2001-2009, The GROMACS development team,
12  * check out http://www.gromacs.org for more information.
13
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * If you want to redistribute modifications, please consider that
20  * scientific software is very special. Version control is crucial -
21  * bugs must be traceable. We will be happy to consider code for
22  * inclusion in the official distribution, but derived work must not
23  * be called official GROMACS. Details are found in the README & COPYING
24  * files - if they are missing, get the official version at www.gromacs.org.
25  *
26  * To help us fund GROMACS development, we humbly ask that you cite
27  * the papers on the package - you can find them in the top README file.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \internal \file
32  * \brief
33  * Implements functions in selmethod.h.
34  *
35  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
36  * \ingroup module_selection
37  */
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41
42 #include <ctype.h>
43 #include <stdarg.h>
44
45 #include "gromacs/legacyheaders/macros.h"
46 #include "gromacs/legacyheaders/string2.h"
47
48 #include "gromacs/selection/selmethod.h"
49 #include "gromacs/utility/exceptions.h"
50
51 #include "symrec.h"
52
53 /*
54  * These global variables cannot be const because gmx_ana_selmethod_register()
55  * modifies them to set some defaults. This is a small price to pay for the
56  * convenience of not having to remember exactly how the selection compiler
57  * expects the structures to be filled, and even more so if the expectations
58  * change. Also, even if the gmx_ana_selmethod_t structures were made const,
59  * the parameters could not be without typecasts somewhere, because the param
60  * field in gmx_ana_selmethod_t cannot be declared const.
61  *
62  * Even though the variables may be modified, this should be thread-safe as
63  * modifications are done only in gmx_ana_selmethod_register(), and it should
64  * work even if called more than once for the same structure, and even if
65  * called concurrently from multiple threads (as long as the selection
66  * collection is not the same).
67  *
68  * All of these problems should go away if/when the selection methods are
69  * implemented as C++ classes.
70  */
71
72 /* From sm_com.c */
73 extern gmx_ana_selmethod_t sm_cog;
74 extern gmx_ana_selmethod_t sm_com;
75 /* From sm_simple.c */
76 extern gmx_ana_selmethod_t sm_all;
77 extern gmx_ana_selmethod_t sm_none;
78 extern gmx_ana_selmethod_t sm_atomnr;
79 extern gmx_ana_selmethod_t sm_resnr;
80 extern gmx_ana_selmethod_t sm_resindex;
81 extern gmx_ana_selmethod_t sm_molindex;
82 extern gmx_ana_selmethod_t sm_atomname;
83 extern gmx_ana_selmethod_t sm_atomtype;
84 extern gmx_ana_selmethod_t sm_resname;
85 extern gmx_ana_selmethod_t sm_insertcode;
86 extern gmx_ana_selmethod_t sm_chain;
87 extern gmx_ana_selmethod_t sm_mass;
88 extern gmx_ana_selmethod_t sm_charge;
89 extern gmx_ana_selmethod_t sm_altloc;
90 extern gmx_ana_selmethod_t sm_occupancy;
91 extern gmx_ana_selmethod_t sm_betafactor;
92 extern gmx_ana_selmethod_t sm_x;
93 extern gmx_ana_selmethod_t sm_y;
94 extern gmx_ana_selmethod_t sm_z;
95 /* From sm_distance.c */
96 extern gmx_ana_selmethod_t sm_distance;
97 extern gmx_ana_selmethod_t sm_mindistance;
98 extern gmx_ana_selmethod_t sm_within;
99 /* From sm_insolidangle.c */
100 extern gmx_ana_selmethod_t sm_insolidangle;
101 /* From sm_same.c */
102 extern gmx_ana_selmethod_t sm_same;
103
104 /* From sm_merge.c */
105 extern gmx_ana_selmethod_t sm_merge;
106 extern gmx_ana_selmethod_t sm_plus;
107 /* From sm_permute.c */
108 extern gmx_ana_selmethod_t sm_permute;
109
110 /*! \internal \brief
111  * Helper structure for defining selection methods.
112  */
113 typedef struct {
114     /*! \brief
115      * Name to register the method under.
116      *
117      * If NULL, use the actual name of the method.
118      * This field is used for defining synonyms.
119      */
120     const char            *name;
121     /** Method data structure to register. */
122     gmx_ana_selmethod_t   *method;
123 } t_register_method;
124
125 /** Array of selection methods defined in the library. */
126 static const t_register_method smtable_def[] = {
127     {NULL,         &sm_cog},
128     {NULL,         &sm_com},
129
130     {NULL,         &sm_all},
131     {NULL,         &sm_none},
132     {NULL,         &sm_atomnr},
133     {NULL,         &sm_resnr},
134     {"resid",      &sm_resnr},
135     {NULL,         &sm_resindex},
136     {"residue",    &sm_resindex},
137     {NULL,         &sm_molindex},
138     {"mol",        &sm_molindex},
139     {"molecule",   &sm_molindex},
140     {NULL,         &sm_atomname},
141     {NULL,         &sm_atomtype},
142     {NULL,         &sm_resname},
143     {NULL,         &sm_insertcode},
144     {NULL,         &sm_chain},
145     {NULL,         &sm_mass},
146     {NULL,         &sm_charge},
147     {NULL,         &sm_altloc},
148     {NULL,         &sm_occupancy},
149     {NULL,         &sm_betafactor},
150     {NULL,         &sm_x},
151     {NULL,         &sm_y},
152     {NULL,         &sm_z},
153
154     {NULL,         &sm_distance},
155     {NULL,         &sm_mindistance},
156     {NULL,         &sm_within},
157     {NULL,         &sm_insolidangle},
158     {NULL,         &sm_same},
159
160     {NULL,         &sm_merge},
161     {NULL,         &sm_plus},
162     {NULL,         &sm_permute},
163 };
164
165 /*! \brief
166  * Convenience function for reporting errors found in selection methods.
167  */
168 static void
169 report_error(FILE *fp, const char *name, const char *fmt, ...)
170 {
171     va_list ap;
172     va_start(ap, fmt);
173     if (fp)
174     {
175         fprintf(fp, "selection method '%s': ", name);
176         vfprintf(fp, fmt, ap);
177         fprintf(fp, "\n");
178     }
179     va_end(ap);
180 }
181
182 /*! \brief
183  * Convenience function for reporting errors found in selection method parameters.
184  */
185 static void
186 report_param_error(FILE *fp, const char *mname, const char *pname,
187                    const char *fmt, ...)
188 {
189     va_list ap;
190     va_start(ap, fmt);
191     if (fp)
192     {
193         fprintf(fp, "selection method '%s': parameter '%s': ", mname, pname);
194         vfprintf(fp, fmt, ap);
195         fprintf(fp, "\n");
196     }
197     va_end(ap);
198 }
199
200 /*! \brief
201  * Checks the validity of parameters.
202  *
203  * \param[in]     fp      File handle to use for diagnostic messages
204  *   (can be NULL).
205  * \param[in]     name    Name of the method (used for error messages).
206  * \param[in]     nparams Number of parameters in \p param.
207  * \param[in,out] param   Parameter array
208  *   (only the \c flags field of boolean parameters may be modified).
209  * \param[in]     symtab  Symbol table (used for checking overlaps).
210  * \returns       true if there are no problems with the parameters,
211  *   false otherwise.
212  *
213  * This function performs some checks common to both check_method() and
214  * check_modifier().
215  * The purpose of these checks is to ensure that the selection parser does not
216  * need to check for the validity of the parameters at each turn, and to
217  * report programming errors as early as possible.
218  * If you remove a check, make sure that the parameter parser can handle the
219  * resulting parameters.
220  */
221 static bool
222 check_params(FILE *fp, const char *name, int nparams, gmx_ana_selparam_t param[],
223              const gmx::SelectionParserSymbolTable &symtab)
224 {
225     bool              bOk = true;
226     int               i, j;
227
228     if (nparams > 0 && !param)
229     {
230         report_error(fp, name, "error: missing parameter data");
231         return false;
232     }
233     if (nparams == 0 && param)
234     {
235         report_error(fp, name, "warning: parameter data unused because nparams=0");
236     }
237     /* Check each parameter */
238     for (i = 0; i < nparams; ++i)
239     {
240         /* Check that there is at most one NULL name, in the beginning */
241         if (param[i].name == NULL && i > 0)
242         {
243             report_error(fp, name, "error: NULL parameter should be the first one");
244             bOk = false;
245             continue;
246         }
247         /* Check for duplicates */
248         for (j = 0; j < i; ++j)
249         {
250             if (param[j].name == NULL)
251             {
252                 continue;
253             }
254             if (!gmx_strcasecmp(param[i].name, param[j].name))
255             {
256                 report_error(fp, name, "error: duplicate parameter name '%s'", param[i].name);
257                 bOk = false;
258                 break;
259             }
260         }
261         /* Check flags */
262         if (param[i].flags & SPAR_SET)
263         {
264             report_param_error(fp, name, param[i].name, "warning: flag SPAR_SET is set");
265             param[i].flags &= ~SPAR_SET;
266         }
267         if (param[i].flags & SPAR_RANGES)
268         {
269             if (param[i].val.type != INT_VALUE && param[i].val.type != REAL_VALUE)
270             {
271                 report_param_error(fp, name, param[i].name, "error: SPAR_RANGES cannot be set for a non-numeric parameter");
272                 bOk = false;
273             }
274             if (param[i].flags & SPAR_DYNAMIC)
275             {
276                 report_param_error(fp, name, param[i].name, "warning: SPAR_DYNAMIC does not have effect with SPAR_RANGES");
277                 param[i].flags &= ~SPAR_DYNAMIC;
278             }
279             if (!(param[i].flags & SPAR_VARNUM) && param[i].val.nr != 1)
280             {
281                 report_param_error(fp, name, param[i].name, "error: range should take either one or an arbitrary number of values");
282                 bOk = false;
283             }
284             if (param[i].flags & SPAR_ATOMVAL)
285             {
286                 report_param_error(fp, name, param[i].name, "error: SPAR_RANGES and SPAR_ATOMVAL both set");
287                 bOk = false;
288             }
289         }
290         if ((param[i].flags & SPAR_VARNUM) && (param[i].flags & SPAR_ATOMVAL))
291         {
292             report_param_error(fp, name, param[i].name, "error: SPAR_VARNUM and SPAR_ATOMVAL both set");
293             bOk = false;
294         }
295         if (param[i].flags & SPAR_ENUMVAL)
296         {
297             if (param[i].val.type != STR_VALUE)
298             {
299                 report_param_error(fp, name, param[i].name, "error: SPAR_ENUMVAL can only be set for string parameters");
300                 bOk = false;
301             }
302             if (param[i].val.nr != 1)
303             {
304                 report_param_error(fp, name, param[i].name, "error: SPAR_ENUMVAL parameters should take exactly one value");
305                 bOk = false;
306             }
307             if (param[i].flags & (SPAR_DYNAMIC | SPAR_VARNUM | SPAR_ATOMVAL))
308             {
309                 report_param_error(fp, name, param[i].name, "error: only SPAR_OPTIONAL supported with SPAR_ENUMVAL");
310                 bOk = false;
311             }
312         }
313         /* Check boolean parameters */
314         if (param[i].val.type == NO_VALUE)
315         {
316             if (param[i].val.nr != 0)
317             {
318                 report_param_error(fp, name, param[i].name, "error: number of values should be zero for boolean parameters");
319                 bOk = false;
320             }
321             /* The boolean parameters should always be optional, so set the
322              * flag for convenience. */
323             param[i].flags |= SPAR_OPTIONAL;
324             /* Any other flags should not be specified */
325             if (param[i].flags & ~SPAR_OPTIONAL)
326             {
327                 report_param_error(fp, name, param[i].name, "error: boolean parameter should not have any flags set");
328                 bOk = false;
329             }
330         }
331         /* Check val.nr */
332         if (param[i].flags & (SPAR_VARNUM | SPAR_ATOMVAL))
333         {
334             if (param[i].val.nr != -1)
335             {
336                 report_param_error(fp, name, param[i].name, "warning: val.nr is not -1 although SPAR_VARNUM/SPAR_ATOMVAL is set");
337             }
338             param[i].val.nr = -1;
339         }
340         else if (param[i].val.type != NO_VALUE)
341         {
342             if (param[i].val.nr <= 0)
343             {
344                 report_param_error(fp, name, param[i].name, "error: val.nr <= 0");
345                 bOk = false;
346             }
347         }
348         /* Check that the value pointer is NULL */
349         if (param[i].nvalptr != NULL)
350         {
351             report_param_error(fp, name, param[i].name, "warning: nvalptr is set");
352         }
353         if (param[i].val.u.ptr != NULL && !(param[i].flags & SPAR_ENUMVAL))
354         {
355             report_param_error(fp, name, param[i].name, "warning: value pointer is set");
356         }
357         /* Check that the name contains only valid characters */
358         if (param[i].name == NULL)
359         {
360             continue;
361         }
362         if (!isalpha(param[i].name[0]))
363         {
364             report_param_error(fp, name, param[i].name, "error: name does not begin with a letter");
365             bOk = false;
366             continue;
367         }
368         for (j = 1; param[i].name[j] != 0; ++j)
369         {
370             if (param[i].name[j] != '_' && !isalnum(param[i].name[j]))
371             {
372                 report_param_error(fp, name, param[i].name, "error: name contains non-alphanumeric characters");
373                 bOk = false;
374                 break;
375             }
376         }
377         if (param[i].name[j] != 0)
378         {
379             continue;
380         }
381         /* Check that the name does not conflict with a method */
382         if (symtab.findSymbol(param[i].name, true))
383         {
384             report_param_error(fp, name, param[i].name, "error: name conflicts with another method or a keyword");
385             bOk = false;
386         }
387     } /* End of parameter loop */
388     /* Check parameters of existing methods */
389     gmx::SelectionParserSymbolIterator symbol
390         = symtab.beginIterator(gmx::SelectionParserSymbol::MethodSymbol);
391     while (symbol != symtab.endIterator())
392     {
393         gmx_ana_selmethod_t *method = symbol->methodValue();
394         gmx_ana_selparam_t  *param =
395             gmx_ana_selmethod_find_param(name, method);
396         if (param)
397         {
398             report_param_error(fp, method->name, param->name, "error: name conflicts with another method or a keyword");
399             bOk = false;
400         }
401         ++symbol;
402     }
403     return bOk;
404 }
405
406 /*! \brief
407  * Checks the validity of selection method callback functions.
408  *
409  * \param[in] fp        File handle to use for diagnostic messages
410  *   (can be NULL).
411  * \param[in] method    The method to check.
412  * \returns   true if there are no problems, false otherwise.
413  *
414  * This function performs some checks common to both check_method() and
415  * check_modifier().
416  * This function checks that all the required callbacks are defined, i.e.,
417  * not NULL, to find programming errors.
418  */
419 static bool
420 check_callbacks(FILE *fp, gmx_ana_selmethod_t *method)
421 {
422     bool         bOk = true;
423     bool         bNeedInit;
424     int          i;
425
426     /* Make some checks on init_data and free */
427     if (method->nparams > 0 && !method->init_data)
428     {
429         report_error(fp, method->name, "error: init_data should be provided because the method has parameters");
430         bOk = false;
431     }
432     if (method->free && !method->init_data)
433     {
434         report_error(fp, method->name, "warning: free is not used because of missing init_data");
435     }
436     /* Check presence of outinit for position-valued methods */
437     if (method->type == POS_VALUE && !method->outinit)
438     {
439         report_error(fp, method->name, "error: outinit should be provided because the method has POS_VALUE");
440         bOk = false;
441     }
442     /* Warn of dynamic callbacks in static methods */
443     if (!(method->flags & SMETH_MODIFIER))
444     {
445         if (method->pupdate && !(method->flags & SMETH_DYNAMIC))
446         {
447             report_error(fp, method->name, "warning: pupdate not used because the method is static");
448             method->pupdate = NULL;
449         }
450     }
451     /* Check that there is an evaluation function */
452     if (method->type != NO_VALUE && !method->update && !method->pupdate)
453     {
454         report_error(fp, method->name, "error: evaluation function missing");
455         bOk = false;
456     }
457     /* Loop through the parameters to determine if initialization callbacks
458      * are needed. */
459     bNeedInit = false;
460     for (i = 0; i < method->nparams; ++i)
461     {
462         if (method->param[i].val.type != POS_VALUE
463             && (method->param[i].flags & (SPAR_VARNUM | SPAR_ATOMVAL)))
464         {
465             bNeedInit = true;
466         }
467     }
468     /* Check that the callbacks required by the parameters are present */
469     if (bNeedInit && !method->init)
470     {
471         report_error(fp, method->name, "error: init should be provided");
472         bOk = false;
473     }
474     return bOk;
475 }
476
477 /*!
478  * Checks the validity of a selection method.
479  *
480  * \param[in]     fp     File handle to use for diagnostic messages
481  *   (can be NULL).
482  * \param[in,out] method Method to check.
483  * \param[in]     symtab Symbol table (used for checking overlaps).
484  *
485  * Checks the validity of the given selection method data structure
486  * that does not have \ref SMETH_MODIFIER set.
487  * If you remove a check, please make sure that the selection parser,
488  * compiler, and evaluation functions can deal with the method.
489  */
490 static bool
491 check_method(FILE *fp, gmx_ana_selmethod_t *method,
492              const gmx::SelectionParserSymbolTable &symtab)
493 {
494     bool         bOk = true;
495
496     /* Check the type */
497     if (method->type == NO_VALUE)
498     {
499         report_error(fp, method->name, "error: no value type specified");
500         bOk = false;
501     }
502     if (method->type == STR_VALUE && method->nparams > 0)
503     {
504         report_error(fp, method->name, "error: evaluates to a string but is not a keyword");
505         bOk = false;
506     }
507     /* Check flags */
508     if (method->type == GROUP_VALUE)
509     {
510         /* Group methods should always have SMETH_SINGLEVAL,
511          * so set it for convenience. */
512         method->flags |= SMETH_SINGLEVAL;
513         /* Check that conflicting flags are not present. */
514         if (method->flags & SMETH_VARNUMVAL)
515         {
516             report_error(fp, method->name, "error: SMETH_VARNUMVAL cannot be set for group-valued methods");
517             bOk = false;
518         }
519     }
520     else
521     {
522         if ((method->flags & SMETH_SINGLEVAL)
523             && (method->flags & SMETH_VARNUMVAL))
524         {
525             report_error(fp, method->name, "error: SMETH_SINGLEVAL and SMETH_VARNUMVAL both set");
526             bOk = false;
527         }
528     }
529     if ((method->flags & SMETH_CHARVAL) && method->type != STR_VALUE)
530     {
531         report_error(fp, method->name, "error: SMETH_CHARVAL can only be specified for STR_VALUE methods");
532         bOk = false;
533     }
534     /* Check the parameters */
535     if (!check_params(fp, method->name, method->nparams, method->param, symtab))
536     {
537         bOk = false;
538     }
539     /* Check the callback pointers */
540     if (!check_callbacks(fp, method))
541     {
542         bOk = false;
543     }
544
545     return bOk;
546 }
547
548 /*!
549  * Checks the validity of a selection modifier method.
550  *
551  * \param[in]     fp     File handle to use for diagnostic messages
552  *   (can be NULL).
553  * \param[in,out] method Method to check.
554  * \param[in]     symtab Symbol table (used for checking overlaps).
555  *
556  * Checks the validity of the given selection method data structure
557  * that has \ref SMETH_MODIFIER set.
558  * If you remove a check, please make sure that the selection parser,
559  * compiler, and evaluation functions can deal with the method.
560  */
561 static bool
562 check_modifier(FILE *fp, gmx_ana_selmethod_t *method,
563                const gmx::SelectionParserSymbolTable &symtab)
564 {
565     bool         bOk = true;
566
567     /* Check the type */
568     if (method->type != NO_VALUE && method->type != POS_VALUE)
569     {
570         report_error(fp, method->name, "error: modifier should have type POS_VALUE or NO_VALUE");
571         bOk = false;
572     }
573     /* Check flags */
574     if (method->flags & (SMETH_SINGLEVAL | SMETH_VARNUMVAL))
575     {
576         report_error(fp, method->name, "error: modifier should not have SMETH_SINGLEVAL or SMETH_VARNUMVAL set");
577         bOk = false;
578     }
579     /* Check the parameters */
580     /* The first parameter is skipped */
581     if (!check_params(fp, method->name, method->nparams-1, method->param+1, symtab))
582     {
583         bOk = false;
584     }
585     /* Check the callback pointers */
586     if (!check_callbacks(fp, method))
587     {
588         bOk = false;
589     }
590     if (method->update)
591     {
592         report_error(fp, method->name, "error: modifier should not have update");
593         bOk = false;
594     }
595     if (method->type == POS_VALUE && !method->pupdate)
596     {
597         report_error(fp, method->name, "error: evaluation function missing");
598         bOk = false;
599     }
600
601     return bOk;
602 }
603
604 /*!
605  * \param[in,out] symtab Symbol table to register the method to.
606  * \param[in]     name   Name under which the method should be registered.
607  * \param[in]     method Method to register.
608  * \returns       0 on success, EINVAL if there was something wrong with the
609  *   method.
610  *
611  * \p name does not need to match the name of the method, and the same
612  * method can be registered multiple times under different names.
613  * If \p name equals some previously registered name,
614  * an error message is printed and the method is not registered.
615  *
616  * The function also performs some sanity checking on the input method,
617  * and refuses to register it if there are problems.
618  * Some problems only generate warnings.
619  * All problems are described to \p stderr.
620  */
621 int
622 gmx_ana_selmethod_register(gmx::SelectionParserSymbolTable *symtab,
623                            const char *name, gmx_ana_selmethod_t *method)
624 {
625     bool bOk;
626
627     /* Check the method */
628     if (method->flags & SMETH_MODIFIER)
629     {
630         bOk = check_modifier(stderr, method, *symtab);
631     }
632     else
633     {
634         bOk = check_method(stderr, method, *symtab);
635     }
636     /* Try to register the method if everything is ok */
637     if (bOk)
638     {
639         try
640         {
641             symtab->addMethod(name, method);
642         }
643         catch (const gmx::APIError &ex)
644         {
645             report_error(stderr, name, ex.what());
646             bOk = false;
647         }
648     }
649     if (!bOk)
650     {
651         report_error(stderr, name, "warning: not registered");
652         return EINVAL;
653     }
654     return 0;
655 }
656
657 /*!
658  * \param[in,out] symtab Symbol table to register the methods to.
659  * \returns       0 on success, -1 if any of the default methods could not be
660  *   registered.
661  */
662 int
663 gmx_ana_selmethod_register_defaults(gmx::SelectionParserSymbolTable *symtab)
664 {
665     size_t i;
666     int  rc;
667     bool bOk;
668
669     bOk = true;
670     for (i = 0; i < asize(smtable_def); ++i)
671     {
672         gmx_ana_selmethod_t *method = smtable_def[i].method;
673
674         if (smtable_def[i].name == NULL)
675         {
676             rc = gmx_ana_selmethod_register(symtab, method->name, method);
677         }
678         else
679         {
680             rc = gmx_ana_selmethod_register(symtab, smtable_def[i].name, method);
681         }
682         if (rc != 0)
683         {
684             bOk = false;
685         }
686     }
687     return bOk ? 0 : -1;
688 }
689
690 /*!
691  * \param[in] name   Name of the parameter to search.
692  * \param[in] method Method to search for the parameter.
693  * \returns   Pointer to the parameter in the
694  *   \ref gmx_ana_selmethod_t::param "method->param" array,
695  *   or NULL if no parameter with name \p name was found.
696  *
697  * This is a simple wrapper for gmx_ana_selparam_find().
698  */
699 gmx_ana_selparam_t *
700 gmx_ana_selmethod_find_param(const char *name, gmx_ana_selmethod_t *method)
701 {
702     return gmx_ana_selparam_find(name, method->nparams, method->param);
703 }