Skip to content

deprecate bitwise or in favor of bitor (+ other bitwise operators); withBitOperators macro #102

@timotheecour

Description

@timotheecour

this is super error prone [1], another gotcha to learn, can complicate generic code in some cases, and makes it harder to search.

These should be deprecated in favor of bitor, etc.
These are some examples:

proc `or`*(x, y: int): int {.magic: "BitorI", noSideEffect.}
proc `xor`*(x, y: int): int {.magic: "BitxorI", noSideEffect.}
proc `not`*[T: SomeUnsignedInt](x: T): T {.magic: "BitnotI", noSideEffect.}
proc `and`*[T: SomeUnsignedInt](x, y: T): T {.magic: "BitandI", noSideEffect.}
proc `xor`*[T: SomeUnsignedInt](x, y: T): T {.magic: "BitxorI", noSideEffect.}
proc `not`*(x: int): int {.magic: "BitnotI", noSideEffect.}

proposal:

  • every proc foo defined with .magic: "BitXXX" is deprecated and aliased to a proc named bitfoo
  • eventually will become an error
  • EDIT define a withBitOperators template that allows using C-style operators | & ^ ~ or short names or etc in a scope (benefit: doesn't pollute namespace, makes it clear when bitwise operations are used; also, withBitOperators can be used in manually porting code after this deprecation as an alternative to nimfix):
withBitOperators: # defines C-style | & ^ ~
  let a1 = 1 | 2 # only valid in scope
  let a2 = 1 or 2 # only valid in scope
  let a3 = 1 bitor 2 # this still works

NOTE: this withBitOperators idea was inspired by this: https://forum.nim-lang.org/t/1188#7366 that defines pointer arithmetics

ptrMath:
    var a: array[0..3, int]
    for i in a.low..a.high:
      a[i] += i
    var p = addr(a[0])
    p += 1
    p[0] -= 2
    echo p[0], " ", p[1]

EDIT added this:
[1] error prone behavior: this code delete both files instead of just 1, because execCmd returns by int status instead of bool (success/fail), so bitwise semantics are used instead of logical semantics, and and or don't short-circuit in this case.

import osproc
echo execCmd("grep DELETEME foo.txt") and execCmd("rm foo.txt") or execCmd("rm backup.txt")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions