Skip to content
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
17 changes: 17 additions & 0 deletions compiler/back_end/cpp/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,17 @@ emboss_cc_test(
],
)

emboss_cc_test(
name = "division_modulus_test",
srcs = [
"testcode/division_modulus_test.cc",
],
deps = [
"//testdata:division_modulus_emboss",
"@com_google_googletest//:gtest_main",
],
)

emboss_cc_test(
name = "auto_array_size_test",
srcs = [
Expand Down Expand Up @@ -488,6 +499,12 @@ cpp_golden_test(
golden_file = "//testdata/golden_cpp:cpp_namespace.emb.h",
)

cpp_golden_test(
name = "division_modulus_golden_test",
emb_file = "//testdata:division_modulus.emb",
golden_file = "//testdata/golden_cpp:division_modulus.emb.h",
)

cpp_golden_test(
name = "dynamic_size_golden_test",
emb_file = "//testdata:dynamic_size.emb",
Expand Down
2 changes: 2 additions & 0 deletions compiler/back_end/cpp/header_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,8 @@ def _builtin_function_name(function):
ir_data.FunctionMapping.ADDITION: "Sum",
ir_data.FunctionMapping.SUBTRACTION: "Difference",
ir_data.FunctionMapping.MULTIPLICATION: "Product",
ir_data.FunctionMapping.FLOOR_DIVISION: "FlooringQuotient",
ir_data.FunctionMapping.MODULUS: "FlooringRemainder",
ir_data.FunctionMapping.EQUALITY: "Equal",
ir_data.FunctionMapping.INEQUALITY: "NotEqual",
ir_data.FunctionMapping.AND: "And",
Expand Down
94 changes: 94 additions & 0 deletions compiler/back_end/cpp/testcode/division_modulus_test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Tests for the `//` (flooring integer division) and `%` (flooring modulus)
// operators in generated C++ code.
#include <array>
#include <cstdint>

#include "gtest/gtest.h"
#include "testdata/division_modulus.emb.h"

namespace emboss {
namespace test {
namespace {

// Constant-folded virtual fields match the design doc's sign table.
TEST(Constants, ConstantFoldedQuotients) {
EXPECT_EQ(20, Constants::exact_quotient());
EXPECT_EQ(14, Constants::truncating_quotient()); // 100 // 7
// (-7) // 2 == -4 (flooring), not -3 (truncating).
EXPECT_EQ(-4, Constants::negative_quotient());
}

TEST(Constants, ConstantFoldedRemainders) {
EXPECT_EQ(0, Constants::exact_modulus());
EXPECT_EQ(2, Constants::truncating_modulus()); // 100 % 7
// (-7) % 2 == 1 (flooring: result takes the sign of the divisor).
EXPECT_EQ(1, Constants::negative_modulus());
}

TEST(Constants, Chained) {
EXPECT_EQ(10, Constants::chained_div()); // 100 // 5 // 2 == 20 // 2
EXPECT_EQ(3, Constants::chained_mod()); // 17 % 7 % 4 == 3 % 4
EXPECT_EQ(1, Constants::mixed_divmod()); // 17 % 7 // 2 == 3 // 2
}

// A field whose size depends on `//`.
TEST(ArrayOfUint16BySizeInBytes, EvenSizeUsesAllBytes) {
static constexpr ::std::array</**/ ::std::uint8_t, 7> kBuf = {{
0x06, // size_in_bytes = 6 -> (6 // 2) * 2 = 6 bytes
0x01, 0x00, // elements[0] = 1
0x02, 0x00, // elements[1] = 2
0x03, 0x00, // elements[2] = 3
}};
auto view = MakeArrayOfUint16BySizeInBytesView(&kBuf);
ASSERT_TRUE(view.Ok());
EXPECT_EQ(7U, view.SizeInBytes());
EXPECT_EQ(3U, view.elements().ElementCount());
EXPECT_EQ(1U, view.elements()[0].Read());
EXPECT_EQ(3U, view.elements()[2].Read());
}

// Odd size_in_bytes: the trailing odd byte is excluded because (n // 2) * 2
// rounds down to a multiple of 2.
TEST(ArrayOfUint16BySizeInBytes, OddSizeRoundsDown) {
static constexpr ::std::array</**/ ::std::uint8_t, 5> kBuf = {{
0x05, // size_in_bytes = 5 -> (5 // 2) * 2 = 4 bytes
0x01, 0x00, // elements[0] = 1
0x02, 0x00, // elements[1] = 2
}};
auto view = MakeArrayOfUint16BySizeInBytesView(&kBuf);
ASSERT_TRUE(view.Ok());
EXPECT_EQ(5U, view.SizeInBytes());
EXPECT_EQ(2U, view.elements().ElementCount());
}

// ChunkedPayload exercises `((n + 3) // 4) * 4` (round up to a multiple of 4).
TEST(ChunkedPayload, RoundsUpToMultipleOfFour) {
static constexpr ::std::array</**/ ::std::uint8_t, 9> kBuf = {{
0x05, // chunk_count = 5
0x11, 0x22, 0x33, 0x44, 0x55, // 5 used bytes
0x00, 0x00, 0x00, // 3 padding bytes -> 8 total
}};
auto view = MakeChunkedPayloadView(&kBuf);
ASSERT_TRUE(view.Ok());
// ((5 + 3) // 4) * 4 == 8 bytes of payload, plus the 1-byte count = 9 total.
EXPECT_EQ(9U, view.SizeInBytes());
EXPECT_EQ(8U, view.padded().ElementCount());
}

} // namespace
} // namespace test
} // namespace emboss
52 changes: 52 additions & 0 deletions compiler/front_end/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,52 @@ def _check_bounds_on_runtime_integer_expressions(
errors += _integer_bounds_errors_for_expression(expression, source_file_name)


def _check_division_and_modulus_have_nonzero_divisors(
expression, source_file_name, errors
):
"""Rejects `l // r` and `l % r` whose divisor range could contain zero.

This is the initial, strict rollout of `//` and `%`: because the expression
type system does not yet track an `undefined` value, the only sound option
for a divisor whose range includes zero is to reject it at compile time. A
later change will loosen this to allow a *possibly*-zero divisor to propagate
an `undefined` value, keeping the error only for a *provably*-zero divisor.
"""
if expression.which_expression != "function":
return
op = expression.function.function
if op not in (
ir_data.FunctionMapping.FLOOR_DIVISION,
ir_data.FunctionMapping.MODULUS,
):
return
divisor = expression.function.args[1]
if divisor.type.which_type != "integer":
return
rmin = divisor.type.integer.minimum_value
rmax = divisor.type.integer.maximum_value
rmin_le_zero = rmin == "-infinity" or int(rmin) <= 0
rmax_ge_zero = rmax == "infinity" or int(rmax) >= 0
if rmin_le_zero and rmax_ge_zero:
op_text = expression.function.function_name.text
errors.append(
[
error.error(
source_file_name,
expression.source_location,
"Right argument of '{}' cannot be zero.".format(op_text),
),
error.note(
source_file_name,
divisor.source_location,
"Divisor range is {} to {}, which includes zero.".format(
rmin, rmax
),
),
]
)


def _attribute_in_attribute_action(a):
return {"in_attribute": a}

Expand Down Expand Up @@ -818,6 +864,12 @@ def check_constraints(ir):
skip_descendants_of={ir_data.EnumValue, ir_data.Expression},
parameters={"errors": errors, "in_attribute": None},
)
traverse_ir.fast_traverse_ir_top_down(
ir,
[ir_data.Expression],
_check_division_and_modulus_have_nonzero_divisors,
parameters={"errors": errors},
)
traverse_ir.fast_traverse_ir_top_down(
ir,
[ir_data.RuntimeParameter],
Expand Down
42 changes: 42 additions & 0 deletions compiler/front_end/constraints_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,48 @@ def test_no_error_on_ok_missing_outer_array_size(self):
ir = _make_ir_from_emb("struct Foo:\n" " 0 [+1] UInt:8[1][] one_byte\n")
self.assertEqual([], constraints.check_constraints(ir))

def test_no_error_on_division_by_positive_constant(self):
ir = _make_ir_from_emb(
"struct Foo:\n" " 0 [+1] UInt x\n" " let half = x // 2\n"
)
self.assertEqual([], constraints.check_constraints(ir))

def test_no_error_on_modulus_by_positive_constant(self):
ir = _make_ir_from_emb(
"struct Foo:\n" " 0 [+1] UInt x\n" " let r = x % 4\n"
)
self.assertEqual([], constraints.check_constraints(ir))

def test_error_on_division_with_divisor_range_including_zero(self):
ir = _make_ir_from_emb(
"struct Foo:\n"
" 0 [+1] UInt divisor\n"
" 1 [+1] UInt dividend\n"
" let q = dividend // divisor\n"
)
errors = error.filter_errors(constraints.check_constraints(ir))
self.assertEqual(1, len(errors))
self.assertIn("Right argument of '//' cannot be zero.", errors[0][0].message)

def test_error_on_modulus_with_divisor_range_including_zero(self):
ir = _make_ir_from_emb(
"struct Foo:\n"
" 0 [+1] UInt divisor\n"
" 1 [+1] UInt dividend\n"
" let r = dividend % divisor\n"
)
errors = error.filter_errors(constraints.check_constraints(ir))
self.assertEqual(1, len(errors))
self.assertIn("Right argument of '%' cannot be zero.", errors[0][0].message)

def test_error_on_division_by_zero_literal(self):
ir = _make_ir_from_emb(
"struct Foo:\n" " 0 [+1] UInt x\n" " let q = x // 0\n"
)
errors = error.filter_errors(constraints.check_constraints(ir))
self.assertEqual(1, len(errors))
self.assertIn("Right argument of '//' cannot be zero.", errors[0][0].message)

def test_no_error_on_dynamically_sized_struct_in_dynamically_sized_field(self):
ir = _make_ir_from_emb(
"struct Foo:\n"
Expand Down
Loading
Loading