Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
facontidavide committed Feb 5, 2025
1 parent 370133e commit c889394
Showing 1 changed file with 58 additions and 17 deletions.
75 changes: 58 additions & 17 deletions src/script_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,31 +67,72 @@ BT::Expected<Any> ParseScriptAndExecute(Ast::Environment& env, const std::string
}
}

Result ValidateScript(const std::string& script)
class SafeErrorReport
{
char error_msgs_buffer[2048];
mutable std::string error_buffer;
mutable std::size_t count = 0;

auto input = lexy::string_input<lexy::utf8_encoding>(script);
auto result =
lexy::parse<BT::Grammar::stmt>(input, ErrorReport().to(error_msgs_buffer));
if(result.has_value() && result.error_count() == 0)
struct _sink
{
try
std::string* buffer;
std::size_t* count;
using return_type = std::size_t;

template <typename Input, typename Reader, typename Tag>
void operator()(const lexy::error_context<Input>& context,
const lexy::error<Reader, Tag>& error)
{
std::vector<BT::Ast::ExprBase::Ptr> exprs = LEXY_MOV(result).value();
if(exprs.empty())
{
return nonstd::make_unexpected("Empty Script");
}
// valid script
return {};
*buffer += "error: while parsing ";
*buffer += context.production();
*buffer += "\n";
(*count)++;
}
catch(std::runtime_error& err)

std::size_t finish() &&
{
return nonstd::make_unexpected(err.what());
return *count;
}
};

public:
using return_type = std::size_t;

constexpr auto sink() const
{
return _sink{ &error_buffer, &count };
}
const std::string& get_errors() const
{
return error_buffer;
}
};

Result ValidateScript(const std::string& script)
{
auto input = lexy::string_input<lexy::utf8_encoding>(script);
SafeErrorReport error_report; // Replace char buffer with our safe handler

auto result = lexy::parse<BT::Grammar::stmt>(input, error_report);

if(!result.has_value() || result.error_count() != 0)
{
return nonstd::make_unexpected(error_report.get_errors());
}

try
{
std::vector<BT::Ast::ExprBase::Ptr> exprs = LEXY_MOV(result).value();
if(exprs.empty())
{
return nonstd::make_unexpected("Empty Script");
}
// valid script
return {};
}
catch(std::runtime_error& err)
{
return nonstd::make_unexpected(err.what());
}
return nonstd::make_unexpected(error_msgs_buffer);
}

} // namespace BT

0 comments on commit c889394

Please sign in to comment.