proposal: Go 2: add a built-in tilde ~ (bitwise not) unary operator (op: OBITNOT -> OCOM), deprecate ^x (XOR) usage #46847
Labels
FrozenDueToAge
LanguageChange
Proposal
v2
A language change or incompatible library change
WaitingForInfo
Issue is not actionable because of missing required information, which needs to be provided.
Milestone
TL;DR: I propose adding built-in support for
~
(bitwise not) unary operator and deprecate of ^x (XOR) usageAbstract
The
~
operator (pronounced as tilde) is a complement (unary) operator, performs a bitwise NOT operation. It takes one-bit operand and returns its complement. If the operand is 1, it returns 0, and if it is 0, it returns 1. When applied to numbers, represented by bitwise not, it changes the number’s sign and then subtracts one. *For example:
I propose the addition of a new built-in
~
operator.Motivation
Currently, AFAIK,
go1.16.4
does not have support for~
operator. I could find neither an actively discussing issue nor a PR. It is a great opportunity to learn compiler theory and get used to Go compiler internals.Backgroud
Tilde
~
operator widely implemented and used by some programming languages. (i.e. Python, C/C++, Java, Rust (!), etc.). Can be used for different purposes in every programming language. We can start implementing this as a unary operator. In the some programming languages, the tilde character is used as a bitwise NOT operator, following the notation in logic:~p
not means notp
, wherep
is a proposition.Proposal
I propose that
~
should work like any other bitwise operator as described in the spec. We will only support prefix notation usage on integers. i.e.~EXPR
. Following codes should compile successfully, as^
already does.~1997 // returns -1998
a := 7 and ~a // returns -8
~-15 // returns 14
-~15 // returns 16
foo := func(x int) int { return ~x } and ~foo(707) // returns -708
if ~7 < 5 { // true }
~3.1415 // INVALID
x ~= y // INVALID
~bool // INVALID
5~7 // INVALID
7~ // INVALID
Compatibility
We should no longer allow
^EXPR
usage. To be more aligned with the usage of the unary syntax just like in other languages. Which will cause language change.Complexity
Since we will add just another single unary operator to the compiler, I think it will not cause even the tiny complexity. The compiler already supports other bitwise operations. (i.e. &, | ,^, &^), and
^
for bitwise not. EspeciallyOBITNOT
operator in the compiler.Implementation
At a minimum this will impact:
Furthermore
After implementation for integers, we may also add different features for this operator, in the future:
Additional Notes
I'm trying to write a new blog post about "How to contribute to Go Compiler". What I want to demonstrate is how can we add a new operator, how to write a discussion proposal, how to contribute to Go. Your feedbacks are valuable. Thanks.
The text was updated successfully, but these errors were encountered: