1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: ensure that << and >> has higher precedence in the generated C code, than arithmetic operations (diff between C and V precedences) (#18814)

This commit is contained in:
Delyan Angelov 2023-07-08 07:02:32 +03:00 committed by GitHub
parent 17b576227f
commit 54635185c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 0 deletions

View File

@ -35,8 +35,17 @@ fn (mut g Gen) infix_expr(node ast.InfixExpr) {
g.infix_expr_arithmetic_op(node)
}
.left_shift {
// `a << b` can mean many things in V ...
// TODO: disambiguate everything in the checker; cgen should not decide all this.
// Instead it should be as simple, as the branch for .right_shift is.
// `array << val` should have its own separate operation internally.
g.infix_expr_left_shift_op(node)
}
.right_shift {
g.write('(')
g.gen_plain_infix_expr(node)
g.write(')')
}
.and, .logical_or {
g.infix_expr_and_or_op(node)
}
@ -846,7 +855,9 @@ fn (mut g Gen) infix_expr_left_shift_op(node ast.InfixExpr) {
}
}
} else {
g.write('(')
g.gen_plain_infix_expr(node)
g.write(')')
}
}

View File

@ -1,5 +1,21 @@
type MyInt = int
fn test_shift_left_precedence() {
x := u32(20)
base := u32(1)
shift := u32(3)
assert x + base << shift == (x + (base << shift)), '<< should have higher precedence than +'
assert x - base << shift == (x - (base << shift)), '<< should have higher precedence than -'
}
fn test_shift_right_precedence() {
x := u32(20)
base := u32(100)
shift := u32(2)
assert x + base >> shift == (x + (base >> shift)), '>> should have higher precedence than +'
assert x - base >> shift == (x - (base >> shift)), '>> should have higher precedence than -'
}
fn test_shift_operators() {
// check that shift works with all integer types
// as the right-hand side operand