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

libexpr: add modulo operator #12617

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions doc/manual/redirects.js
Original file line number Diff line number Diff line change
@@ -208,6 +208,7 @@ const redirects = {
"builtin-listToAttrs": "language/builtins.html#builtins-listToAttrs",
"builtin-map": "language/builtins.html#builtins-map",
"builtin-match": "language/builtins.html#builtins-match",
"builtin-mod": "language/builtins.html#builtins-mod",
"builtin-mul": "language/builtins.html#builtins-mul",
"builtin-parseDrvName": "language/builtins.html#builtins-parseDrvName",
"builtin-path": "language/builtins.html#builtins-path",
2 changes: 2 additions & 0 deletions doc/manual/source/language/operators.md
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@
| List concatenation | *list* `++` *list* | right | 5 |
| [Multiplication][arithmetic] | *number* `*` *number* | left | 6 |
| [Division][arithmetic] | *number* `/` *number* | left | 6 |
| [Modulo][arithmetic] | *number* `%` *number* | left | 6 |
| [Subtraction][arithmetic] | *number* `-` *number* | left | 7 |
| [Addition][arithmetic] | *number* `+` *number* | left | 7 |
| [String concatenation] | *string* `+` *string* | left | 7 |
@@ -88,6 +89,7 @@ Pure integer operations will always return integers, whereas any operation invol

Evaluation of the following numeric operations throws an evaluation error:
- Division by zero
- Modulo by zero
- Integer overflow, that is, any operation yielding a result outside of the representable range of [Nix language integers](./syntax.md#number-literal)

See also [Comparison] and [Equality].
18 changes: 18 additions & 0 deletions src/libexpr-tests/error_traces.cc
Original file line number Diff line number Diff line change
@@ -1044,6 +1044,24 @@ namespace nix {
}


TEST_F(ErrorTraceTest, mod) {
ASSERT_TRACE2("mod \"foo\" 1",
TypeError,
HintFmt("expected an integer but found %s: %s", "a string", Uncolored(ANSI_MAGENTA "\"foo\"" ANSI_NORMAL)),
HintFmt("while evaluating the first operand of the modulo"));

ASSERT_TRACE2("mod 1 \"foo\"",
TypeError,
HintFmt("expected an integer but found %s: %s", "a string", Uncolored(ANSI_MAGENTA "\"foo\"" ANSI_NORMAL)),
HintFmt("while evaluating the second operand of the modulo"));

ASSERT_TRACE1("mod \"foo\" 0",
EvalError,
HintFmt("modulo by zero"));

}


TEST_F(ErrorTraceTest, bitAnd) {
ASSERT_TRACE2("bitAnd 1.1 2",
TypeError,
24 changes: 24 additions & 0 deletions src/libexpr-tests/primops.cc
Original file line number Diff line number Diff line change
@@ -503,6 +503,30 @@ namespace nix {
ASSERT_THROW(eval("builtins.div 5.0 0.0"), EvalError);
}

TEST_F(PrimOpTest, modPosPos) {
auto v = eval("builtins.mod 5 2");
ASSERT_THAT(v, IsIntEq(1));
}

TEST_F(PrimOpTest, modPosNeg) {
auto v = eval("builtins.mod 5 (-2)");
ASSERT_THAT(v, IsIntEq(1));
}

TEST_F(PrimOpTest, modNegPos) {
auto v = eval("builtins.mod (-5) 2");
ASSERT_THAT(v, IsIntEq(-1));
}

TEST_F(PrimOpTest, modNegNeg) {
auto v = eval("builtins.mod (-5) (-2)");
ASSERT_THAT(v, IsIntEq(-1));
}

TEST_F(PrimOpTest, modZero) {
ASSERT_THROW(eval("builtins.mod 5 0"), EvalError);
}

TEST_F(PrimOpTest, bitOr) {
auto v = eval("builtins.bitOr 1 2");
ASSERT_THAT(v, IsIntEq(3));
1 change: 1 addition & 0 deletions src/libexpr/eval.cc
Original file line number Diff line number Diff line change
@@ -238,6 +238,7 @@ EvalState::EvalState(
.lessThan = symbols.create("__lessThan"),
.mul = symbols.create("__mul"),
.div = symbols.create("__div"),
.mod = symbols.create("__mod"),
.or_ = symbols.create("or"),
.findFile = symbols.create("__findFile"),
.nixPath = symbols.create("__nixPath"),
2 changes: 1 addition & 1 deletion src/libexpr/nixexpr.hh
Original file line number Diff line number Diff line change
@@ -80,7 +80,7 @@ std::string showAttrPath(const SymbolTable & symbols, const AttrPath & attrPath)
struct Expr
{
struct AstSymbols {
Symbol sub, lessThan, mul, div, or_, findFile, nixPath, body;
Symbol sub, lessThan, mul, div, mod, or_, findFile, nixPath, body;
};


2 changes: 2 additions & 0 deletions src/libexpr/parser.y
Original file line number Diff line number Diff line change
@@ -173,6 +173,7 @@ static Expr * makeCall(PosIdx pos, Expr * fn, Expr * arg) {
%left NOT
%left '+' '-'
%left '*' '/'
%left '%'
%right CONCAT
%nonassoc '?'
%nonassoc NEGATE
@@ -259,6 +260,7 @@ expr_op
| expr_op '-' expr_op { $$ = new ExprCall(state->at(@2), new ExprVar(state->s.sub), {$1, $3}); }
| expr_op '*' expr_op { $$ = new ExprCall(state->at(@2), new ExprVar(state->s.mul), {$1, $3}); }
| expr_op '/' expr_op { $$ = new ExprCall(state->at(@2), new ExprVar(state->s.div), {$1, $3}); }
| expr_op '%' expr_op { $$ = new ExprCall(state->at(@2), new ExprVar(state->s.mod), {$1, $3}); }
| expr_op CONCAT expr_op { $$ = new ExprOpConcatLists(state->at(@2), $1, $3); }
| expr_app
;
30 changes: 30 additions & 0 deletions src/libexpr/primops.cc
Original file line number Diff line number Diff line change
@@ -3951,6 +3951,36 @@ static RegisterPrimOp primop_div({
.fun = prim_div,
});

static void prim_mod(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto i2 = state.forceInt(*args[1], pos, "while evaluating the second operand of the modulo");

if (i2.value == 0)
state.error<EvalError>("modulo by zero").atPos(pos).debugThrow();

auto i1 = state.forceInt(*args[0], pos, "while evaluating the first operand of the modulo");

v.mkInt(i1.value % i2.value);
}

static RegisterPrimOp primop_mod({
.name = "__mod",
.args = {"e1", "e2"},
.doc = R"(
Return the remainder of the division of the numbers *e1* and *e2*.

Fails when *e2* is zero - in this case the result is undefined.

The modulo operator matches division in behavior - the following identity is always true (assuming integer division):
```nix
a == b * (a / b) + (a % b)
```

Following that, the outcome is **negative**, when exactly one of *e1* or *e2* evaluates to a negative number.
)",
.fun = prim_mod,
});

static void prim_bitAnd(EvalState & state, const PosIdx pos, Value * * args, Value & v)
{
auto i1 = state.forceInt(*args[0], pos, "while evaluating the first argument passed to builtins.bitAnd");