Skip to content

Commit

Permalink
patch division by zero crash
Browse files Browse the repository at this point in the history
  • Loading branch information
Prevter committed Aug 3, 2024
1 parent fe40868 commit 39962f6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/value.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,23 +142,42 @@ namespace rift {

// If either value is a boolean, convert them to integers and divide them.
if (m_type == Type::Boolean || other.m_type == Type::Boolean) {
// check for division by zero
if (other.m_integer == 0) {
return Value::floating(std::numeric_limits<float>::infinity());
}
return Value::integer(m_integer / other.m_integer);
}

// If both values are numbers, divide them.
if (m_type == Type::Integer && other.m_type == Type::Integer) {
// check for division by zero
if (other.m_integer == 0) {
return Value::floating(std::numeric_limits<float>::infinity());
}
return Value::integer(m_integer / other.m_integer);
}

if (m_type == Type::Float && other.m_type == Type::Float) {
// check for division by zero
if (other.m_float == 0) {
return Value::floating(std::numeric_limits<float>::infinity());
}
return Value::floating(m_float / other.m_float);
}

// If one of the values is a float, convert the other to a float and divide them.
if (m_type == Type::Float) {
// check for division by zero
if (other.toFloat() == 0) {
return Value::floating(std::numeric_limits<float>::infinity());
}
return Value::floating(m_float / other.toFloat());
}

if (other.toFloat() == 0) {
return Value::floating(std::numeric_limits<float>::infinity());
}
return Value::floating(toFloat() / other.toFloat());
}

Expand Down
2 changes: 2 additions & 0 deletions test/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,11 @@ int main() {
"Ternary test: World!",
{ VALUE("number", 2), VALUE("name", "World") });

RIFT_TEST_CASE("{ 2 + }", "<ParseError: Expected number, string, identifier, or '(' at index 6>");
RIFT_TEST_CASE("{snake_case_variable}", "Hi!", { VALUE("snake_case_variable", "Hi!") });
RIFT_TEST_CASE("2 + 2 * 2 = {2 + 2 * 2}!", "2 + 2 * 2 = 6!");
RIFT_TEST_CASE("sqrt(4): {sqrt(4)}", "sqrt(4): 2.00");
RIFT_TEST_CASE("{0 / 0} {10 / false}", "inf inf"); // integer division by zero should not crash
RIFT_TEST_CASE("2 + 2 * {number} = {2 + 2 * number}!", "2 + 2 * 3 = 8!", { VALUE("number", 3) });
RIFT_TEST_CASE("Is 2 + 2 equal to 4? {2 + 2 == 4}!", "Is 2 + 2 equal to 4? true!");
RIFT_TEST_CASE("Is 2 + 2 equal to 4? {2 + 2 == 4 ? 'Yes' : 'No'}!", "Is 2 + 2 equal to 4? Yes!");
Expand Down

0 comments on commit 39962f6

Please sign in to comment.