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 108 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 287 of file Parser.C.

289 : _root(nullptr),
290 _input_filenames(input_filenames),
291 _input_text(input_text ? *input_text : std::vector<std::string>()),
292 _cli_root(nullptr),
293 _throw_on_error(false)
294{
295 if (input_text && _input_filenames.size() != input_text->size())
296 mooseError("Parser: Input text not the same length as input filenames");
297}
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:258
const std::vector< std::string > _input_filenames
The input file names.
Definition Parser.h:255
std::unique_ptr< hit::Node > _cli_root
The root node for command line hit arguments.
Definition Parser.h:261
std::unique_ptr< hit::Node > _root
The root node, which owns the whole tree.
Definition Parser.h:252
bool _throw_on_error
Whether or not to throw on error.
Definition Parser.h:267

◆ 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 299 of file Parser.C.

301 : Parser(std::vector<std::string>{input_filename},
302 input_text ? std::optional<std::vector<std::string>>({*input_text})
303 : std::optional<std::vector<std::string>>())
304{
305}
Class for parsing input files.
Definition Parser.h:109

Member Function Documentation

◆ appendErrorMessages() [1/2]

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

Definition at line 628 of file Parser.C.

629{
630 appendErrorMessages(to, error.error_messages);
631}
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:621

◆ 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 621 of file Parser.C.

623{
624 to.insert(to.end(), from.begin(), from.end());
625}

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

◆ getAppType()

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

Definition at line 186 of file Parser.h.

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

◆ getCommandLineRoot() [1/2]

hit::Node & Parser::getCommandLineRoot ( )

Definition at line 615 of file Parser.C.

616{
617 return const_cast<hit::Node &>(std::as_const(*this).getCommandLineRoot());
618}

◆ 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 607 of file Parser.C.

608{
610 mooseError("Parser::getCommandLineRoot(): command line root is not set");
611 return *queryCommandLineRoot();
612}
const hit::Node * queryCommandLineRoot() const
Definition Parser.h:159

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 227 of file Parser.h.

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

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

◆ getInputFileNames()

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

Definition at line 176 of file Parser.h.

176{ return _input_filenames; }

Referenced by parse().

◆ getInputText()

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

Definition at line 181 of file Parser.h.

181{ return _input_text; }

Referenced by parse().

◆ getLastInputFileName()

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

Definition at line 430 of file Parser.C.

431{
432 if (_input_filenames.empty())
433 mooseError("Parser::getLastInputFileName(): No inputs are set");
434 return _input_filenames.back();
435}

Referenced by getLastInputFilePath().

◆ getLastInputFilePath()

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

Definition at line 206 of file Parser.h.

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

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 599 of file Parser.C.

600{
601 if (!queryRoot())
602 mooseError("Parser::getRoot(): root is not set");
603 return *queryRoot();
604}
const hit::Node * queryRoot() const
Definition Parser.h:142

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 220 of file Parser.h.

220{ 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 634 of file Parser.C.

635{
636 std::vector<std::string> values;
637 for (const auto & em : error_messages)
638 values.push_back(em.prefixed_message);
639 return MooseUtils::stringJoin(values, "\n");
640}
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 443 of file Parser.C.

444{
445 mooseAssert(!_root && !_cli_root, "Has already parsed");
446
447 if (getInputFileNames().size() > 1)
448 mooseInfo("Merging inputs ", Moose::stringify(getInputFileNames()));
449
450 // Correct filenames (default is to use real path)
451 const std::string use_rel_paths_str =
452 std::getenv("MOOSE_RELATIVE_FILEPATHS") ? std::getenv("MOOSE_RELATIVE_FILEPATHS") : "false";
453 const auto use_real_paths = use_rel_paths_str == "0" || use_rel_paths_str == "false";
454 std::vector<std::string> filenames;
455 for (const auto & filename : getInputFileNames())
456 filenames.push_back(use_real_paths ? MooseUtils::realpath(filename) : filename);
457
458 // Load each input file if text was not provided
459 if (_input_text.empty())
460 for (const auto & filename : filenames)
461 {
462 MooseUtils::checkFileReadable(filename, true);
463 std::ifstream f(filename);
464 _input_text.push_back(
465 std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()));
466 }
467
468 CompileParamWalker::ParamMap override_map;
469 CompileParamWalker cpw(override_map);
470 OverrideParamWalker opw(override_map);
471
472 // Errors from the duplicate param walker, ran within each input
473 // independently first
474 std::vector<hit::ErrorMessage> dw_errors;
475
476 for (const auto i : index_range(getInputFileNames()))
477 {
478 const auto & filename = filenames[i];
479 const auto & input = getInputText()[i];
480
481 try
482 {
483 // provide stream to hit parse function to capture any syntax errors,
484 // set parser root node, then throw those errors if any were captured
485 std::vector<hit::ErrorMessage> syntax_errors;
486 std::unique_ptr<hit::Node> root(hit::parse(filename, input, &syntax_errors));
487
489 root->walk(&dw, hit::NodeType::Field);
490 appendErrorMessages(dw_errors, dw.errors);
491
492 if (!queryRoot())
493 _root = std::move(root);
494 else
495 {
496 root->walk(&opw, hit::NodeType::Field);
497 hit::merge(root.get(), &getRoot());
498 }
499
500 if (!syntax_errors.empty())
501 throw Parser::Error(syntax_errors);
502
503 getRoot().walk(&cpw, hit::NodeType::Field);
504 }
505 catch (hit::Error & err)
506 {
507 parseError(err.error_messages);
508 }
509 }
510
511 // warn about overridden parameters in multiple inputs
512 if (!opw.warnings.empty())
513 mooseInfo(Moose::stringify(opw.warnings), "\n");
514
515 // If we don't have a root (allow no input files),
516 // create an empty one
517 if (!queryRoot())
518 _root.reset(hit::parse("EMPTY", ""));
519
520 {
522 getRoot().walk(&bw, hit::NodeType::Section);
523 if (bw.errors.size())
524 parseError(bw.errors);
525 }
526
527 {
528 FindAppWalker fw;
529 getRoot().walk(&fw, hit::NodeType::Field);
530 if (fw.getApp())
531 setAppType(*fw.getApp());
532 }
533
534 // Duplicate parameter errors (within each input file)
535 if (dw_errors.size())
536 parseError(dw_errors);
537
538 // Merge in command line HIT arguments
539 const auto joined_params =
541 try
542 {
543 _cli_root.reset(hit::parse("CLI_ARGS", joined_params));
544 hit::merge(&getCommandLineRoot(), &getRoot());
545 }
546 catch (hit::Error & err)
547 {
548 parseError(err.error_messages);
549 }
550
551 std::vector<hit::ErrorMessage> errors;
552
553 // expand ${bla} parameter values and mark/include variables
554 // used in expansion as "used" (obtained later by the Builder
555 // with getExtractedVars())
556 {
557 hit::RawEvaler raw;
558 hit::EnvEvaler env;
559 hit::ReplaceEvaler repl;
560 FuncParseEvaler fparse_ev;
561 UnitsConversionEvaler units_ev;
562 EnumerateEvaler enumerate_ev;
563 RangeEvaler range_ev;
564 RepeatEvaler repeat_ev;
565 hit::BraceExpander exw;
566 exw.registerEvaler("raw", raw);
567 exw.registerEvaler("env", env);
568 exw.registerEvaler("fparse", fparse_ev);
569 exw.registerEvaler("replace", repl);
570 exw.registerEvaler("units", units_ev);
571 exw.registerEvaler("enumerate", enumerate_ev);
572 exw.registerEvaler("range", range_ev);
573 exw.registerEvaler("repeat", repeat_ev);
574 getRoot().walk(&exw);
575 for (auto & var : exw.used)
576 _extracted_vars.insert(var);
577 Parser::appendErrorMessages(errors, exw.errors);
578 }
579
580 // Collect duplicate parameters now that we've merged inputs
581 {
583 getRoot().walk(&dw, hit::NodeType::Field);
585 }
586
587 // Check bad active now that we've merged inputs
588 {
590 getRoot().walk(&bw, hit::NodeType::Section);
592 }
593
594 if (errors.size())
595 parseError(errors);
596}
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:75
virtual void walk(const std::string &, const std::string &, hit::Node *section) override
Definition Parser.C:354
std::map< std::string, hit::Node * > ParamMap
Definition Parser.h:81
virtual void walk(const std::string &fullpath, const std::string &, hit::Node *n) override
Definition Parser.C:308
std::vector< hit::ErrorMessage > errors
Definition Parser.h:63
const std::optional< std::string > & getApp()
Definition Parser.C:416
void walk(const std::string &, const std::string &, hit::Node *n) override
Definition Parser.C:411
void setAppType(const std::string &app_type)
Definition Parser.h:191
const hit::Node & getCommandLineRoot() const
Definition Parser.C:607
const std::vector< std::string > & getInputText() const
Definition Parser.h:181
const std::vector< std::string > & getInputFileNames() const
Definition Parser.h:176
std::optional< std::vector< std::string > > _command_line_params
The command line HIT parameters (if any)
Definition Parser.h:270
void parseError(std::vector< hit::ErrorMessage > messages) const
Helper for throwing an error with the given messages.
Definition Parser.C:643
hit::Node & getRoot()
Definition Parser.C:599
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:317
std::string stringify(const T &t)
conversion to string
Definition Conversion.h:65
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 643 of file Parser.C.

644{
645 // Few things about command line arguments...
646 // 1. We don't care to add line and column context for CLI args, because
647 // it doesn't make sense. We go from the full CLI args and pull out
648 // the HIT parameters so "line" 1 might not even be command line
649 // argument 1. So, remove line/column context from all CLI args.
650 // 2. Whenever we have a parameter in input that then gets overridden
651 // by a command line argument, under the hood we're merging two
652 // different HIT trees. However, WASP doesn't currently update the
653 // "filename" context for the updated parameter. Which means that
654 // a param that is in input and then overridden by CLI will have
655 // its location as in input. Which isn't true. So we get around this
656 // by searching the independent CLI args tree for params that we have
657 // errors for. If the associated path is also in CLI args, we manually
658 // set its error to come from CLI args. This should be fixed in
659 // the future with a WASP update.
660 for (auto & em : messages)
661 if (em.node && queryCommandLineRoot())
662 if (getCommandLineRoot().find(em.node->fullpath()))
663 em = hit::ErrorMessage(em.message, "CLI_ARGS");
664
665 if (_throw_on_error)
666 throw Parser::Error(messages);
667 else
668 mooseError(joinErrorMessages(messages));
669}
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:634
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 160 of file Parser.h.

160{ 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 159 of file Parser.h.

159{ return _cli_root.get(); }

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

◆ queryRoot() [1/2]

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

Definition at line 143 of file Parser.h.

143{ 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 142 of file Parser.h.

142{ return _root.get(); }

Referenced by getRoot(), and parse().

◆ setAppType()

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

Definition at line 191 of file Parser.h.

191{ _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 423 of file Parser.C.

424{
425 mooseAssert(!_command_line_params, "Already set");
426 _command_line_params = params;
427}

◆ 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 213 of file Parser.h.

213{ _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 264 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 261 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 270 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 273 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 255 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 258 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 252 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 267 of file Parser.h.

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


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