Xiaoven / codegex

A light-weight tools like spotbugs
GNU Lesser General Public License v2.1
1 stars 0 forks source link

Re-implement BIT_SIGNED_CHECK, BIT_SIGNED_CHECK_HIGH_BIT and BIT_AND_ZZ #57

Closed Xiaoven closed 3 years ago

Xiaoven commented 3 years ago

3 个 patterns

BIT_SIGNED_CHECK

属于 Bad Practice 分类,对形如 ((event.detail & SWT.SELECTED) > 0) 的pattern,不管constant SWT.SELECTED 是否为负,都建议使用 != 0

BIT_SIGNED_CHECK_HIGH_BIT

属于 Correctness 分类,是BIT_SIGNED_CHECK的子类。对于形如 ((val & CONSTANT) > 0) 的pattern, 如果 CONSTANT 是负数,会得不到想要的结果。

BIT_AND_ZZ

(e & 0) 跟 0 比较,比较结果总是固定的。 另外请参考 spotbugs 的实现考虑 BIT_ANDBIT_IOR 是否可以实现

打算参考 spotbugs 重新实现这两个 pattern, 前期调研基本结束。

TODO:

static int populationCount(long i) {
        // Returns the number of one-bits in the two's complement binary representation of the specified long value.
        return Long.bitCount(i);
    }

    static long getFlagBits(boolean isLong, long arg0) {
        long bits = arg0;
        if (isLong) {
            int a = populationCount(bits);
            long b = ~bits;
            int c = populationCount(b);
            if (a > c) {
                bits = ~bits;
            }
        } else if (populationCount(0xffffffffL & bits) > populationCount(0xffffffffL & ~bits)) {
            bits = 0xffffffffL & ~bits;
        }
        return bits;
    }

    public static void main(String[] args) {
        Number arg1 = TO_ASSIGNED;
        boolean isLong = arg1 instanceof Long;
        long bits = getFlagBits(isLong, arg1.longValue());
        boolean highbit = !isLong && (bits & 0x80000000) != 0 || isLong && bits < 0 && bits << 1 == 0;
        boolean onlyLowBits = bits >>> 12 == 0;
        System.out.println(highbit);
        System.out.println(onlyLowBits);
    }