Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a safe version of parsing broma files so that the code doesn't have to exit #7

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions include/ast.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -218,4 +218,13 @@ namespace broma {
return &*it;
}
};

/// @brief Used as a safety mechanism for parsing
// in other languages or on multiple threads.
typedef struct SafeRootResult {
void* result;
bool is_error;
} SafeRootResult;


} // namespace broma
6 changes: 6 additions & 0 deletions include/broma.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,10 @@ namespace broma {
///
/// @param fname The path of the file you want to parse, as a string.
Root parse_file(std::string const& fname);

/// @brief Parses a broma file safely by not exiting when the parser throws an error
/// @param fname The filename or path of the file you want to parse as a string.
/// @return A root result with a boolean value to check for errors.
SafeRootResult parse_file_safely(std::string const& fname);

}
24 changes: 24 additions & 0 deletions src/broma.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,28 @@ namespace broma {

return root;
}

SafeRootResult parse_file_safely(std::string const& fname){
file_input<> input(fname);

SafeRootResult result;

Root root;
ScratchData scratch;
parse<must<root_grammar>, run_action>(input, &root, &scratch);
post_process(root);

if (scratch.errors.size()) {
std::vector<char*>err_data;
for (auto&e : scratch.errors){
err_data.emplace_back(e.what());
}
result.result = reinterpret_cast<void*>(&err_data);
result.is_error = true;
} else {
result.result = reinterpret_cast<void*>(&root);
result.is_error = false;
}
return result;
}
} // namespace broma