Apply clang-format to source tree
[alexxy/gromacs.git] / src / gromacs / commandline / pargs.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "gmxpre.h"
38
39 #include "pargs.h"
40
41 #include <cstdlib>
42 #include <cstring>
43
44 #include <algorithm>
45 #include <list>
46
47 #include "gromacs/commandline/cmdlinehelpcontext.h"
48 #include "gromacs/commandline/cmdlinehelpwriter.h"
49 #include "gromacs/commandline/cmdlineparser.h"
50 #include "gromacs/fileio/oenv.h"
51 #include "gromacs/fileio/timecontrol.h"
52 #include "gromacs/options/basicoptions.h"
53 #include "gromacs/options/behaviorcollection.h"
54 #include "gromacs/options/filenameoption.h"
55 #include "gromacs/options/filenameoptionmanager.h"
56 #include "gromacs/options/options.h"
57 #include "gromacs/options/timeunitmanager.h"
58 #include "gromacs/utility/arrayref.h"
59 #include "gromacs/utility/basenetwork.h"
60 #include "gromacs/utility/classhelpers.h"
61 #include "gromacs/utility/exceptions.h"
62 #include "gromacs/utility/fatalerror.h"
63 #include "gromacs/utility/gmxassert.h"
64 #include "gromacs/utility/path.h"
65 #include "gromacs/utility/programcontext.h"
66 #include "gromacs/utility/stringutil.h"
67
68 /* The source code in this file should be thread-safe.
69       Please keep it that way. */
70
71 int nenum(const char* const enumc[])
72 {
73     int i;
74
75     i = 1;
76     /* we *can* compare pointers directly here! */
77     while (enumc[i] && enumc[0] != enumc[i])
78     {
79         i++;
80     }
81
82     return i;
83 }
84
85 int opt2parg_int(const char* option, int nparg, t_pargs pa[])
86 {
87     int i;
88
89     for (i = 0; (i < nparg); i++)
90     {
91         if (strcmp(pa[i].option, option) == 0)
92         {
93             return *pa[i].u.i;
94         }
95     }
96
97     gmx_fatal(FARGS, "No integer option %s in pargs", option);
98 }
99
100 gmx_bool opt2parg_bool(const char* option, int nparg, t_pargs pa[])
101 {
102     int i;
103
104     for (i = 0; (i < nparg); i++)
105     {
106         if (strcmp(pa[i].option, option) == 0)
107         {
108             return *pa[i].u.b;
109         }
110     }
111
112     gmx_fatal(FARGS, "No boolean option %s in pargs", option);
113
114     return FALSE;
115 }
116
117 real opt2parg_real(const char* option, int nparg, t_pargs pa[])
118 {
119     int i;
120
121     for (i = 0; (i < nparg); i++)
122     {
123         if (strcmp(pa[i].option, option) == 0)
124         {
125             return *pa[i].u.r;
126         }
127     }
128
129     gmx_fatal(FARGS, "No real option %s in pargs", option);
130 }
131
132 const char* opt2parg_str(const char* option, int nparg, t_pargs pa[])
133 {
134     int i;
135
136     for (i = 0; (i < nparg); i++)
137     {
138         if (strcmp(pa[i].option, option) == 0)
139         {
140             return *(pa[i].u.c);
141         }
142     }
143
144     gmx_fatal(FARGS, "No string option %s in pargs", option);
145 }
146
147 gmx_bool opt2parg_bSet(const char* option, int nparg, const t_pargs* pa)
148 {
149     int i;
150
151     for (i = 0; (i < nparg); i++)
152     {
153         if (strcmp(pa[i].option, option) == 0)
154         {
155             return pa[i].bSet;
156         }
157     }
158
159     gmx_fatal(FARGS, "No such option %s in pargs", option);
160
161     return FALSE; /* Too make some compilers happy */
162 }
163
164 const char* opt2parg_enum(const char* option, int nparg, t_pargs pa[])
165 {
166     int i;
167
168     for (i = 0; (i < nparg); i++)
169     {
170         if (strcmp(pa[i].option, option) == 0)
171         {
172             return pa[i].u.c[0];
173         }
174     }
175
176     gmx_fatal(FARGS, "No such option %s in pargs", option);
177 }
178
179 /********************************************************************
180  * parse_common_args()
181  */
182
183 namespace gmx
184 {
185
186 namespace
187 {
188
189 /*! \brief
190  * Returns the index of the default xvg format.
191  *
192  * \ingroup module_commandline
193  */
194 int getDefaultXvgFormat(gmx::ArrayRef<const char* const> xvgFormats)
195 {
196     const char* const select = getenv("GMX_VIEW_XVG");
197     if (select != nullptr)
198     {
199         ArrayRef<const char* const>::const_iterator i =
200                 std::find(xvgFormats.begin(), xvgFormats.end(), std::string(select));
201         if (i != xvgFormats.end())
202         {
203             return std::distance(xvgFormats.begin(), i);
204         }
205         else
206         {
207             return exvgNONE - 1;
208         }
209     }
210     /* The default is the first option */
211     return 0;
212 }
213
214 /*! \brief
215  * Conversion helper between t_pargs/t_filenm and Options.
216  *
217  * This class holds the necessary mapping between the old C structures and
218  * the new C++ options to allow copying values back after parsing for cases
219  * where the C++ options do not directly provide the type of value required for
220  * the C structures.
221  *
222  * \ingroup module_commandline
223  */
224 class OptionsAdapter
225 {
226 public:
227     /*! \brief
228      * Initializes the adapter to convert from a specified command line.
229      *
230      * The command line is required, because t_pargs wants to return
231      * strings by reference to the original command line.
232      * OptionsAdapter creates a copy of the `argv` array (but not the
233      * strings) to make this possible, even if the parser removes
234      * options it has recognized.
235      */
236     OptionsAdapter(int argc, const char* const argv[]) : argv_(argv, argv + argc) {}
237
238     /*! \brief
239      * Converts a t_filenm option into an Options option.
240      *
241      * \param options Options object to add the new option to.
242      * \param fnm     t_filenm option to convert.
243      */
244     void filenmToOptions(Options* options, t_filenm* fnm);
245     /*! \brief
246      * Converts a t_pargs option into an Options option.
247      *
248      * \param     options Options object to add the new option to.
249      * \param     pa      t_pargs option to convert.
250      */
251     void pargsToOptions(Options* options, t_pargs* pa);
252
253     /*! \brief
254      * Copies values back from options to t_pargs/t_filenm.
255      */
256     void copyValues();
257
258 private:
259     struct FileNameData
260     {
261         //! Creates a conversion helper for a given `t_filenm` struct.
262         explicit FileNameData(t_filenm* fnm) : fnm(fnm), optionInfo(nullptr) {}
263
264         //! t_filenm structure to receive the final values.
265         t_filenm* fnm;
266         //! Option info object for the created FileNameOption.
267         FileNameOptionInfo* optionInfo;
268         //! Value storage for the created FileNameOption.
269         std::vector<std::string> values;
270     };
271     struct ProgramArgData
272     {
273         //! Creates a conversion helper for a given `t_pargs` struct.
274         explicit ProgramArgData(t_pargs* pa) :
275             pa(pa),
276             optionInfo(nullptr),
277             enumIndex(0),
278             boolValue(false)
279         {
280         }
281
282         //! t_pargs structure to receive the final values.
283         t_pargs* pa;
284         //! Option info object for the created option.
285         OptionInfo* optionInfo;
286         //! Value storage for a non-enum StringOption (unused for other types).
287         std::string stringValue;
288         //! Value storage for an enum option (unused for other types).
289         int enumIndex;
290         //! Value storage for a BooleanOption (unused for other types).
291         bool boolValue;
292     };
293
294     std::vector<const char*> argv_;
295     // These are lists instead of vectors to avoid relocating existing
296     // objects in case the container is reallocated (the Options object
297     // contains pointes to members of the objects, which would get
298     // invalidated).
299     std::list<FileNameData>   fileNameOptions_;
300     std::list<ProgramArgData> programArgs_;
301
302     GMX_DISALLOW_COPY_AND_ASSIGN(OptionsAdapter);
303 };
304
305 void OptionsAdapter::filenmToOptions(Options* options, t_filenm* fnm)
306 {
307     const bool        bRead     = ((fnm->flag & ffREAD) != 0);
308     const bool        bWrite    = ((fnm->flag & ffWRITE) != 0);
309     const bool        bOptional = ((fnm->flag & ffOPT) != 0);
310     const bool        bLibrary  = ((fnm->flag & ffLIB) != 0);
311     const bool        bMultiple = ((fnm->flag & ffMULT) != 0);
312     const bool        bMissing  = ((fnm->flag & ffALLOW_MISSING) != 0);
313     const char* const name      = (fnm->opt ? &fnm->opt[1] : &ftp2defopt(fnm->ftp)[1]);
314     const char*       defName   = fnm->fn;
315     int               defType   = -1;
316     if (defName == nullptr)
317     {
318         defName = ftp2defnm(fnm->ftp);
319     }
320     else if (Path::hasExtension(defName))
321     {
322         defType = fn2ftp(defName);
323         GMX_RELEASE_ASSERT(defType != efNR, "File name option specifies an invalid extension");
324     }
325     fileNameOptions_.emplace_back(fnm);
326     FileNameData& data = fileNameOptions_.back();
327     data.optionInfo    = options->addOption(FileNameOption(name)
328                                                  .storeVector(&data.values)
329                                                  .defaultBasename(defName)
330                                                  .defaultType(defType)
331                                                  .legacyType(fnm->ftp)
332                                                  .legacyOptionalBehavior()
333                                                  .readWriteFlags(bRead, bWrite)
334                                                  .required(!bOptional)
335                                                  .libraryFile(bLibrary)
336                                                  .multiValue(bMultiple)
337                                                  .allowMissing(bMissing)
338                                                  .description(ftp2desc(fnm->ftp)));
339 }
340
341 void OptionsAdapter::pargsToOptions(Options* options, t_pargs* pa)
342 {
343     const bool        bHidden = startsWith(pa->desc, "HIDDEN");
344     const char* const name    = &pa->option[1];
345     const char* const desc    = (bHidden ? &pa->desc[6] : pa->desc);
346     programArgs_.emplace_back(pa);
347     ProgramArgData& data = programArgs_.back();
348     switch (pa->type)
349     {
350         case etINT:
351             data.optionInfo = options->addOption(
352                     IntegerOption(name).store(pa->u.i).description(desc).hidden(bHidden));
353             return;
354         case etINT64:
355             data.optionInfo = options->addOption(
356                     Int64Option(name).store(pa->u.is).description(desc).hidden(bHidden));
357             return;
358         case etREAL:
359             data.optionInfo =
360                     options->addOption(RealOption(name).store(pa->u.r).description(desc).hidden(bHidden));
361             return;
362         case etTIME:
363             data.optionInfo = options->addOption(
364                     RealOption(name).store(pa->u.r).timeValue().description(desc).hidden(bHidden));
365             return;
366         case etSTR:
367         {
368             const char* const defValue = (*pa->u.c != nullptr ? *pa->u.c : "");
369             data.optionInfo            = options->addOption(StringOption(name)
370                                                          .store(&data.stringValue)
371                                                          .defaultValue(defValue)
372                                                          .description(desc)
373                                                          .hidden(bHidden));
374             return;
375         }
376         case etBOOL:
377             data.optionInfo = options->addOption(BooleanOption(name)
378                                                          .store(&data.boolValue)
379                                                          .defaultValue(*pa->u.b)
380                                                          .description(desc)
381                                                          .hidden(bHidden));
382             return;
383         case etRVEC:
384             data.optionInfo = options->addOption(
385                     RealOption(name).store(*pa->u.rv).vector().description(desc).hidden(bHidden));
386             return;
387         case etENUM:
388         {
389             const int defaultIndex = (pa->u.c[0] != nullptr ? nenum(pa->u.c) - 1 : 0);
390             data.optionInfo        = options->addOption(EnumIntOption(name)
391                                                          .store(&data.enumIndex)
392                                                          .defaultValue(defaultIndex)
393                                                          .enumValueFromNullTerminatedArray(pa->u.c + 1)
394                                                          .description(desc)
395                                                          .hidden(bHidden));
396             return;
397         }
398     }
399     GMX_THROW(NotImplementedError("Argument type not implemented"));
400 }
401
402 void OptionsAdapter::copyValues()
403 {
404     std::list<FileNameData>::const_iterator file;
405     for (file = fileNameOptions_.begin(); file != fileNameOptions_.end(); ++file)
406     {
407         if (file->optionInfo->isSet())
408         {
409             file->fnm->flag |= ffSET;
410         }
411         file->fnm->filenames = file->values;
412     }
413     std::list<ProgramArgData>::const_iterator arg;
414     for (arg = programArgs_.begin(); arg != programArgs_.end(); ++arg)
415     {
416         arg->pa->bSet = arg->optionInfo->isSet();
417         switch (arg->pa->type)
418         {
419             case etSTR:
420             {
421                 if (arg->pa->bSet)
422                 {
423                     std::vector<const char*>::const_iterator pos =
424                             std::find(argv_.begin(), argv_.end(), arg->stringValue);
425                     GMX_RELEASE_ASSERT(pos != argv_.end(),
426                                        "String argument got a value not in argv");
427                     *arg->pa->u.c = *pos;
428                 }
429                 break;
430             }
431             case etBOOL: *arg->pa->u.b = arg->boolValue; break;
432             case etENUM: *arg->pa->u.c = arg->pa->u.c[arg->enumIndex + 1]; break;
433             default:
434                 // For other types, there is nothing type-specific to do.
435                 break;
436         }
437     }
438 }
439
440 } // namespace
441
442 } // namespace gmx
443
444 gmx_bool parse_common_args(int*               argc,
445                            char*              argv[],
446                            unsigned long      Flags,
447                            int                nfile,
448                            t_filenm           fnm[],
449                            int                npargs,
450                            t_pargs*           pa,
451                            int                ndesc,
452                            const char**       desc,
453                            int                nbugs,
454                            const char**       bugs,
455                            gmx_output_env_t** oenv)
456 {
457     /* This array should match the order of the enum in oenv.h */
458     const char* const xvg_formats[] = { "xmgrace", "xmgr", "none" };
459
460     // Lambda function to test the (local) Flags parameter against a bit mask.
461     auto isFlagSet = [Flags](unsigned long bits) { return (Flags & bits) == bits; };
462
463     try
464     {
465         double                         tbegin = 0.0, tend = 0.0, tdelta = 0.0;
466         bool                           bBeginTimeSet = false, bEndTimeSet = false, bDtSet = false;
467         bool                           bView     = false;
468         int                            xvgFormat = 0;
469         gmx::OptionsAdapter            adapter(*argc, argv);
470         gmx::Options                   options;
471         gmx::OptionsBehaviorCollection behaviors(&options);
472         gmx::FileNameOptionManager     fileOptManager;
473
474         fileOptManager.disableInputOptionChecking(isFlagSet(PCA_DISABLE_INPUT_FILE_CHECKING));
475         options.addManager(&fileOptManager);
476
477         if (isFlagSet(PCA_CAN_SET_DEFFNM))
478         {
479             fileOptManager.addDefaultFileNameOption(&options, "deffnm");
480         }
481         if (isFlagSet(PCA_CAN_BEGIN))
482         {
483             options.addOption(
484                     gmx::DoubleOption("b").store(&tbegin).storeIsSet(&bBeginTimeSet).timeValue().description("Time of first frame to read from trajectory (default unit %t)"));
485         }
486         if (isFlagSet(PCA_CAN_END))
487         {
488             options.addOption(
489                     gmx::DoubleOption("e").store(&tend).storeIsSet(&bEndTimeSet).timeValue().description("Time of last frame to read from trajectory (default unit %t)"));
490         }
491         if (isFlagSet(PCA_CAN_DT))
492         {
493             options.addOption(gmx::DoubleOption("dt").store(&tdelta).storeIsSet(&bDtSet).timeValue().description(
494                     "Only use frame when t MOD dt = first time (default unit %t)"));
495         }
496         gmx::TimeUnit timeUnit = gmx::TimeUnit_Default;
497         if (isFlagSet(PCA_TIME_UNIT))
498         {
499             std::shared_ptr<gmx::TimeUnitBehavior> timeUnitBehavior(new gmx::TimeUnitBehavior());
500             timeUnitBehavior->setTimeUnitStore(&timeUnit);
501             timeUnitBehavior->setTimeUnitFromEnvironment();
502             timeUnitBehavior->addTimeUnitOption(&options, "tu");
503             behaviors.addBehavior(timeUnitBehavior);
504         }
505         if (isFlagSet(PCA_CAN_VIEW))
506         {
507             options.addOption(gmx::BooleanOption("w").store(&bView).description(
508                     "View output [REF].xvg[ref], [REF].xpm[ref], "
509                     "[REF].eps[ref] and [REF].pdb[ref] files"));
510         }
511
512         bool bXvgr = false;
513         for (int i = 0; i < nfile; i++)
514         {
515             bXvgr = bXvgr || (fnm[i].ftp == efXVG);
516         }
517         xvgFormat = gmx::getDefaultXvgFormat(xvg_formats);
518         if (bXvgr)
519         {
520             options.addOption(
521                     gmx::EnumIntOption("xvg").enumValue(xvg_formats).store(&xvgFormat).description("xvg plot formatting"));
522         }
523
524         /* Now append the program specific arguments */
525         for (int i = 0; i < nfile; i++)
526         {
527             adapter.filenmToOptions(&options, &fnm[i]);
528         }
529         for (int i = 0; i < npargs; i++)
530         {
531             adapter.pargsToOptions(&options, &pa[i]);
532         }
533
534         const gmx::CommandLineHelpContext* context = gmx::GlobalCommandLineHelpContext::get();
535         if (context != nullptr)
536         {
537             GMX_RELEASE_ASSERT(gmx_node_rank() == 0,
538                                "Help output should be handled higher up and "
539                                "only get called only on the master rank");
540             gmx::CommandLineHelpWriter(options)
541                     .setHelpText(gmx::constArrayRefFromArray<const char*>(desc, ndesc))
542                     .setKnownIssues(gmx::constArrayRefFromArray(bugs, nbugs))
543                     .writeHelp(*context);
544             return FALSE;
545         }
546
547         /* Now parse all the command-line options */
548         gmx::CommandLineParser(&options)
549                 .skipUnknown(isFlagSet(PCA_NOEXIT_ON_ARGS))
550                 .allowPositionalArguments(isFlagSet(PCA_NOEXIT_ON_ARGS))
551                 .parse(argc, argv);
552         behaviors.optionsFinishing();
553         options.finish();
554
555         /* set program name, command line, and default values for output options */
556         output_env_init(oenv, gmx::getProgramContext(), static_cast<time_unit_t>(timeUnit + 1),
557                         bView, // NOLINT(bugprone-misplaced-widening-cast)
558                         static_cast<xvg_format_t>(xvgFormat + 1), 0);
559
560         /* Extract Time info from arguments */
561         if (bBeginTimeSet)
562         {
563             setTimeValue(TBEGIN, tbegin);
564         }
565         if (bEndTimeSet)
566         {
567             setTimeValue(TEND, tend);
568         }
569         if (bDtSet)
570         {
571             setTimeValue(TDELTA, tdelta);
572         }
573
574         adapter.copyValues();
575
576         return TRUE;
577     }
578     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
579 }