focusaurus / atom-format-shell

Format shell script from within atom text editor
MIT License
6 stars 1 forks source link

[v2.1.6] Bitwise negation operator not recognized in numerical expressions #9

Closed leagris closed 5 years ago

leagris commented 5 years ago

format-shell version 2.1.6 fails with:

format-shell failed with code 1.
:2:13: not a valid arithmetic operator: 0

On the code below

#!/usr/bin/env bash
echo "$(( ~ 0 ))"

because it does not recognize the ~ as the binary negation operator in a numerical expression

See: Bash Man-Page / 6.5 Shell Arithmetic

Here is a practical use of the negation operator to compute a CRC32 checksum in pure Bash without a lookup table, that is causing shell-format to choke on the operator

crc32_string() {
  local -i i byte cur_crc crc=0xFFFFFFFF
  for ((i = 0; i < ${#1}; i++)); do
    byte=$(printf '%d' "'${1:i:1}") # Get byte value of character at i
    cur_crc=$(
      # This numerical expression causes shell-format 2.1.6 to fail with code 1: 
      # reached ( without matching ( with )
      ((cur_byte = ( ~ (crc ^ byte) & 0xFF))) )
      for _ in {0..7}; do
        ((lsb = cur_byte & 0x01))
        ((cur_byte = (cur_byte >> 1) & 0x7FFFFFFF))
        [[ $lsb -eq 0 ]] && ((cur_byte = cur_byte ^ 0xEDB88320))
      done
      echo -n "${cur_byte}"
    )
    ((crc = (cur_crc ^ (crc >> 8)) & 0xFFFFFFFF))

  done
  echo $((crc ^ 0xFFFFFFFF))
}

printf 'The CRC32 of: %s\nis: %08x\n' "${1}" "$(crc32_string "${1}")"

# crc32_string "The quick brown fox jumps over the lazy dog"
# yields 414fa339
focusaurus commented 5 years ago

Thanks for the report @leagris . This repo is for the atom plugin, but it looks like your bug is with shfmt itself. Could you please report this issue on the mvdav/sh repository?

leagris commented 5 years ago

Reported here: https://github.com/mvdan/sh/issues/373