Skip to content

Commit

Permalink
add check for too few arguments in operator parser
Browse files Browse the repository at this point in the history
  • Loading branch information
pantor committed Jul 10, 2022
1 parent 72f9012 commit 9f923b3
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 3 deletions.
2 changes: 1 addition & 1 deletion include/inja/node.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ class FunctionNode : public ExpressionNode {
Op operation;

std::string name;
int number_args; // Should also be negative -> -1 for unknown number
int number_args; // Can also be negative -> -1 for unknown number
std::vector<std::shared_ptr<ExpressionNode>> arguments;
CallbackFunction callback;

Expand Down
4 changes: 4 additions & 0 deletions include/inja/parser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ class Parser {
auto function = operator_stack.top();
operator_stack.pop();

if (static_cast<int>(arguments.size()) < function->number_args) {
throw_parser_error("too few arguments");
}

for (int i = 0; i < function->number_args; ++i) {
function->arguments.insert(function->arguments.begin(), arguments.back());
arguments.pop_back();
Expand Down
6 changes: 5 additions & 1 deletion single_include/inja/inja.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ class FunctionNode : public ExpressionNode {
Op operation;

std::string name;
int number_args; // Should also be negative -> -1 for unknown number
int number_args; // Can also be negative -> -1 for unknown number
std::vector<std::shared_ptr<ExpressionNode>> arguments;
CallbackFunction callback;

Expand Down Expand Up @@ -1490,6 +1490,10 @@ class Parser {
auto function = operator_stack.top();
operator_stack.pop();

if (static_cast<int>(arguments.size()) < function->number_args) {
throw_parser_error("too few arguments");
}

for (int i = 0; i < function->number_args; ++i) {
function->arguments.insert(function->arguments.begin(), arguments.back());
arguments.pop_back();
Expand Down
3 changes: 2 additions & 1 deletion test/test-functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ TEST_CASE("functions") {
CHECK(env.render("{{ 5^3 }}", data) == "125");
CHECK(env.render("{{ 5 + 12 + 4 * (4 - (1 + 1))^2 - 75 * 1 }}", data) == "-42");

// CHECK_THROWS_WITH(env.render("{{ +1 }}", data), "[inja.exception.render_error] (at 1:4) empty expression");
CHECK_THROWS_WITH(env.render("{{ +1 }}", data), "[inja.exception.parser_error] (at 1:7) too few arguments");
CHECK_THROWS_WITH(env.render("{{ 1 + }}", data), "[inja.exception.parser_error] (at 1:8) too few arguments");
}

SUBCASE("upper") {
Expand Down

0 comments on commit 9f923b3

Please sign in to comment.