https://mooseframework.inl.gov
Loading...
Searching...
No Matches
Classes | Public Member Functions | Static Public Member Functions | Private Attributes | List of all members
Parser Class Reference

Class for parsing input files. More...

#include <Parser.h>

Classes

struct  Error
 

Public Member Functions

 Parser (const std::vector< std::string > &input_filenames, const std::optional< std::vector< std::string > > &input_text={})
 Constructor given a list of input files, given in input_filenames.
 
 Parser (const std::string &input_filename, const std::optional< std::string > &input_text={})
 Constructor, given a file in input_filename.
 
void parse ()
 Parses the inputs.
 
hit::Node & getRoot ()
 
const std::vector< std::string > & getInputFileNames () const
 
const std::vector< std::string > & getInputText () const
 
const std::string & getAppType () const
 
void setAppType (const std::string &app_type)
 
void setCommandLineParams (const std::vector< std::string > &params)
 Sets the HIT parameters from the command line.
 
const std::string & getLastInputFileName () const
 
std::filesystem::path getLastInputFilePath () const
 
void setThrowOnError (const bool throw_on_error)
 Set whether or not to throw Parse::Error on errors.
 
bool getThrowOnError () const
 
const std::set< std::string > & getExtractedVars () const
 
void parseError (std::vector< hit::ErrorMessage > messages) const
 Helper for throwing an error with the given messages.
 
const hit::Node * queryRoot () const
 
hit::Node * queryRoot ()
 
const hit::Node * queryCommandLineRoot () const
 
hit::Node * queryCommandLineRoot ()
 
const hit::Node & getCommandLineRoot () const
 
hit::Node & getCommandLineRoot ()
 

Static Public Member Functions

static std::string joinErrorMessages (const std::vector< hit::ErrorMessage > &error_messages)
 Helper for combining error messages into a single, newline separated message.
 
static void appendErrorMessages (std::vector< hit::ErrorMessage > &to, const std::vector< hit::ErrorMessage > &from)
 Helper for accumulating errors from a walker into an accumulation of errors.
 
static void appendErrorMessages (std::vector< hit::ErrorMessage > &to, const hit::Error &error)
 

Private Attributes

std::unique_ptr< hit::Node > _root
 The root node, which owns the whole tree.
 
const std::vector< std::string > _input_filenames
 The input file names.
 
std::vector< std::string > _input_text
 The input text (may be filled during parse())
 
std::unique_ptr< hit::Node > _cli_root
 The root node for command line hit arguments.
 
std::string _app_type
 The application types extracted from [Application] block.
 
bool _throw_on_error
 Whether or not to throw on error.
 
std::optional< std::vector< std::string > > _command_line_params
 The command line HIT parameters (if any)
 
std::set< std::string > _extracted_vars
 Variables that have been extracted during brace expansion.
 

Detailed Description

Class for parsing input files.

This class utilizes the GetPot library for actually tokenizing and parsing files. It is not currently designed for extensibility. If you wish to build your own parser, please contact the MOOSE team for guidance.

Definition at line 101 of file Parser.h.

Constructor & Destructor Documentation

◆ Parser() [1/2]

Parser::Parser ( const std::vector< std::string > &  input_filenames,
const std::optional< std::vector< std::string > > &  input_text = {} 
)

Constructor given a list of input files, given in input_filenames.

Optionally, the file contents can be provided via text in input_text.

Definition at line 215 of file Parser.C.

217 : _root(nullptr),
218 _input_filenames(input_filenames),
219 _input_text(input_text ? *input_text : std::vector<std::string>()),
220 _cli_root(nullptr),
221 _throw_on_error(false)
222{
223 if (input_text && _input_filenames.size() != input_text->size())
224 mooseError("Parser: Input text not the same length as input filenames");
225}
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
Definition MooseError.h:311
std::vector< std::string > _input_text
The input text (may be filled during parse())
Definition Parser.h:251
const std::vector< std::string > _input_filenames
The input file names.
Definition Parser.h:248
std::unique_ptr< hit::Node > _cli_root
The root node for command line hit arguments.
Definition Parser.h:254
std::unique_ptr< hit::Node > _root
The root node, which owns the whole tree.
Definition Parser.h:245
bool _throw_on_error
Whether or not to throw on error.
Definition Parser.h:260

◆ Parser() [2/2]

Parser::Parser ( const std::string &  input_filename,
const std::optional< std::string > &  input_text = {} 
)

Constructor, given a file in input_filename.

Optionally, the file contents can be provided via text in input_text.

Definition at line 227 of file Parser.C.

229 : Parser(std::vector<std::string>{input_filename},
230 input_text ? std::optional<std::vector<std::string>>({*input_text})
231 : std::optional<std::vector<std::string>>())
232{
233}
Class for parsing input files.
Definition Parser.h:102

Member Function Documentation

◆ appendErrorMessages() [1/2]

void Parser::appendErrorMessages ( std::vector< hit::ErrorMessage > &  to,
const hit::Error &  error 
)
static

Definition at line 554 of file Parser.C.

555{
556 appendErrorMessages(to, error.error_messages);
557}
static void appendErrorMessages(std::vector< hit::ErrorMessage > &to, const std::vector< hit::ErrorMessage > &from)
Helper for accumulating errors from a walker into an accumulation of errors.
Definition Parser.C:547

◆ appendErrorMessages() [2/2]

void Parser::appendErrorMessages ( std::vector< hit::ErrorMessage > &  to,
const std::vector< hit::ErrorMessage > &  from 
)
static

Helper for accumulating errors from a walker into an accumulation of errors.

Definition at line 547 of file Parser.C.

549{
550 to.insert(to.end(), from.begin(), from.end());
551}

Referenced by appendErrorMessages(), Moose::Builder::errorCheck(), and parse().

◆ getAppType()

const std::string & Parser::getAppType ( ) const
inline

Definition at line 179 of file Parser.h.

179{ return _app_type; }
std::string _app_type
The application types extracted from [Application] block.
Definition Parser.h:257

◆ getCommandLineRoot() [1/2]

hit::Node & Parser::getCommandLineRoot ( )

Definition at line 541 of file Parser.C.

542{
543 return const_cast<hit::Node &>(std::as_const(*this).getCommandLineRoot());
544}

◆ getCommandLineRoot() [2/2]

const hit::Node & Parser::getCommandLineRoot ( ) const
Returns
The root command line HIT node, with error checking on if it exists

If it doesn't exist, it means we haven't parsed yet

Definition at line 533 of file Parser.C.

534{
536 mooseError("Parser::getCommandLineRoot(): command line root is not set");
537 return *queryCommandLineRoot();
538}
const hit::Node * queryCommandLineRoot() const
Definition Parser.h:152

Referenced by Moose::Builder::errorCheck(), parse(), and parseError().

◆ getExtractedVars()

const std::set< std::string > & Parser::getExtractedVars ( ) const
inline
Returns
The variables that have been extracted so far.

These are the variables that have been used during brace expansion.

Definition at line 220 of file Parser.h.

220{ return _extracted_vars; }
std::set< std::string > _extracted_vars
Variables that have been extracted during brace expansion.
Definition Parser.h:266

Referenced by Moose::Builder::build().

◆ getInputFileNames()

const std::vector< std::string > & Parser::getInputFileNames ( ) const
inline
Returns
The names of the inputs

Definition at line 169 of file Parser.h.

169{ return _input_filenames; }

Referenced by parse().

◆ getInputText()

const std::vector< std::string > & Parser::getInputText ( ) const
inline
Returns
The input file contents

Definition at line 174 of file Parser.h.

174{ return _input_text; }

Referenced by parse().

◆ getLastInputFileName()

const std::string & Parser::getLastInputFileName ( ) const
Returns
The file name of the last input

Definition at line 358 of file Parser.C.

359{
360 if (_input_filenames.empty())
361 mooseError("Parser::getLastInputFileName(): No inputs are set");
362 return _input_filenames.back();
363}

Referenced by getLastInputFilePath().

◆ getLastInputFilePath()

std::filesystem::path Parser::getLastInputFilePath ( ) const
inline
Returns
The path of the last input

Definition at line 199 of file Parser.h.

199{ return getLastInputFileName(); }
const std::string & getLastInputFileName() const
Definition Parser.C:358

Referenced by Moose::Builder::getPrimaryFileName().

◆ getRoot()

hit::Node & Parser::getRoot ( )
Returns
The root HIT node with error checking on if it exists

If it doesn't exist, it means we haven't parsed yet

Definition at line 525 of file Parser.C.

526{
527 if (!queryRoot())
528 mooseError("Parser::getRoot(): root is not set");
529 return *queryRoot();
530}
const hit::Node * queryRoot() const
Definition Parser.h:135

Referenced by ActionFactory::create(), and parse().

◆ getThrowOnError()

bool Parser::getThrowOnError ( ) const
inline
Returns
Whether or not to throw Parse::Error on errors

This is used by the MooseServer to capture errors while retaining the root if possible

Definition at line 213 of file Parser.h.

213{ return _throw_on_error; }

Referenced by Moose::Builder::errorCheck().

◆ joinErrorMessages()

std::string Parser::joinErrorMessages ( const std::vector< hit::ErrorMessage > &  error_messages)
static

Helper for combining error messages into a single, newline separated message.

Definition at line 560 of file Parser.C.

561{
562 std::vector<std::string> values;
563 for (const auto & em : error_messages)
564 values.push_back(em.prefixed_message);
565 return MooseUtils::stringJoin(values, "\n");
566}
std::array< Real, 2 > values
Definition MortarUtils.C:52
std::string stringJoin(const std::vector< std::string > &values, const std::string &separator=" ")
Concatenates value into a single string separated by separator.

Referenced by Moose::Builder::errorCheck(), and parseError().

◆ parse()

void Parser::parse ( )

Parses the inputs.

Definition at line 371 of file Parser.C.

372{
373 mooseAssert(!_root && !_cli_root, "Has already parsed");
374
375 if (getInputFileNames().size() > 1)
376 mooseInfo("Merging inputs ", Moose::stringify(getInputFileNames()));
377
378 // Correct filenames (default is to use real path)
379 const std::string use_rel_paths_str =
380 std::getenv("MOOSE_RELATIVE_FILEPATHS") ? std::getenv("MOOSE_RELATIVE_FILEPATHS") : "false";
381 const auto use_real_paths = use_rel_paths_str == "0" || use_rel_paths_str == "false";
382 std::vector<std::string> filenames;
383 for (const auto & filename : getInputFileNames())
384 filenames.push_back(use_real_paths ? MooseUtils::realpath(filename) : filename);
385
386 // Load each input file if text was not provided
387 if (_input_text.empty())
388 for (const auto & filename : filenames)
389 {
390 MooseUtils::checkFileReadable(filename, true);
391 std::ifstream f(filename);
392 _input_text.push_back(
393 std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()));
394 }
395
396 CompileParamWalker::ParamMap override_map;
397 CompileParamWalker cpw(override_map);
398 OverrideParamWalker opw(override_map);
399
400 // Errors from the duplicate param walker, ran within each input
401 // independently first
402 std::vector<hit::ErrorMessage> dw_errors;
403
404 for (const auto i : index_range(getInputFileNames()))
405 {
406 const auto & filename = filenames[i];
407 const auto & input = getInputText()[i];
408
409 try
410 {
411 // provide stream to hit parse function to capture any syntax errors,
412 // set parser root node, then throw those errors if any were captured
413 std::vector<hit::ErrorMessage> syntax_errors;
414 std::unique_ptr<hit::Node> root(hit::parse(filename, input, &syntax_errors));
415
417 root->walk(&dw, hit::NodeType::Field);
418 appendErrorMessages(dw_errors, dw.errors);
419
420 if (!queryRoot())
421 _root = std::move(root);
422 else
423 {
424 root->walk(&opw, hit::NodeType::Field);
425 hit::merge(root.get(), &getRoot());
426 }
427
428 if (!syntax_errors.empty())
429 throw Parser::Error(syntax_errors);
430
431 getRoot().walk(&cpw, hit::NodeType::Field);
432 }
433 catch (hit::Error & err)
434 {
435 parseError(err.error_messages);
436 }
437 }
438
439 // warn about overridden parameters in multiple inputs
440 if (!opw.warnings.empty())
441 mooseInfo(Moose::stringify(opw.warnings), "\n");
442
443 // If we don't have a root (allow no input files),
444 // create an empty one
445 if (!queryRoot())
446 _root.reset(hit::parse("EMPTY", ""));
447
448 {
450 getRoot().walk(&bw, hit::NodeType::Section);
451 if (bw.errors.size())
452 parseError(bw.errors);
453 }
454
455 {
456 FindAppWalker fw;
457 getRoot().walk(&fw, hit::NodeType::Field);
458 if (fw.getApp())
459 setAppType(*fw.getApp());
460 }
461
462 // Duplicate parameter errors (within each input file)
463 if (dw_errors.size())
464 parseError(dw_errors);
465
466 // Merge in command line HIT arguments
467 const auto joined_params =
469 try
470 {
471 _cli_root.reset(hit::parse("CLI_ARGS", joined_params));
472 hit::merge(&getCommandLineRoot(), &getRoot());
473 }
474 catch (hit::Error & err)
475 {
476 parseError(err.error_messages);
477 }
478
479 std::vector<hit::ErrorMessage> errors;
480
481 // expand ${bla} parameter values and mark/include variables
482 // used in expansion as "used" (obtained later by the Builder
483 // with getExtractedVars())
484 {
485 hit::RawEvaler raw;
486 hit::EnvEvaler env;
487 hit::ReplaceEvaler repl;
488 FuncParseEvaler fparse_ev;
489 UnitsConversionEvaler units_ev;
490 EnumerateEvaler enumerate_ev;
491 RepeatEvaler repeat_ev;
492 hit::BraceExpander exw;
493 exw.registerEvaler("raw", raw);
494 exw.registerEvaler("env", env);
495 exw.registerEvaler("fparse", fparse_ev);
496 exw.registerEvaler("replace", repl);
497 exw.registerEvaler("units", units_ev);
498 exw.registerEvaler("enumerate", enumerate_ev);
499 exw.registerEvaler("repeat", repeat_ev);
500 getRoot().walk(&exw);
501 for (auto & var : exw.used)
502 _extracted_vars.insert(var);
503 Parser::appendErrorMessages(errors, exw.errors);
504 }
505
506 // Collect duplicate parameters now that we've merged inputs
507 {
509 getRoot().walk(&dw, hit::NodeType::Field);
511 }
512
513 // Check bad active now that we've merged inputs
514 {
516 getRoot().walk(&bw, hit::NodeType::Section);
518 }
519
520 if (errors.size())
521 parseError(errors);
522}
void mooseInfo(Args &&... args)
Emit an informational message with the given stringified, concatenated args.
Definition MooseError.h:401
std::vector< hit::ErrorMessage > errors
Definition Parser.h:68
virtual void walk(const std::string &, const std::string &, hit::Node *section) override
Definition Parser.C:282
std::map< std::string, hit::Node * > ParamMap
Definition Parser.h:74
virtual void walk(const std::string &fullpath, const std::string &, hit::Node *n) override
Definition Parser.C:236
std::vector< hit::ErrorMessage > errors
Definition Parser.h:56
const std::optional< std::string > & getApp()
Definition Parser.C:344
void walk(const std::string &, const std::string &, hit::Node *n) override
Definition Parser.C:339
void setAppType(const std::string &app_type)
Definition Parser.h:184
const hit::Node & getCommandLineRoot() const
Definition Parser.C:533
const std::vector< std::string > & getInputText() const
Definition Parser.h:174
const std::vector< std::string > & getInputFileNames() const
Definition Parser.h:169
std::optional< std::vector< std::string > > _command_line_params
The command line HIT parameters (if any)
Definition Parser.h:263
void parseError(std::vector< hit::ErrorMessage > messages) const
Helper for throwing an error with the given messages.
Definition Parser.C:569
hit::Node & getRoot()
Definition Parser.C:525
std::string realpath(const std::string &path)
bool checkFileReadable(const std::string &filename, bool check_line_endings, bool throw_on_unreadable, bool check_for_git_lfs_pointer)
Definition MooseUtils.C:265
std::string stringify(const T &t)
conversion to string
Definition Conversion.h:64
auto index_range(const T &sizable)
OStreamProxy err(std::cerr)

◆ parseError()

void Parser::parseError ( std::vector< hit::ErrorMessage >  messages) const

Helper for throwing an error with the given messages.

If throwOnError(), throw a Parser::Error (for the MooseServer). Otherwise, use mooseError() (for standard runs).

Definition at line 569 of file Parser.C.

570{
571 // Few things about command line arguments...
572 // 1. We don't care to add line and column context for CLI args, because
573 // it doesn't make sense. We go from the full CLI args and pull out
574 // the HIT parameters so "line" 1 might not even be command line
575 // argument 1. So, remove line/column context from all CLI args.
576 // 2. Whenever we have a parameter in input that then gets overridden
577 // by a command line argument, under the hood we're merging two
578 // different HIT trees. However, WASP doesn't currently update the
579 // "filename" context for the updated parameter. Which means that
580 // a param that is in input and then overridden by CLI will have
581 // its location as in input. Which isn't true. So we get around this
582 // by searching the independent CLI args tree for params that we have
583 // errors for. If the associated path is also in CLI args, we manually
584 // set its error to come from CLI args. This should be fixed in
585 // the future with a WASP update.
586 for (auto & em : messages)
587 if (em.node && queryCommandLineRoot())
588 if (getCommandLineRoot().find(em.node->fullpath()))
589 em = hit::ErrorMessage(em.message, "CLI_ARGS");
590
591 if (_throw_on_error)
592 throw Parser::Error(messages);
593 else
594 mooseError(joinErrorMessages(messages));
595}
if(!dmm->_nl) SETERRQ(PETSC_COMM_WORLD
static std::string joinErrorMessages(const std::vector< hit::ErrorMessage > &error_messages)
Helper for combining error messages into a single, newline separated message.
Definition Parser.C:560
KOKKOS_INLINE_FUNCTION const T * find(const T &target, const T *const begin, const T *const end)
Find a value in an array.
Definition KokkosUtils.h:40
Definition Moose.h:48

Referenced by Moose::Builder::build(), Moose::Builder::errorCheck(), and parse().

◆ queryCommandLineRoot() [1/2]

hit::Node * Parser::queryCommandLineRoot ( )
inline

Definition at line 153 of file Parser.h.

153{ return _cli_root.get(); }

◆ queryCommandLineRoot() [2/2]

const hit::Node * Parser::queryCommandLineRoot ( ) const
inline
Returns
The root command line HIT node if it exists

If this is null, it means we haven't parsed yet

Definition at line 152 of file Parser.h.

152{ return _cli_root.get(); }

Referenced by Moose::Builder::errorCheck(), getCommandLineRoot(), and parseError().

◆ queryRoot() [1/2]

hit::Node * Parser::queryRoot ( )
inline

Definition at line 136 of file Parser.h.

136{ return _root.get(); }

◆ queryRoot() [2/2]

const hit::Node * Parser::queryRoot ( ) const
inline
Returns
The root HIT node if it exists

If this is null, it means we haven't parsed yet

Definition at line 135 of file Parser.h.

135{ return _root.get(); }

Referenced by getRoot(), and parse().

◆ setAppType()

void Parser::setAppType ( const std::string &  app_type)
inline

Definition at line 184 of file Parser.h.

184{ _app_type = app_type; }

Referenced by parse().

◆ setCommandLineParams()

void Parser::setCommandLineParams ( const std::vector< std::string > &  params)

Sets the HIT parameters from the command line.

Definition at line 351 of file Parser.C.

352{
353 mooseAssert(!_command_line_params, "Already set");
354 _command_line_params = params;
355}

◆ setThrowOnError()

void Parser::setThrowOnError ( const bool  throw_on_error)
inline

Set whether or not to throw Parse::Error on errors.

This is used by the MooseServer to capture errors while retaining the root if possible

Definition at line 206 of file Parser.h.

206{ _throw_on_error = throw_on_error; }

Member Data Documentation

◆ _app_type

std::string Parser::_app_type
private

The application types extracted from [Application] block.

Definition at line 257 of file Parser.h.

Referenced by getAppType(), and setAppType().

◆ _cli_root

std::unique_ptr<hit::Node> Parser::_cli_root
private

The root node for command line hit arguments.

Definition at line 254 of file Parser.h.

Referenced by parse(), queryCommandLineRoot(), and queryCommandLineRoot().

◆ _command_line_params

std::optional<std::vector<std::string> > Parser::_command_line_params
private

The command line HIT parameters (if any)

Definition at line 263 of file Parser.h.

Referenced by parse(), and setCommandLineParams().

◆ _extracted_vars

std::set<std::string> Parser::_extracted_vars
private

Variables that have been extracted during brace expansion.

Definition at line 266 of file Parser.h.

Referenced by getExtractedVars(), and parse().

◆ _input_filenames

const std::vector<std::string> Parser::_input_filenames
private

The input file names.

Definition at line 248 of file Parser.h.

Referenced by getInputFileNames(), getLastInputFileName(), and Parser().

◆ _input_text

std::vector<std::string> Parser::_input_text
private

The input text (may be filled during parse())

Definition at line 251 of file Parser.h.

Referenced by getInputText(), and parse().

◆ _root

std::unique_ptr<hit::Node> Parser::_root
private

The root node, which owns the whole tree.

Definition at line 245 of file Parser.h.

Referenced by parse(), queryRoot(), and queryRoot().

◆ _throw_on_error

bool Parser::_throw_on_error
private

Whether or not to throw on error.

Definition at line 260 of file Parser.h.

Referenced by getThrowOnError(), parseError(), and setThrowOnError().


The documentation for this class was generated from the following files: