repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/MemSizeEstimator.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Interface for estimating size of a specific Java type
*
* Created by Anton Nashatyrev on 01.12.2016.
*/
public interface MemSizeEstimator<E> {
long estimateSize(E e);
/**
* byte[] type size estimator
*/
MemSizeEstimator<byte[]> ByteArrayEstimator = bytes -> {
return bytes == null ? 0 : bytes.length + 16; // 4 - compressed ref size, 12 - Object header
};
}
| 1,230
| 31.394737
| 100
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/CountingQuotientFilter.java
|
package org.ethereum.datasource;
import java.util.HashMap;
import java.util.Map;
/**
* Supplies {@link QuotientFilter} with collisions counter map.
*
* <p>
* Hence it can handle any number of hard and/or soft collisions without performance lack.
* While {@link QuotientFilter} experiencing performance problem when collision number tends to 10_000.
*
* @author Mikhail Kalinin
* @since 14.02.2018
*/
public class CountingQuotientFilter extends QuotientFilter {
long FINGERPRINT_MASK;
private Map<Long, Counter> counters = new HashMap<>();
private CountingQuotientFilter(int quotientBits, int remainderBits) {
super(quotientBits, remainderBits);
this.FINGERPRINT_MASK = LOW_MASK(QUOTIENT_BITS + REMAINDER_BITS);
}
public static CountingQuotientFilter create(long largestNumberOfElements, long startingElements) {
QuotientFilter filter = QuotientFilter.create(largestNumberOfElements, startingElements);
return new CountingQuotientFilter(filter.QUOTIENT_BITS, filter.REMAINDER_BITS);
}
@Override
public synchronized void insert(long hash) {
if (super.maybeContains(hash)) {
addRef(hash);
} else {
super.insert(hash);
}
}
@Override
public synchronized void remove(long hash) {
if (super.maybeContains(hash) && delRef(hash) < 0) {
super.remove(hash);
}
}
@Override
protected long hash(byte[] bytes) {
long hash = 1;
for (byte b : bytes) {
hash = 31 * hash + b;
}
return hash;
}
public synchronized int getCollisionNumber() {
return counters.size();
}
public long getEntryNumber() {
return entries;
}
public long getMaxInsertions() {
return MAX_INSERTIONS;
}
private void addRef(long hash) {
long fp = fingerprint(hash);
Counter cnt = counters.get(fp);
if (cnt == null) {
counters.put(fp, new Counter());
} else {
cnt.refs++;
}
}
private int delRef(long hash) {
long fp = fingerprint(hash);
Counter cnt = counters.get(fp);
if (cnt == null) {
return -1;
}
if (--cnt.refs < 1) {
counters.remove(fp);
}
return cnt.refs;
}
private long fingerprint(long hash) {
return hash & FINGERPRINT_MASK;
}
private static class Counter {
int refs = 1;
}
}
| 2,520
| 24.464646
| 107
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/DataSourceArray.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import org.ethereum.util.ByteUtil;
import org.spongycastle.util.encoders.Hex;
import java.util.AbstractList;
/**
* Stores List structure in Source structure
*
* Created by Anton Nashatyrev on 17.03.2016.
*/
public class DataSourceArray<V> extends AbstractList<V> {
private ObjectDataSource<V> src;
private static final byte[] SIZE_KEY = Hex.decode("FFFFFFFFFFFFFFFF");
private int size = -1;
public DataSourceArray(ObjectDataSource<V> src) {
this.src = src;
}
public synchronized boolean flush() {
return src.flush();
}
@Override
public synchronized V set(int idx, V value) {
if (idx >= size()) {
setSize(idx + 1);
}
src.put(ByteUtil.intToBytes(idx), value);
return value;
}
@Override
public synchronized void add(int index, V element) {
set(index, element);
}
@Override
public synchronized V remove(int index) {
throw new RuntimeException("Not supported yet.");
}
@Override
public synchronized V get(int idx) {
if (idx < 0 || idx >= size()) throw new IndexOutOfBoundsException(idx + " > " + size);
return src.get(ByteUtil.intToBytes(idx));
}
@Override
public synchronized int size() {
if (size < 0) {
byte[] sizeBB = src.getSource().get(SIZE_KEY);
size = sizeBB == null ? 0 : ByteUtil.byteArrayToInt(sizeBB);
}
return size;
}
private synchronized void setSize(int newSize) {
size = newSize;
src.getSource().put(SIZE_KEY, ByteUtil.intToBytes(newSize));
}
}
| 2,447
| 28.853659
| 94
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/SourceCodec.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Source for converting between different key/value types
* Has no own state and immediately propagate all changes
* to the backing Source with key/value conversion
*
* Created by Anton Nashatyrev on 03.11.2016.
*/
public class SourceCodec<Key, Value, SourceKey, SourceValue>
extends AbstractChainedSource<Key, Value, SourceKey, SourceValue> {
protected Serializer<Key, SourceKey> keySerializer;
protected Serializer<Value, SourceValue> valSerializer;
/**
* Instantiates class
* @param src Backing Source
* @param keySerializer Key codec Key <=> SourceKey
* @param valSerializer Value codec Value <=> SourceValue
*/
public SourceCodec(Source<SourceKey, SourceValue> src, Serializer<Key, SourceKey> keySerializer, Serializer<Value, SourceValue> valSerializer) {
super(src);
this.keySerializer = keySerializer;
this.valSerializer = valSerializer;
setFlushSource(true);
}
@Override
public void put(Key key, Value val) {
getSource().put(keySerializer.serialize(key), valSerializer.serialize(val));
}
@Override
public Value get(Key key) {
return valSerializer.deserialize(getSource().get(keySerializer.serialize(key)));
}
@Override
public void delete(Key key) {
getSource().delete(keySerializer.serialize(key));
}
@Override
public boolean flushImpl() {
return false;
}
/**
* Shortcut class when only value conversion is required
*/
public static class ValueOnly<Key, Value, SourceValue> extends SourceCodec<Key, Value, Key, SourceValue> {
public ValueOnly(Source<Key, SourceValue> src, Serializer<Value, SourceValue> valSerializer) {
super(src, new Serializers.Identity<Key>(), valSerializer);
}
}
/**
* Shortcut class when only key conversion is required
*/
public static class KeyOnly<Key, Value, SourceKey> extends SourceCodec<Key, Value, SourceKey, Value> {
public KeyOnly(Source<SourceKey, Value> src, Serializer<Key, SourceKey> keySerializer) {
super(src, keySerializer, new Serializers.Identity<Value>());
}
}
/**
* Shortcut class when only value conversion is required and keys are of byte[] type
*/
public static class BytesKey<Value, SourceValue> extends ValueOnly<byte[], Value, SourceValue> {
public BytesKey(Source<byte[], SourceValue> src, Serializer<Value, SourceValue> valSerializer) {
super(src, valSerializer);
}
}
}
| 3,392
| 35.483871
| 148
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/WriteCache.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import com.googlecode.concurentlocks.ReadWriteUpdateLock;
import com.googlecode.concurentlocks.ReentrantReadWriteUpdateLock;
import org.ethereum.util.ALock;
import org.ethereum.util.ByteArrayMap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Collects changes and propagate them to the backing Source when flush() is called
*
* The WriteCache can be of two types: Simple and Counting
*
* Simple acts as regular Map: single and double adding of the same entry has the same effect
* Source entries (key/value pairs) may have arbitrary nature
*
* Counting counts the resulting number of inserts (+1) and deletes (-1) and when flushed
* does the resulting number of inserts (if sum > 0) or deletes (if sum < 0)
* Counting Source acts like {@link HashedKeySource} and makes sense only for data
* where a single key always corresponds to a single value
* Counting cache normally used as backing store for Trie data structure
*
* Created by Anton Nashatyrev on 11.11.2016.
*/
public class WriteCache<Key, Value> extends AbstractCachedSource<Key, Value> {
/**
* Type of the write cache
*/
public enum CacheType {
/**
* Simple acts as regular Map: single and double adding of the same entry has the same effect
* Source entries (key/value pairs) may have arbitrary nature
*/
SIMPLE,
/**
* Counting counts the resulting number of inserts (+1) and deletes (-1) and when flushed
* does the resulting number of inserts (if sum > 0) or deletes (if sum < 0)
* Counting Source acts like {@link HashedKeySource} and makes sense only for data
* where a single key always corresponds to a single value
* Counting cache normally used as backing store for Trie data structure
*/
COUNTING
}
private static abstract class CacheEntry<V> implements Entry<V>{
// dedicated value instance which indicates that the entry was deleted
// (ref counter decremented) but we don't know actual value behind it
static final Object UNKNOWN_VALUE = new Object();
V value;
int counter = 0;
protected CacheEntry(V value) {
this.value = value;
}
protected abstract void deleted();
protected abstract void added();
protected abstract V getValue();
@Override
public V value() {
V v = getValue();
return v == UNKNOWN_VALUE ? null : v;
}
}
private static final class SimpleCacheEntry<V> extends CacheEntry<V> {
public SimpleCacheEntry(V value) {
super(value);
}
public void deleted() {
counter = -1;
}
public void added() {
counter = 1;
}
@Override
public V getValue() {
return counter < 0 ? null : value;
}
}
private static final class CountCacheEntry<V> extends CacheEntry<V> {
public CountCacheEntry(V value) {
super(value);
}
public void deleted() {
counter--;
}
public void added() {
counter++;
}
@Override
public V getValue() {
// for counting cache we return the cached value even if
// it was deleted (once or several times) as we don't know
// how many 'instances' are left behind
return value;
}
}
private final boolean isCounting;
protected volatile Map<Key, CacheEntry<Value>> cache = new HashMap<>();
protected ReadWriteUpdateLock rwuLock = new ReentrantReadWriteUpdateLock();
protected ALock readLock = new ALock(rwuLock.readLock());
protected ALock writeLock = new ALock(rwuLock.writeLock());
protected ALock updateLock = new ALock(rwuLock.updateLock());
private boolean checked = false;
public WriteCache(Source<Key, Value> src, CacheType cacheType) {
super(src);
this.isCounting = cacheType == CacheType.COUNTING;
}
public WriteCache<Key, Value> withCache(Map<Key, CacheEntry<Value>> cache) {
this.cache = cache;
return this;
}
@Override
public Collection<Key> getModified() {
try (ALock l = readLock.lock()){
return cache.keySet();
}
}
@Override
public boolean hasModified() {
return !cache.isEmpty();
}
private CacheEntry<Value> createCacheEntry(Value val) {
if (isCounting) {
return new CountCacheEntry<>(val);
} else {
return new SimpleCacheEntry<>(val);
}
}
@Override
public void put(Key key, Value val) {
checkByteArrKey(key);
if (val == null) {
delete(key);
return;
}
try (ALock l = writeLock.lock()){
CacheEntry<Value> curVal = cache.get(key);
if (curVal == null) {
curVal = createCacheEntry(val);
CacheEntry<Value> oldVal = cache.put(key, curVal);
if (oldVal != null) {
cacheRemoved(key, oldVal.value == unknownValue() ? null : oldVal.value);
}
cacheAdded(key, curVal.value);
}
// assigning for non-counting cache only
// for counting cache the value should be immutable (see HashedKeySource)
curVal.value = val;
curVal.added();
}
}
@Override
public Value get(Key key) {
checkByteArrKey(key);
try (ALock l = readLock.lock()){
CacheEntry<Value> curVal = cache.get(key);
if (curVal == null) {
return getSource() == null ? null : getSource().get(key);
} else {
Value value = curVal.getValue();
if (value == unknownValue()) {
return getSource() == null ? null : getSource().get(key);
} else {
return value;
}
}
}
}
@Override
public void delete(Key key) {
checkByteArrKey(key);
try (ALock l = writeLock.lock()){
CacheEntry<Value> curVal = cache.get(key);
if (curVal == null) {
curVal = createCacheEntry(getSource() == null ? null : unknownValue());
CacheEntry<Value> oldVal = cache.put(key, curVal);
if (oldVal != null) {
cacheRemoved(key, oldVal.value);
}
cacheAdded(key, curVal.value == unknownValue() ? null : curVal.value);
}
curVal.deleted();
}
}
@Override
public boolean flush() {
boolean ret = false;
try (ALock l = updateLock.lock()){
for (Map.Entry<Key, CacheEntry<Value>> entry : cache.entrySet()) {
if (entry.getValue().counter > 0) {
for (int i = 0; i < entry.getValue().counter; i++) {
getSource().put(entry.getKey(), entry.getValue().value);
}
ret = true;
} else if (entry.getValue().counter < 0) {
for (int i = 0; i > entry.getValue().counter; i--) {
getSource().delete(entry.getKey());
}
ret = true;
}
}
if (flushSource) {
getSource().flush();
}
try (ALock l1 = writeLock.lock()){
cache.clear();
cacheCleared();
}
return ret;
}
}
@Override
protected boolean flushImpl() {
return false;
}
private Value unknownValue() {
return (Value) CacheEntry.UNKNOWN_VALUE;
}
public Entry<Value> getCached(Key key) {
try (ALock l = readLock.lock()){
CacheEntry<Value> entry = cache.get(key);
if (entry == null || entry.value == unknownValue()) {
return null;
}else {
return entry;
}
}
}
// Guard against wrong cache Map
// if a regular Map is accidentally used for byte[] type keys
// the situation might be tricky to debug
private void checkByteArrKey(Key key) {
if (checked) return;
if (key instanceof byte[]) {
if (!(cache instanceof ByteArrayMap)) {
throw new RuntimeException("Wrong map/set for byte[] key");
}
}
checked = true;
}
public long debugCacheSize() {
long ret = 0;
for (Map.Entry<Key, CacheEntry<Value>> entry : cache.entrySet()) {
ret += keySizeEstimator.estimateSize(entry.getKey());
ret += valueSizeEstimator.estimateSize(entry.getValue().value());
}
return ret;
}
/**
* Shortcut for WriteCache with byte[] keys. Also prevents accidental
* usage of regular Map implementation (non byte[])
*/
public static class BytesKey<V> extends WriteCache<byte[], V> implements CachedSource.BytesKey<V> {
public BytesKey(Source<byte[], V> src, CacheType cacheType) {
super(src, cacheType);
withCache(new ByteArrayMap<CacheEntry<V>>());
}
}
}
| 10,205
| 31.195584
| 103
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/Source.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Base interface for all data source classes
*
* Created by Anton Nashatyrev on 05.10.2016.
*/
public interface Source<K, V> {
/**
* Puts key-value pair into source
*/
void put(K key, V val);
/**
* Gets a value by its key
* @return value or <null/> if no such key in the source
*/
V get(K key);
/**
* Deletes the key-value pair from the source
*/
void delete(K key);
/**
* If this source has underlying level source then all
* changes collected in this source are flushed into the
* underlying source.
* The implementation may do 'cascading' flush, i.e. call
* flush() on the underlying Source
* @return true if any changes we flushed, false if the underlying
* Source didn't change
*/
boolean flush();
}
| 1,649
| 29
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/NodeKeyCompositor.java
|
package org.ethereum.datasource;
import org.ethereum.config.CommonConfig;
import org.ethereum.db.RepositoryRoot;
import static java.lang.System.arraycopy;
import static org.ethereum.crypto.HashUtil.sha3;
/**
* Composes keys for contract storage nodes.
*
* <p>
* <b>Input:</b> 32-bytes node key, 20-bytes contract address
* <br/>
* <b>Output:</b> 32-bytes composed key <i>[first 16-bytes of node key : first 16-bytes of address hash]</i>
*
* <p>
* Example: <br/>
* Contract address hash <i>a9539c810cc2e8fa20785bdd78ec36ccb25e1b5be78dbadf6c4e817c6d170bbb</i> <br/>
* Key of one of the storage nodes <i>bbbbbb5be78dbadf6c4e817c6d170bbb47e9916f8f6cc4607c5f3819ce98497b</i> <br/>
* Composed key will be <i>bbbbbb5be78dbadf6c4e817c6d170bbba9539c810cc2e8fa20785bdd78ec36cc</i>
*
* <p>
* This mechanism is a part of flat storage source which is free from reference counting
*
* @see CommonConfig#trieNodeSource()
* @see RepositoryRoot#RepositoryRoot(Source, byte[])
*
* @author Mikhail Kalinin
* @since 05.12.2017
*/
public class NodeKeyCompositor implements Serializer<byte[], byte[]> {
public static final int HASH_LEN = 32;
public static final int PREFIX_BYTES = 16;
private byte[] addrHash;
public NodeKeyCompositor(byte[] addrOrHash) {
this.addrHash = addrHash(addrOrHash);
}
@Override
public byte[] serialize(byte[] key) {
return composeInner(key, addrHash);
}
@Override
public byte[] deserialize(byte[] stream) {
return stream;
}
public static byte[] compose(byte[] key, byte[] addrOrHash) {
return composeInner(key, addrHash(addrOrHash));
}
private static byte[] composeInner(byte[] key, byte[] addrHash) {
validateKey(key);
byte[] derivative = new byte[key.length];
arraycopy(key, 0, derivative, 0, PREFIX_BYTES);
arraycopy(addrHash, 0, derivative, PREFIX_BYTES, PREFIX_BYTES);
return derivative;
}
private static void validateKey(byte[] key) {
if (key.length != HASH_LEN)
throw new IllegalArgumentException("Key is not a hash code");
}
private static byte[] addrHash(byte[] addrOrHash) {
return addrOrHash.length == HASH_LEN ? addrOrHash : sha3(addrOrHash);
}
}
| 2,305
| 29.342105
| 116
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/AbstractCachedSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Abstract cache implementation which tracks the cache size with
* supplied key and value MemSizeEstimator's
*
* Created by Anton Nashatyrev on 01.12.2016.
*/
public abstract class AbstractCachedSource <Key, Value>
extends AbstractChainedSource<Key, Value, Key, Value>
implements CachedSource<Key, Value> {
private final Object lock = new Object();
/**
* Like the Optional interface represents either the value cached
* or null cached (i.e. cache knows that underlying storage contain null)
*/
public interface Entry<V> {
V value();
}
static final class SimpleEntry<V> implements Entry<V> {
private V val;
public SimpleEntry(V val) {
this.val = val;
}
public V value() {
return val;
}
}
protected MemSizeEstimator<Key> keySizeEstimator;
protected MemSizeEstimator<Value> valueSizeEstimator;
private int size = 0;
public AbstractCachedSource(Source<Key, Value> source) {
super(source);
}
/**
* Returns the cached value if exist.
* Method doesn't look into the underlying storage
* @return The value Entry if it cached (Entry may has null value if null value is cached),
* or null if no information in the cache for this key
*/
abstract Entry<Value> getCached(Key key);
/**
* Needs to be called by the implementation when cache entry is added
* Only new entries should be accounted for accurate size tracking
* If the value for the key is changed the {@link #cacheRemoved}
* needs to be called first
*/
protected void cacheAdded(Key key, Value value) {
synchronized (lock) {
if (keySizeEstimator != null) {
size += keySizeEstimator.estimateSize(key);
}
if (valueSizeEstimator != null) {
size += valueSizeEstimator.estimateSize(value);
}
}
}
/**
* Needs to be called by the implementation when cache entry is removed
*/
protected void cacheRemoved(Key key, Value value) {
synchronized (lock) {
if (keySizeEstimator != null) {
size -= keySizeEstimator.estimateSize(key);
}
if (valueSizeEstimator != null) {
size -= valueSizeEstimator.estimateSize(value);
}
}
}
/**
* Needs to be called by the implementation when cache is cleared
*/
protected void cacheCleared() {
synchronized (lock) {
size = 0;
}
}
/**
* Sets the key/value size estimators
*/
public AbstractCachedSource <Key, Value> withSizeEstimators(MemSizeEstimator<Key> keySizeEstimator, MemSizeEstimator<Value> valueSizeEstimator) {
this.keySizeEstimator = keySizeEstimator;
this.valueSizeEstimator = valueSizeEstimator;
return this;
}
@Override
public long estimateCacheSize() {
return size;
}
}
| 3,857
| 31.15
| 149
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/DbSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import java.util.Set;
/**
* Interface represents DB source which is normally the final Source in the chain
*/
public interface DbSource<V> extends BatchSource<byte[], V> {
/**
* Sets the DB name.
* This could be the underlying DB table/dir name
*/
void setName(String name);
/**
* @return DB name
*/
String getName();
/**
* Initializes DB (open table, connection, etc)
* with default {@link DbSettings#DEFAULT}
*/
void init();
/**
* Initializes DB (open table, connection, etc)
* @param settings DB settings
*/
void init(DbSettings settings);
/**
* @return true if DB connection is alive
*/
boolean isAlive();
/**
* Closes the DB table/connection
*/
void close();
/**
* @return DB keys if this option is available
* @throws RuntimeException if the method is not supported
*/
Set<byte[]> keys() throws RuntimeException;
/**
* Closes database, destroys its data and finally runs init()
*/
void reset();
/**
* If supported, retrieves a value using a key prefix.
* Prefix extraction is meant to be done on the implementing side.<br>
*
* @param key a key for the lookup
* @param prefixBytes prefix length in bytes
* @return first value picked by prefix lookup over DB or null if there is no match
* @throws RuntimeException if operation is not supported
*/
V prefixLookup(byte[] key, int prefixBytes);
}
| 2,348
| 27.646341
| 87
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/MultiCache.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Cache of Caches (child caches)
* When a child cache is not found in the local cache it is looked up in the backing Source
* Based on this child backing cache (or null if not found) the new local cache is created
* via create() method
*
* When flushing children, each child is just flushed if it has backing Source or the whole
* child cache is put to the MultiCache backing source
*
* The primary goal if for caching contract storages in the child repositories (tracks)
*
* Created by Anton Nashatyrev on 07.10.2016.
*/
public abstract class MultiCache<V extends CachedSource> extends ReadWriteCache.BytesKey<V> {
public MultiCache(Source<byte[], V> src) {
super(src, WriteCache.CacheType.SIMPLE);
}
/**
* When a child cache is not found in the local cache it is looked up in the backing Source
* Based on this child backing cache (or null if not found) the new local cache is created
* via create() method
*/
@Override
public synchronized V get(byte[] key) {
AbstractCachedSource.Entry<V> ownCacheEntry = getCached(key);
V ownCache = ownCacheEntry == null ? null : ownCacheEntry.value();
if (ownCache == null) {
V v = getSource() != null ? super.get(key) : null;
ownCache = create(key, v);
put(key, ownCache);
}
return ownCache;
}
/**
* each child is just flushed if it has backing Source or the whole
* child cache is put to the MultiCache backing source
*/
@Override
public synchronized boolean flushImpl() {
boolean ret = false;
for (byte[] key: writeCache.getModified()) {
V value = super.get(key);
if (value == null) {
// cache was deleted
ret |= flushChild(key, value);
if (getSource() != null) {
getSource().delete(key);
}
} else if (value.getSource() != null){
ret |= flushChild(key, value);
} else {
getSource().put(key, value);
ret = true;
}
}
return ret;
}
/**
* Is invoked to flush child cache if it has backing Source
* Some additional tasks may be performed by subclasses here
*/
protected boolean flushChild(byte[] key, V childCache) {
return childCache != null ? childCache.flush() : true;
}
/**
* Creates a local child cache instance based on the child cache instance
* (or null) from the MultiCache backing Source
*/
protected abstract V create(byte[] key, V srcCache);
}
| 3,479
| 35.631579
| 95
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/HashedKeySource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Indicator interface which narrows the Source contract:
* the same Key always maps to the same Value,
* there could be no put() with the same Key and different Value
* Normally the Key is the hash of the Value
* Usually such kind of sources are Merkle Trie backing stores
*
* Created by Anton Nashatyrev on 08.11.2016.
*/
public interface HashedKeySource<Key, Value> extends Source<Key, Value> {
}
| 1,235
| 38.870968
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/PrefixLookupSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* A kind of source which executes {@link #get(byte[])} query as
* a {@link DbSource#prefixLookup(byte[], int)} query of backing source.<br>
*
* Other operations are simply propagated to backing {@link DbSource}.
*
* @author Mikhail Kalinin
* @since 01.12.2017
*/
public class PrefixLookupSource<V> implements Source<byte[], V> {
// prefix length in bytes
private int prefixBytes;
private DbSource<V> source;
public PrefixLookupSource(DbSource<V> source, int prefixBytes) {
this.source = source;
this.prefixBytes = prefixBytes;
}
@Override
public V get(byte[] key) {
return source.prefixLookup(key, prefixBytes);
}
@Override
public void put(byte[] key, V val) {
source.put(key, val);
}
@Override
public void delete(byte[] key) {
source.delete(key);
}
@Override
public boolean flush() {
return source.flush();
}
}
| 1,770
| 28.516667
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/Serializer.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Converter from one type to another and vice versa
*
* Created by Anton Nashatyrev on 17.03.2016.
*/
public interface Serializer<T, S> {
/**
* Converts T ==> S
* Should correctly handle null parameter
*/
S serialize(T object);
/**
* Converts S ==> T
* Should correctly handle null parameter
*/
T deserialize(S stream);
}
| 1,200
| 31.459459
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/ObjectDataSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Just a convenient class to store arbitrary Objects into byte[] value backing
* Source.
* Includes ReadCache for caching deserialized objects and object Serializer
*
* Created by Anton Nashatyrev on 06.12.2016.
*/
public class ObjectDataSource<V> extends SourceChainBox<byte[], V, byte[], byte[]> {
ReadCache<byte[], V> cache;
SourceCodec<byte[], V, byte[], byte[]> codec;
Source<byte[], byte[]> byteSource;
/**
* Creates new instance
* @param byteSource baking store
* @param serializer for encode/decode byte[] <=> V
* @param readCacheEntries number of entries to cache
*/
public ObjectDataSource(Source<byte[], byte[]> byteSource, Serializer<V, byte[]> serializer, int readCacheEntries) {
super(byteSource);
this.byteSource = byteSource;
add(codec = new SourceCodec<>(byteSource, new Serializers.Identity<byte[]>(), serializer));
if (readCacheEntries > 0) {
add(cache = new ReadCache.BytesKey<>(codec).withMaxCapacity(readCacheEntries));
}
}
}
| 1,884
| 39.106383
| 120
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/AsyncFlushable.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.Future;
/**
* Represents cache Source which is able to do asynchronous flush
*
* Created by Anton Nashatyrev on 02.02.2017.
*/
public interface AsyncFlushable {
/**
* Flip the backing storage so the current state will be flushed
* when call {@link #flushAsync()} and all the newer changes will
* be collected to a new backing store and will be flushed only on
* subsequent flush call
*
* The method is intended to make consistent flush from several
* sources. I.e. at some point all the related Sources are flipped
* synchronously first (this doesn't consume any time normally) and then
* are flushed asynchronously
*
* This call may block until a previous flush is completed (if still in progress)
*
* @throws InterruptedException
*/
void flipStorage() throws InterruptedException;
/**
* Does async flush, i.e. returns immediately while starts doing flush in a separate thread
* This call may still block if the previous flush is not complete yet
*
* @return Future when the actual flush is complete
*/
ListenableFuture<Boolean> flushAsync() throws InterruptedException;
}
| 2,104
| 36.589286
| 95
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/CountingBytesSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import org.ethereum.crypto.HashUtil;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import java.util.Arrays;
/**
* 'Reference counting' Source. Unlike regular Source if an entry was
* e.g. 'put' twice it is actually deleted when 'delete' is called twice
* I.e. each put increments counter and delete decrements counter, the
* entry is deleted when the counter becomes zero.
*
* Please note that the counting mechanism makes sense only for
* {@link HashedKeySource} like Sources when any taken key can correspond to
* the only value
*
* This Source is constrained to byte[] values only as the counter
* needs to be encoded to the backing Source value as byte[]
*
* Created by Anton Nashatyrev on 08.11.2016.
*/
public class CountingBytesSource extends AbstractChainedSource<byte[], byte[], byte[], byte[]>
implements HashedKeySource<byte[], byte[]> {
QuotientFilter filter;
boolean dirty = false;
private byte[] filterKey = HashUtil.sha3("countingStateFilter".getBytes());
public CountingBytesSource(Source<byte[], byte[]> src) {
this(src, false);
}
public CountingBytesSource(Source<byte[], byte[]> src, boolean bloom) {
super(src);
byte[] filterBytes = src.get(filterKey);
if (bloom) {
if (filterBytes != null) {
filter = QuotientFilter.deserialize(filterBytes);
} else {
filter = QuotientFilter.create(5_000_000, 10_000);
}
}
}
@Override
public void put(byte[] key, byte[] val) {
if (val == null) {
delete(key);
return;
}
synchronized (this) {
byte[] srcVal = getSource().get(key);
int srcCount = decodeCount(srcVal);
if (srcCount >= 1) {
if (filter != null) filter.insert(key);
dirty = true;
}
getSource().put(key, encodeCount(val, srcCount + 1));
}
}
@Override
public byte[] get(byte[] key) {
return decodeValue(getSource().get(key));
}
@Override
public void delete(byte[] key) {
synchronized (this) {
int srcCount;
byte[] srcVal = null;
if (filter == null || filter.maybeContains(key)) {
srcVal = getSource().get(key);
srcCount = decodeCount(srcVal);
} else {
srcCount = 1;
}
if (srcCount > 1) {
getSource().put(key, encodeCount(decodeValue(srcVal), srcCount - 1));
} else {
getSource().delete(key);
}
}
}
@Override
protected boolean flushImpl() {
if (filter != null && dirty) {
byte[] filterBytes;
synchronized (this) {
filterBytes = filter.serialize();
}
getSource().put(filterKey, filterBytes);
dirty = false;
return true;
} else {
return false;
}
}
/**
* Extracts value from the backing Source counter + value byte array
*/
protected byte[] decodeValue(byte[] srcVal) {
return srcVal == null ? null : Arrays.copyOfRange(srcVal, RLP.decode(srcVal, 0).getPos(), srcVal.length);
}
/**
* Extracts counter from the backing Source counter + value byte array
*/
protected int decodeCount(byte[] srcVal) {
return srcVal == null ? 0 : ByteUtil.byteArrayToInt((byte[]) RLP.decode(srcVal, 0).getDecoded());
}
/**
* Composes value and counter into backing Source value
*/
protected byte[] encodeCount(byte[] val, int count) {
return ByteUtil.merge(RLP.encodeInt(count), val);
}
}
| 4,600
| 31.401408
| 113
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/BatchSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import java.util.Map;
/**
* The Source which is capable of batch updates.
* The semantics of a batch update is up to implementation:
* it can be just performance optimization or batch update
* can be atomic or other.
*
* Created by Anton Nashatyrev on 01.11.2016.
*/
public interface BatchSource<K, V> extends Source<K, V> {
/**
* Do batch update
* @param rows Normally this Map is treated just as a collection
* of key-value pairs and shouldn't conform to a normal
* Map contract. Though it is up to implementation to
* require passing specific Maps
*/
void updateBatch(Map<K, V> rows);
}
| 1,497
| 35.536585
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/NoDeleteSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
/**
* Just ignores deletes from the backing Source
* Normally used for testing for Trie backing Sources to
* not delete older states
*
* Created by Anton Nashatyrev on 03.11.2016.
*/
public class NoDeleteSource<Key, Value> extends AbstractChainedSource<Key, Value, Key, Value> {
public NoDeleteSource(Source<Key, Value> src) {
super(src);
setFlushSource(true);
}
@Override
public void delete(Key key) {
}
@Override
public void put(Key key, Value val) {
if (val != null) getSource().put(key, val);
}
@Override
public Value get(Key key) {
return getSource().get(key);
}
@Override
protected boolean flushImpl() {
return false;
}
}
| 1,559
| 28.433962
| 95
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/SourceChainBox.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a chain of Sources as a single Source
* All calls to this Source are delegated to the last Source in the chain
* On flush all Sources in chain are flushed in reverse order
*
* Created by Anton Nashatyrev on 07.12.2016.
*/
public class SourceChainBox<Key, Value, SourceKey, SourceValue>
extends AbstractChainedSource<Key, Value, SourceKey, SourceValue> {
List<Source> chain = new ArrayList<>();
Source<Key, Value> lastSource;
public SourceChainBox(Source<SourceKey, SourceValue> source) {
super(source);
}
/**
* Adds next Source in the chain to the collection
* Sources should be added from most bottom (connected to the backing Source)
* All calls to the SourceChainBox will be delegated to the last added
* Source
*/
public void add(Source src) {
chain.add(src);
lastSource = src;
}
@Override
public void put(Key key, Value val) {
lastSource.put(key, val);
}
@Override
public Value get(Key key) {
return lastSource.get(key);
}
@Override
public void delete(Key key) {
lastSource.delete(key);
}
// @Override
// public boolean flush() {
//// boolean ret = false;
//// for (int i = chain.size() - 1; i >= 0 ; i--) {
//// ret |= chain.get(i).flush();
//// }
// return lastSource.flush();
// }
@Override
protected boolean flushImpl() {
return lastSource.flush();
}
}
| 2,382
| 28.7875
| 81
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/ReadWriteCache.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import java.util.Collection;
/**
* Facade class which encapsulates both Read and Write caches
*
* Created by Anton Nashatyrev on 29.11.2016.
*/
public class ReadWriteCache<Key, Value>
extends SourceChainBox<Key, Value, Key, Value>
implements CachedSource<Key, Value> {
protected ReadCache<Key, Value> readCache;
protected WriteCache<Key, Value> writeCache;
protected ReadWriteCache(Source<Key, Value> source) {
super(source);
}
public ReadWriteCache(Source<Key, Value> src, WriteCache.CacheType cacheType) {
super(src);
add(writeCache = new WriteCache<>(src, cacheType));
add(readCache = new ReadCache<>(writeCache));
readCache.setFlushSource(true);
}
@Override
public synchronized Collection<Key> getModified() {
return writeCache.getModified();
}
@Override
public boolean hasModified() {
return writeCache.hasModified();
}
protected synchronized AbstractCachedSource.Entry<Value> getCached(Key key) {
AbstractCachedSource.Entry<Value> v = readCache.getCached(key);
if (v == null) {
v = writeCache.getCached(key);
}
return v;
}
@Override
public synchronized long estimateCacheSize() {
return readCache.estimateCacheSize() + writeCache.estimateCacheSize();
}
public static class BytesKey<V> extends ReadWriteCache<byte[], V> {
public BytesKey(Source<byte[], V> src, WriteCache.CacheType cacheType) {
super(src);
add(this.writeCache = new WriteCache.BytesKey<>(src, cacheType));
add(this.readCache = new ReadCache.BytesKey<>(writeCache));
readCache.setFlushSource(true);
}
}
}
| 2,577
| 32.480519
| 83
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/ReadCache.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import org.apache.commons.collections4.map.LRUMap;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.util.ByteArrayMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Caches entries get/updated and use LRU algo to purge them if the number
* of entries exceeds threshold.
*
* This implementation could extended to estimate cached data size for
* more accurate size restriction, but if entries are more or less
* of the same size the entries count would be good enough
*
* Another implementation idea is heap sensitive read cache based on
* SoftReferences, when the cache occupies all the available heap
* but get shrink when low heap
*
* Created by Anton Nashatyrev on 05.10.2016.
*/
public class ReadCache<Key, Value> extends AbstractCachedSource<Key, Value> {
private final Value NULL = (Value) new Object();
private Map<Key, Value> cache;
private boolean byteKeyMap;
public ReadCache(Source<Key, Value> src) {
super(src);
withCache(new HashMap<Key, Value>());
}
/**
* Installs the specific cache Map implementation
*/
public ReadCache<Key, Value> withCache(Map<Key, Value> cache) {
byteKeyMap = cache instanceof ByteArrayMap;
this.cache = Collections.synchronizedMap(cache);
return this;
}
/**
* Sets the max number of entries to cache
*/
public ReadCache<Key, Value> withMaxCapacity(int maxCapacity) {
return withCache(new LRUMap<Key, Value>(maxCapacity) {
@Override
protected boolean removeLRU(LinkEntry<Key, Value> entry) {
cacheRemoved(entry.getKey(), entry.getValue());
return super.removeLRU(entry);
}
});
}
// the guard against incorrect Map implementation for byte[] keys
private boolean checked = false;
private void checkByteArrKey(Key key) {
if (checked) return;
if (key instanceof byte[]) {
if (!byteKeyMap) {
throw new RuntimeException("Wrong map/set for byte[] key");
}
}
checked = true;
}
@Override
public void put(Key key, Value val) {
checkByteArrKey(key);
if (val == null) {
delete(key);
} else {
cache.put(key, val);
cacheAdded(key, val);
getSource().put(key, val);
}
}
@Override
public Value get(Key key) {
checkByteArrKey(key);
Value ret = cache.get(key);
if (ret == NULL) {
return null;
}
if (ret == null) {
ret = getSource().get(key);
cache.put(key, ret == null ? NULL : ret);
cacheAdded(key, ret);
}
return ret;
}
@Override
public void delete(Key key) {
checkByteArrKey(key);
Value value = cache.remove(key);
cacheRemoved(key, value);
getSource().delete(key);
}
@Override
protected boolean flushImpl() {
return false;
}
public synchronized Collection<Key> getModified() {
return Collections.emptyList();
}
@Override
public boolean hasModified() {
return false;
}
@Override
public synchronized Entry<Value> getCached(Key key) {
Value value = cache.get(key);
return value == null ? null : new SimpleEntry<>(value == NULL ? null : value);
}
/**
* Shortcut for ReadCache with byte[] keys. Also prevents accidental
* usage of regular Map implementation (non byte[])
*/
public static class BytesKey<V> extends ReadCache<byte[], V> implements CachedSource.BytesKey<V> {
public BytesKey(Source<byte[], V> src) {
super(src);
withCache(new ByteArrayMap<V>());
}
public ReadCache.BytesKey<V> withMaxCapacity(int maxCapacity) {
withCache(new ByteArrayMap<V>(new LRUMap<ByteArrayWrapper, V>(maxCapacity) {
@Override
protected boolean removeLRU(LinkEntry<ByteArrayWrapper, V> entry) {
cacheRemoved(entry.getKey().getData(), entry.getValue());
return super.removeLRU(entry);
}
}));
return this;
}
}
}
| 5,164
| 29.744048
| 102
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/inmem/HashMapDB.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource.inmem;
import org.ethereum.datasource.DbSettings;
import org.ethereum.datasource.DbSource;
import org.ethereum.util.ALock;
import org.ethereum.util.ByteArrayMap;
import org.ethereum.util.FastByteComparisons;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by Anton Nashatyrev on 12.10.2016.
*/
public class HashMapDB<V> implements DbSource<V> {
protected final Map<byte[], V> storage;
protected ReadWriteLock rwLock = new ReentrantReadWriteLock();
protected ALock readLock = new ALock(rwLock.readLock());
protected ALock writeLock = new ALock(rwLock.writeLock());
public HashMapDB() {
this(new ByteArrayMap<V>());
}
public HashMapDB(ByteArrayMap<V> storage) {
this.storage = storage;
}
@Override
public void put(byte[] key, V val) {
if (val == null) {
delete(key);
} else {
try (ALock l = writeLock.lock()) {
storage.put(key, val);
}
}
}
@Override
public V get(byte[] key) {
try (ALock l = readLock.lock()) {
return storage.get(key);
}
}
@Override
public void delete(byte[] key) {
try (ALock l = writeLock.lock()) {
storage.remove(key);
}
}
@Override
public boolean flush() {
return true;
}
@Override
public void setName(String name) {}
@Override
public String getName() {
return "in-memory";
}
@Override
public void init() {}
@Override
public void init(DbSettings settings) {}
@Override
public boolean isAlive() {
return true;
}
@Override
public void close() {}
@Override
public Set<byte[]> keys() {
try (ALock l = readLock.lock()) {
return getStorage().keySet();
}
}
@Override
public void reset() {
try (ALock l = writeLock.lock()) {
storage.clear();
}
}
@Override
public V prefixLookup(byte[] key, int prefixBytes) {
try (ALock l = readLock.lock()) {
for (Map.Entry<byte[], V> e : storage.entrySet())
if (FastByteComparisons.compareTo(key, 0, prefixBytes, e.getKey(), 0, prefixBytes) == 0) {
return e.getValue();
}
return null;
}
}
@Override
public void updateBatch(Map<byte[], V> rows) {
try (ALock l = writeLock.lock()) {
for (Map.Entry<byte[], V> entry : rows.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
}
public Map<byte[], V> getStorage() {
return storage;
}
}
| 3,622
| 24.695035
| 106
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/inmem/HashMapDBSimple.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource.inmem;
import org.ethereum.datasource.DbSettings;
import org.ethereum.datasource.DbSource;
import org.ethereum.util.ByteArrayMap;
import org.ethereum.util.FastByteComparisons;
import java.util.Map;
import java.util.Set;
/**
* Created by Anton Nashatyrev on 12.10.2016.
*/
public class HashMapDBSimple<V> implements DbSource<V> {
protected final Map<byte[], V> storage;
public HashMapDBSimple() {
this(new ByteArrayMap<V>());
}
public HashMapDBSimple(ByteArrayMap<V> storage) {
this.storage = storage;
}
@Override
public void put(byte[] key, V val) {
if (val == null) {
delete(key);
} else {
storage.put(key, val);
}
}
@Override
public V get(byte[] key) {
return storage.get(key);
}
@Override
public void delete(byte[] key) {
storage.remove(key);
}
@Override
public boolean flush() {
return true;
}
@Override
public void setName(String name) {}
@Override
public String getName() {
return "in-memory";
}
@Override
public void init() {}
@Override
public void init(DbSettings settings) {}
@Override
public boolean isAlive() {
return true;
}
@Override
public void close() {}
@Override
public Set<byte[]> keys() {
return getStorage().keySet();
}
@Override
public void reset() {
storage.clear();
}
@Override
public V prefixLookup(byte[] key, int prefixBytes) {
for (Map.Entry<byte[], V> e : storage.entrySet())
if (FastByteComparisons.compareTo(key, 0, prefixBytes, e.getKey(), 0, prefixBytes) == 0) {
return e.getValue();
}
return null;
}
@Override
public void updateBatch(Map<byte[], V> rows) {
for (Map.Entry<byte[], V> entry : rows.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public Map<byte[], V> getStorage() {
return storage;
}
}
| 2,882
| 22.826446
| 102
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/leveldb/LevelDbDataSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource.leveldb;
import org.ethereum.config.SystemProperties;
import org.ethereum.datasource.DbSettings;
import org.ethereum.datasource.DbSource;
import org.ethereum.util.FileUtil;
import org.iq80.leveldb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static org.fusesource.leveldbjni.JniDBFactory.factory;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* @author Roman Mandeleil
* @since 18.01.2015
*/
public class LevelDbDataSource implements DbSource<byte[]> {
private static final Logger logger = LoggerFactory.getLogger("db");
@Autowired
SystemProperties config = SystemProperties.getDefault(); // initialized for standalone test
String name;
DB db;
boolean alive;
DbSettings settings = DbSettings.DEFAULT;
// The native LevelDB insert/update/delete are normally thread-safe
// However close operation is not thread-safe and may lead to a native crash when
// accessing a closed DB.
// The leveldbJNI lib has a protection over accessing closed DB but it is not synchronized
// This ReadWriteLock still permits concurrent execution of insert/delete/update operations
// however blocks them on init/close/delete operations
private ReadWriteLock resetDbLock = new ReentrantReadWriteLock();
public LevelDbDataSource() {
}
public LevelDbDataSource(String name) {
this.name = name;
logger.debug("New LevelDbDataSource: " + name);
}
@Override
public void init() {
init(DbSettings.DEFAULT);
}
@Override
public void init(DbSettings settings) {
this.settings = settings;
resetDbLock.writeLock().lock();
try {
logger.debug("~> LevelDbDataSource.init(): " + name);
if (isAlive()) return;
if (name == null) throw new NullPointerException("no name set to the db");
Options options = new Options();
options.createIfMissing(true);
options.compressionType(CompressionType.NONE);
options.blockSize(10 * 1024 * 1024);
options.writeBufferSize(10 * 1024 * 1024);
options.cacheSize(0);
options.paranoidChecks(true);
options.verifyChecksums(true);
options.maxOpenFiles(settings.getMaxOpenFiles());
try {
logger.debug("Opening database");
final Path dbPath = getPath();
if (!Files.isSymbolicLink(dbPath.getParent())) Files.createDirectories(dbPath.getParent());
logger.debug("Initializing new or existing database: '{}'", name);
try {
db = factory.open(dbPath.toFile(), options);
} catch (IOException e) {
// database could be corrupted
// exception in std out may look:
// org.fusesource.leveldbjni.internal.NativeDB$DBException: Corruption: 16 missing files; e.g.: /Users/stan/ethereumj/database-test/block/000026.ldb
// org.fusesource.leveldbjni.internal.NativeDB$DBException: Corruption: checksum mismatch
if (e.getMessage().contains("Corruption:")) {
logger.warn("Problem initializing database.", e);
logger.info("LevelDB database must be corrupted. Trying to repair. Could take some time.");
factory.repair(dbPath.toFile(), options);
logger.info("Repair finished. Opening database again.");
db = factory.open(dbPath.toFile(), options);
} else {
// must be db lock
// org.fusesource.leveldbjni.internal.NativeDB$DBException: IO error: lock /Users/stan/ethereumj/database-test/state/LOCK: Resource temporarily unavailable
throw e;
}
}
alive = true;
} catch (IOException ioe) {
logger.error(ioe.getMessage(), ioe);
throw new RuntimeException("Can't initialize database", ioe);
}
logger.debug("<~ LevelDbDataSource.init(): " + name);
} finally {
resetDbLock.writeLock().unlock();
}
}
private Path getPath() {
return Paths.get(config.databaseDir(), name);
}
@Override
public void reset() {
close();
FileUtil.recursiveDelete(getPath().toString());
init(settings);
}
@Override
public byte[] prefixLookup(byte[] key, int prefixBytes) {
throw new RuntimeException("LevelDbDataSource.prefixLookup() is not supported");
}
@Override
public boolean isAlive() {
return alive;
}
public void destroyDB(File fileLocation) {
resetDbLock.writeLock().lock();
try {
logger.debug("Destroying existing database: " + fileLocation);
Options options = new Options();
try {
factory.destroy(fileLocation, options);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
} finally {
resetDbLock.writeLock().unlock();
}
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public byte[] get(byte[] key) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.get(): " + name + ", key: " + toHexString(key));
try {
byte[] ret = db.get(key);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.get(): " + name + ", key: " + toHexString(key) + ", " + (ret == null ? "null" : ret.length));
return ret;
} catch (DBException e) {
logger.warn("Exception. Retrying again...", e);
byte[] ret = db.get(key);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.get(): " + name + ", key: " + toHexString(key) + ", " + (ret == null ? "null" : ret.length));
return ret;
}
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public void put(byte[] key, byte[] value) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.put(): " + name + ", key: " + toHexString(key) + ", " + (value == null ? "null" : value.length));
db.put(key, value);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.put(): " + name + ", key: " + toHexString(key) + ", " + (value == null ? "null" : value.length));
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public void delete(byte[] key) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.delete(): " + name + ", key: " + toHexString(key));
db.delete(key);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.delete(): " + name + ", key: " + toHexString(key));
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public Set<byte[]> keys() {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.keys(): " + name);
try (DBIterator iterator = db.iterator()) {
Set<byte[]> result = new HashSet<>();
for (iterator.seekToFirst(); iterator.hasNext(); iterator.next()) {
result.add(iterator.peekNext().getKey());
}
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.keys(): " + name + ", " + result.size());
return result;
} catch (IOException e) {
logger.error("Unexpected", e);
throw new RuntimeException(e);
}
} finally {
resetDbLock.readLock().unlock();
}
}
private void updateBatchInternal(Map<byte[], byte[]> rows) throws IOException {
try (WriteBatch batch = db.createWriteBatch()) {
for (Map.Entry<byte[], byte[]> entry : rows.entrySet()) {
if (entry.getValue() == null) {
batch.delete(entry.getKey());
} else {
batch.put(entry.getKey(), entry.getValue());
}
}
db.write(batch);
}
}
@Override
public void updateBatch(Map<byte[], byte[]> rows) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.updateBatch(): " + name + ", " + rows.size());
try {
updateBatchInternal(rows);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.updateBatch(): " + name + ", " + rows.size());
} catch (Exception e) {
logger.error("Error, retrying one more time...", e);
// try one more time
try {
updateBatchInternal(rows);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.updateBatch(): " + name + ", " + rows.size());
} catch (Exception e1) {
logger.error("Error", e);
throw new RuntimeException(e);
}
}
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public boolean flush() {
return false;
}
@Override
public void close() {
resetDbLock.writeLock().lock();
try {
if (!isAlive()) return;
try {
logger.debug("Close db: {}", name);
db.close();
alive = false;
} catch (IOException e) {
logger.error("Failed to find the db file on the close: {} ", name);
}
} finally {
resetDbLock.writeLock().unlock();
}
}
}
| 11,487
| 35.938907
| 179
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/datasource/rocksdb/RocksDbDataSource.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource.rocksdb;
import org.ethereum.config.SystemProperties;
import org.ethereum.datasource.DbSettings;
import org.ethereum.datasource.DbSource;
import org.ethereum.datasource.NodeKeyCompositor;
import org.ethereum.util.FileUtil;
import org.rocksdb.*;
import org.rocksdb.CompressionType;
import org.rocksdb.Options;
import org.rocksdb.WriteBatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static java.lang.System.arraycopy;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* @author Mikhail Kalinin
* @since 28.11.2017
*/
public class RocksDbDataSource implements DbSource<byte[]> {
private static final Logger logger = LoggerFactory.getLogger("db");
@Autowired
SystemProperties config = SystemProperties.getDefault(); // initialized for standalone test
String name;
RocksDB db;
ReadOptions readOpts;
boolean alive;
DbSettings settings = DbSettings.DEFAULT;
// The native RocksDB insert/update/delete are normally thread-safe
// However close operation is not thread-safe.
// This ReadWriteLock still permits concurrent execution of insert/delete/update operations
// however blocks them on init/close/delete operations
private ReadWriteLock resetDbLock = new ReentrantReadWriteLock();
static {
RocksDB.loadLibrary();
}
public RocksDbDataSource() {
}
public RocksDbDataSource(String name) {
this.name = name;
logger.debug("New RocksDbDataSource: " + name);
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public void init() {
init(DbSettings.DEFAULT);
}
@Override
public void init(DbSettings settings) {
this.settings = settings;
resetDbLock.writeLock().lock();
try {
logger.debug("~> RocksDbDataSource.init(): " + name);
if (isAlive()) return;
if (name == null) throw new NullPointerException("no name set to the db");
try (Options options = new Options()) {
// most of these options are suggested by https://github.com/facebook/rocksdb/wiki/Set-Up-Options
// general options
options.setCreateIfMissing(true);
options.setCompressionType(CompressionType.LZ4_COMPRESSION);
options.setBottommostCompressionType(CompressionType.ZSTD_COMPRESSION);
options.setLevelCompactionDynamicLevelBytes(true);
options.setMaxOpenFiles(settings.getMaxOpenFiles());
options.setIncreaseParallelism(settings.getMaxThreads());
// key prefix for state node lookups
options.useFixedLengthPrefixExtractor(NodeKeyCompositor.PREFIX_BYTES);
// table options
final BlockBasedTableConfig tableCfg;
options.setTableFormatConfig(tableCfg = new BlockBasedTableConfig());
tableCfg.setBlockSize(16 * 1024);
tableCfg.setBlockCacheSize(32 * 1024 * 1024);
tableCfg.setCacheIndexAndFilterBlocks(true);
tableCfg.setPinL0FilterAndIndexBlocksInCache(true);
tableCfg.setFilter(new BloomFilter(10, false));
// read options
readOpts = new ReadOptions();
readOpts = readOpts.setPrefixSameAsStart(true)
.setVerifyChecksums(false);
try {
logger.debug("Opening database");
final Path dbPath = getPath();
if (!Files.isSymbolicLink(dbPath.getParent())) Files.createDirectories(dbPath.getParent());
if (config.databaseFromBackup() && backupPath().toFile().canWrite()) {
logger.debug("Restoring database from backup: '{}'", name);
try (BackupableDBOptions backupOptions = new BackupableDBOptions(backupPath().toString());
RestoreOptions restoreOptions = new RestoreOptions(false);
BackupEngine backups = BackupEngine.open(Env.getDefault(), backupOptions)) {
if (!backups.getBackupInfo().isEmpty()) {
backups.restoreDbFromLatestBackup(getPath().toString(), getPath().toString(),
restoreOptions);
}
} catch (RocksDBException e) {
logger.error("Failed to restore database '{}' from backup", name, e);
}
}
logger.debug("Initializing new or existing database: '{}'", name);
try {
db = RocksDB.open(options, dbPath.toString());
} catch (RocksDBException e) {
logger.error(e.getMessage(), e);
throw new RuntimeException("Failed to initialize database", e);
}
alive = true;
} catch (IOException ioe) {
logger.error(ioe.getMessage(), ioe);
throw new RuntimeException("Failed to initialize database", ioe);
}
logger.debug("<~ RocksDbDataSource.init(): " + name);
}
} finally {
resetDbLock.writeLock().unlock();
}
}
public void backup() {
resetDbLock.readLock().lock();
if (logger.isTraceEnabled()) logger.trace("~> RocksDbDataSource.backup(): " + name);
Path path = backupPath();
path.toFile().mkdirs();
try (BackupableDBOptions backupOptions = new BackupableDBOptions(path.toString());
BackupEngine backups = BackupEngine.open(Env.getDefault(), backupOptions)) {
backups.createNewBackup(db, true);
if (logger.isTraceEnabled()) logger.trace("<~ RocksDbDataSource.backup(): " + name + " done");
} catch (RocksDBException e) {
logger.error("Failed to backup database '{}'", name, e);
hintOnTooManyOpenFiles(e);
throw new RuntimeException(e);
} finally {
resetDbLock.readLock().unlock();
}
}
private Path backupPath() {
return Paths.get(config.databaseDir(), "backup", name);
}
@Override
public boolean isAlive() {
return alive;
}
@Override
public void close() {
resetDbLock.writeLock().lock();
try {
if (!isAlive()) return;
logger.debug("Close db: {}", name);
db.close();
readOpts.close();
alive = false;
} catch (Exception e) {
logger.error("Error closing db '{}'", name, e);
} finally {
resetDbLock.writeLock().unlock();
}
}
@Override
public Set<byte[]> keys() throws RuntimeException {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> RocksDbDataSource.keys(): " + name);
try (RocksIterator iterator = db.newIterator()) {
Set<byte[]> result = new HashSet<>();
for (iterator.seekToFirst(); iterator.isValid(); iterator.next()) {
result.add(iterator.key());
}
if (logger.isTraceEnabled()) logger.trace("<~ RocksDbDataSource.keys(): " + name + ", " + result.size());
return result;
} catch (Exception e) {
logger.error("Error iterating db '{}'", name, e);
hintOnTooManyOpenFiles(e);
throw new RuntimeException(e);
}
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public void reset() {
close();
FileUtil.recursiveDelete(getPath().toString());
init(settings);
}
private Path getPath() {
return Paths.get(config.databaseDir(), name);
}
@Override
public void updateBatch(Map<byte[], byte[]> rows) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> RocksDbDataSource.updateBatch(): " + name + ", " + rows.size());
try {
try (WriteBatch batch = new WriteBatch();
WriteOptions writeOptions = new WriteOptions()) {
for (Map.Entry<byte[], byte[]> entry : rows.entrySet()) {
if (entry.getValue() == null) {
batch.remove(entry.getKey());
} else {
batch.put(entry.getKey(), entry.getValue());
}
}
db.write(writeOptions, batch);
}
if (logger.isTraceEnabled()) logger.trace("<~ RocksDbDataSource.updateBatch(): " + name + ", " + rows.size());
} catch (RocksDBException e) {
logger.error("Error in batch update on db '{}'", name, e);
hintOnTooManyOpenFiles(e);
throw new RuntimeException(e);
}
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public void put(byte[] key, byte[] val) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> RocksDbDataSource.put(): " + name + ", key: " + toHexString(key) + ", " + (val == null ? "null" : val.length));
if (val != null) {
db.put(key, val);
} else {
db.delete(key);
}
if (logger.isTraceEnabled()) logger.trace("<~ RocksDbDataSource.put(): " + name + ", key: " + toHexString(key) + ", " + (val == null ? "null" : val.length));
} catch (RocksDBException e) {
logger.error("Failed to put into db '{}'", name, e);
hintOnTooManyOpenFiles(e);
throw new RuntimeException(e);
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public byte[] get(byte[] key) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> RocksDbDataSource.get(): " + name + ", key: " + toHexString(key));
byte[] ret = db.get(readOpts, key);
if (logger.isTraceEnabled()) logger.trace("<~ RocksDbDataSource.get(): " + name + ", key: " + toHexString(key) + ", " + (ret == null ? "null" : ret.length));
return ret;
} catch (RocksDBException e) {
logger.error("Failed to get from db '{}'", name, e);
hintOnTooManyOpenFiles(e);
throw new RuntimeException(e);
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public void delete(byte[] key) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> RocksDbDataSource.delete(): " + name + ", key: " + toHexString(key));
db.delete(key);
if (logger.isTraceEnabled()) logger.trace("<~ RocksDbDataSource.delete(): " + name + ", key: " + toHexString(key));
} catch (RocksDBException e) {
logger.error("Failed to delete from db '{}'", name, e);
throw new RuntimeException(e);
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public byte[] prefixLookup(byte[] key, int prefixBytes) {
if (prefixBytes != NodeKeyCompositor.PREFIX_BYTES)
throw new RuntimeException("RocksDbDataSource.prefixLookup() supports only " + prefixBytes + "-bytes prefix");
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> RocksDbDataSource.prefixLookup(): " + name + ", key: " + toHexString(key));
// RocksDB sets initial position of iterator to the first key which is greater or equal to the seek key
// since keys in RocksDB are ordered in asc order iterator must be initiated with the lowest key
// thus bytes with indexes greater than PREFIX_BYTES must be nullified
byte[] prefix = new byte[NodeKeyCompositor.PREFIX_BYTES];
arraycopy(key, 0, prefix, 0, NodeKeyCompositor.PREFIX_BYTES);
byte[] ret = null;
try (RocksIterator it = db.newIterator(readOpts)) {
it.seek(prefix);
if (it.isValid())
ret = it.value();
} catch (Exception e) {
logger.error("Failed to seek by prefix in db '{}'", name, e);
hintOnTooManyOpenFiles(e);
throw new RuntimeException(e);
}
if (logger.isTraceEnabled()) logger.trace("<~ RocksDbDataSource.prefixLookup(): " + name + ", key: " + toHexString(key) + ", " + (ret == null ? "null" : ret.length));
return ret;
} finally {
resetDbLock.readLock().unlock();
}
}
@Override
public boolean flush() {
return false;
}
private void hintOnTooManyOpenFiles(Exception e) {
if (e.getMessage() != null && e.getMessage().toLowerCase().contains("too many open files")) {
logger.info("");
logger.info(" Mitigating 'Too many open files':");
logger.info(" either decrease value of database.maxOpenFiles parameter in ethereumj.conf");
logger.info(" or set higher limit by using 'ulimit -n' command in command line");
logger.info("");
}
}
}
| 14,900
| 36.724051
| 178
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/facade/PendingState.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.facade;
import org.ethereum.core.*;
import java.util.List;
import java.util.Set;
/**
* @author Mikhail Kalinin
* @since 28.09.2015
*/
public interface PendingState {
/**
* @return pending state repository
*/
org.ethereum.core.Repository getRepository();
/**
* @return list of pending transactions
*/
List<Transaction> getPendingTransactions();
}
| 1,201
| 28.317073
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/facade/EthereumFactory.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.facade;
import org.ethereum.config.DefaultConfig;
import org.ethereum.config.SystemProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;
/**
* @author Roman Mandeleil
* @since 13.11.2014
*/
@Component
public class EthereumFactory {
private static final Logger logger = LoggerFactory.getLogger("general");
public static Ethereum createEthereum() {
return createEthereum((Class) null);
}
public static Ethereum createEthereum(Class userSpringConfig) {
return userSpringConfig == null ? createEthereum(new Class[] {DefaultConfig.class}) :
createEthereum(DefaultConfig.class, userSpringConfig);
}
/**
* @deprecated The config parameter is not used anymore. The configuration is passed
* via 'systemProperties' bean either from the DefaultConfig or from supplied userSpringConfig
* @param config Not used
* @param userSpringConfig User Spring configuration class
* @return Fully initialized Ethereum instance
*/
public static Ethereum createEthereum(SystemProperties config, Class userSpringConfig) {
return userSpringConfig == null ? createEthereum(new Class[] {DefaultConfig.class}) :
createEthereum(DefaultConfig.class, userSpringConfig);
}
public static Ethereum createEthereum(Class ... springConfigs) {
logger.info("Starting EthereumJ...");
AbstractApplicationContext context = new AnnotationConfigApplicationContext(springConfigs);
context.registerShutdownHook();
return context.getBean(Ethereum.class);
}
}
| 2,668
| 37.681159
| 99
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/facade/SyncStatus.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.facade;
/**
* Represents the current state of syncing process
*/
public class SyncStatus {
public enum SyncStage {
/**
* Fast sync: looking for a Pivot block.
* Normally we need several peers to select the block but
* the block can be selected from existing peers due to timeout
*/
PivotBlock,
/**
* Fast sync: downloading state trie nodes and importing blocks
*/
StateNodes,
/**
* Fast sync: downloading headers for securing the latest state
*/
Headers,
/**
* Fast sync: downloading blocks
*/
BlockBodies,
/**
* Fast sync: downloading receipts
*/
Receipts,
/**
* Regular sync is in progress
*/
Regular,
/**
* Sync is complete:
* Fast sync: the state is secure, all blocks and receipt are downloaded
* Regular sync: all blocks are imported up to the blockchain head
*/
Complete,
/**
* Syncing is turned off
*/
Off;
/**
* Indicates if this state represents ongoing FastSync
*/
public boolean isFastSync() {
return this == PivotBlock || this == StateNodes || this == Headers || this == BlockBodies || this == Receipts;
}
/**
* Indicates the current state is secure
*
* When doing fast sync UNSECURE sync means that the full state is downloaded,
* chain is on the latest block, and blockchain operations may be executed
* (such as state querying, transaction submission)
* but the state isn't yet confirmed with the whole block chain and can't be
* trusted.
* At this stage historical blocks and receipts are unavailable yet
*
* SECURE sync means that the full state is downloaded,
* chain is on the latest block, and blockchain operations may be executed
* (such as state querying, transaction submission)
* The state is now confirmed by the full chain (all block headers are
* downloaded and verified) and can be trusted
* At this stage historical blocks and receipts are unavailable yet
*/
public boolean isSecure() {
return this != PivotBlock || this != StateNodes && this != Headers;
}
/**
* Indicates the blockchain state is up-to-date
* Warning: the state could still be non-secure
*/
public boolean hasLatestState() {
return this == Headers || this == BlockBodies || this == Receipts || this == Complete;
}
}
private final SyncStage stage;
private final long curCnt;
private final long knownCnt;
private final long blockLastImported;
private final long blockBestKnown;
public SyncStatus(SyncStatus state, long blockLastImported, long blockBestKnown) {
this(state.getStage(), state.getCurCnt(), state.getKnownCnt(), blockLastImported, blockBestKnown);
}
public SyncStatus(SyncStage stage, long curCnt, long knownCnt, long blockLastImported, long blockBestKnown) {
this.stage = stage;
this.curCnt = curCnt;
this.knownCnt = knownCnt;
this.blockLastImported = blockLastImported;
this.blockBestKnown = blockBestKnown;
}
public SyncStatus(SyncStage stage, long curCnt, long knownCnt) {
this(stage, curCnt, knownCnt, 0, 0);
}
/**
* Gets the current stage of syncing
*/
public SyncStage getStage() {
return stage;
}
/**
* Gets the current count of items processed for this syncing stage :
* PivotBlock: number of seconds pivot block is searching for
* ( this number can be greater than getKnownCnt() if no peers found)
* StateNodes: number of trie nodes downloaded
* Headers: number of headers downloaded
* BlockBodies: number of block bodies downloaded
* Receipts: number of blocks receipts are downloaded for
*/
public long getCurCnt() {
return curCnt;
}
/**
* Gets the known count of items for this syncing stage :
* PivotBlock: number of seconds pivot is forced to be selected
* StateNodes: number of currently known trie nodes. This number is not constant as new nodes
* are discovered when their parent is downloaded
* Headers: number of headers to be downloaded
* BlockBodies: number of block bodies to be downloaded
* Receipts: number of blocks receipts are to be downloaded for
*/
public long getKnownCnt() {
return knownCnt;
}
/**
* Reflects the blockchain state: the latest imported block
* Blocks importing can run in parallel with other sync stages
* (like header/blocks/receipts downloading)
*/
public long getBlockLastImported() {
return blockLastImported;
}
/**
* Return the best known block from other peers
*/
public long getBlockBestKnown() {
return blockBestKnown;
}
@Override
public String toString() {
return stage +
(stage != SyncStage.Off && stage != SyncStage.Complete ? " (" + getCurCnt() + " of " + getKnownCnt() + ")" : "") +
", last block #" + getBlockLastImported() + ", best known #" + getBlockBestKnown();
}
}
| 6,273
| 34.446328
| 130
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/facade/EthereumImpl.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.facade;
import org.ethereum.config.BlockchainConfig;
import org.ethereum.config.CommonConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.*;
import org.ethereum.core.PendingState;
import org.ethereum.core.Repository;
import org.ethereum.crypto.ECKey;
import org.ethereum.listener.CompositeEthereumListener;
import org.ethereum.listener.EthereumListener;
import org.ethereum.listener.GasPriceTracker;
import org.ethereum.manager.AdminInfo;
import org.ethereum.manager.BlockLoader;
import org.ethereum.manager.WorldManager;
import org.ethereum.mine.BlockMiner;
import org.ethereum.net.client.PeerClient;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.ChannelManager;
import org.ethereum.net.shh.Whisper;
import org.ethereum.net.submit.TransactionExecutor;
import org.ethereum.net.submit.TransactionTask;
import org.ethereum.sync.SyncManager;
import org.ethereum.util.ByteUtil;
import org.ethereum.vm.hook.VMHook;
import org.ethereum.vm.program.ProgramResult;
import org.ethereum.vm.program.invoke.ProgramInvokeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.FutureAdapter;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* @author Roman Mandeleil
* @since 27.07.2014
*/
@Component
public class EthereumImpl implements Ethereum, SmartLifecycle {
private static final Logger logger = LoggerFactory.getLogger("facade");
private static final Logger gLogger = LoggerFactory.getLogger("general");
@Autowired
WorldManager worldManager;
@Autowired
AdminInfo adminInfo;
@Autowired
ChannelManager channelManager;
@Autowired
ApplicationContext ctx;
@Autowired
BlockLoader blockLoader;
@Autowired
ProgramInvokeFactory programInvokeFactory;
@Autowired
Whisper whisper;
@Autowired
PendingState pendingState;
@Autowired
SyncManager syncManager;
@Autowired
CommonConfig commonConfig = CommonConfig.getDefault();
private SystemProperties config;
private CompositeEthereumListener compositeEthereumListener;
private GasPriceTracker gasPriceTracker = new GasPriceTracker();
@Autowired
public EthereumImpl(final SystemProperties config, final CompositeEthereumListener compositeEthereumListener) {
this.compositeEthereumListener = compositeEthereumListener;
this.config = config;
System.out.println();
this.compositeEthereumListener.addListener(gasPriceTracker);
gLogger.info("EthereumJ node started: enode://" + toHexString(config.nodeId()) + "@" + config.externalIp() + ":" + config.listenPort());
}
@Override
public void startPeerDiscovery() {
worldManager.startPeerDiscovery();
}
@Override
public void stopPeerDiscovery() {
worldManager.stopPeerDiscovery();
}
@Override
public void connect(InetAddress addr, int port, String remoteId) {
connect(addr.getHostName(), port, remoteId);
}
@Override
public void connect(final String ip, final int port, final String remoteId) {
logger.debug("Connecting to: {}:{}", ip, port);
worldManager.getActivePeer().connectAsync(ip, port, remoteId, false);
}
@Override
public void connect(Node node) {
connect(node.getHost(), node.getPort(), Hex.toHexString(node.getId()));
}
@Override
public org.ethereum.facade.Blockchain getBlockchain() {
return (org.ethereum.facade.Blockchain) worldManager.getBlockchain();
}
public ImportResult addNewMinedBlock(Block block) {
ImportResult importResult = worldManager.getBlockchain().tryToConnect(block);
if (importResult == ImportResult.IMPORTED_BEST) {
channelManager.sendNewBlock(block);
}
return importResult;
}
@Override
public BlockMiner getBlockMiner() {
return ctx.getBean(BlockMiner.class);
}
@Override
public void addListener(EthereumListener listener) {
worldManager.addListener(listener);
}
@Override
public void close() {
logger.info("### Shutdown initiated ### ");
((AbstractApplicationContext) getApplicationContext()).close();
}
@Override
public SyncStatus getSyncStatus() {
return syncManager.getSyncStatus();
}
@Override
public PeerClient getDefaultPeer() {
return worldManager.getActivePeer();
}
@Override
public boolean isConnected() {
return worldManager.getActivePeer() != null;
}
@Override
public Transaction createTransaction(BigInteger nonce,
BigInteger gasPrice,
BigInteger gas,
byte[] receiveAddress,
BigInteger value, byte[] data) {
byte[] nonceBytes = ByteUtil.bigIntegerToBytes(nonce);
byte[] gasPriceBytes = ByteUtil.bigIntegerToBytes(gasPrice);
byte[] gasBytes = ByteUtil.bigIntegerToBytes(gas);
byte[] valueBytes = ByteUtil.bigIntegerToBytes(value);
return new Transaction(nonceBytes, gasPriceBytes, gasBytes,
receiveAddress, valueBytes, data, getChainIdForNextBlock());
}
@Override
public Future<Transaction> submitTransaction(Transaction transaction) {
TransactionTask transactionTask = new TransactionTask(transaction, channelManager);
final Future<List<Transaction>> listFuture =
TransactionExecutor.instance.submitTransaction(transactionTask);
pendingState.addPendingTransaction(transaction);
return new FutureAdapter<Transaction, List<Transaction>>(listFuture) {
@Override
protected Transaction adapt(List<Transaction> adapteeResult) throws ExecutionException {
return adapteeResult.get(0);
}
};
}
@Override
public TransactionReceipt callConstant(Transaction tx, Block block) {
if (tx.getSignature() == null) {
tx.sign(ECKey.DUMMY);
}
return callConstantImpl(tx, block).getReceipt();
}
@Override
public BlockSummary replayBlock(Block block) {
List<TransactionReceipt> receipts = new ArrayList<>();
List<TransactionExecutionSummary> summaries = new ArrayList<>();
Block parent = worldManager.getBlockchain().getBlockByHash(block.getParentHash());
if (parent == null) {
logger.info("Failed to replay block #{}, its ancestor is not presented in the db", block.getNumber());
return new BlockSummary(block, new HashMap<byte[], BigInteger>(), receipts, summaries);
}
Repository track = ((Repository) worldManager.getRepository())
.getSnapshotTo(parent.getStateRoot());
try {
for (Transaction tx : block.getTransactionsList()) {
Repository txTrack = track.startTracking();
org.ethereum.core.TransactionExecutor executor = new org.ethereum.core.TransactionExecutor(
tx, block.getCoinbase(), txTrack, worldManager.getBlockStore(),
programInvokeFactory, block, worldManager.getListener(), 0, VMHook.EMPTY)
.withCommonConfig(commonConfig);
executor.init();
executor.execute();
executor.go();
TransactionExecutionSummary summary = executor.finalization();
txTrack.commit();
TransactionReceipt receipt = executor.getReceipt();
receipt.setPostTxState(track.getRoot());
receipts.add(receipt);
summaries.add(summary);
}
} finally {
track.rollback();
}
return new BlockSummary(block, new HashMap<byte[], BigInteger>(), receipts, summaries);
}
private org.ethereum.core.TransactionExecutor callConstantImpl(Transaction tx, Block block) {
Repository repository = ((Repository) worldManager.getRepository())
.getSnapshotTo(block.getStateRoot())
.startTracking();
try {
org.ethereum.core.TransactionExecutor executor = new org.ethereum.core.TransactionExecutor
(tx, block.getCoinbase(), repository, worldManager.getBlockStore(),
programInvokeFactory, block)
.withCommonConfig(commonConfig)
.setLocalCall(true);
executor.init();
executor.execute();
executor.go();
executor.finalization();
return executor;
} finally {
repository.rollback();
}
}
@Override
public ProgramResult callConstantFunction(String receiveAddress,
CallTransaction.Function function, Object... funcArgs) {
return callConstantFunction(receiveAddress, ECKey.DUMMY, function, funcArgs);
}
@Override
public ProgramResult callConstantFunction(String receiveAddress, ECKey senderPrivateKey,
CallTransaction.Function function, Object... funcArgs) {
Transaction tx = CallTransaction.createCallTransaction(0, 0, 100000000000000L,
receiveAddress, 0, function, funcArgs);
tx.sign(senderPrivateKey);
Block bestBlock = worldManager.getBlockchain().getBestBlock();
return callConstantImpl(tx, bestBlock).getResult();
}
@Override
public org.ethereum.facade.Repository getRepository() {
return worldManager.getRepository();
}
@Override
public org.ethereum.facade.Repository getLastRepositorySnapshot() {
return getSnapshotTo(getBlockchain().getBestBlock().getStateRoot());
}
@Override
public org.ethereum.facade.Repository getPendingState() {
return worldManager.getPendingState().getRepository();
}
@Override
public org.ethereum.facade.Repository getSnapshotTo(byte[] root) {
Repository repository = (Repository) worldManager.getRepository();
org.ethereum.facade.Repository snapshot = repository.getSnapshotTo(root);
return snapshot;
}
@Override
public AdminInfo getAdminInfo() {
return adminInfo;
}
@Override
public ChannelManager getChannelManager() {
return channelManager;
}
@Override
public List<Transaction> getWireTransactions() {
return worldManager.getPendingState().getPendingTransactions();
}
@Override
public List<Transaction> getPendingStateTransactions() {
return worldManager.getPendingState().getPendingTransactions();
}
@Override
public BlockLoader getBlockLoader() {
return blockLoader;
}
@Override
public Whisper getWhisper() {
return whisper;
}
@Override
public long getGasPrice() {
return gasPriceTracker.getGasPrice();
}
@Override
public Integer getChainIdForNextBlock() {
BlockchainConfig nextBlockConfig = config.getBlockchainConfig().getConfigForBlock(getBlockchain()
.getBestBlock().getNumber() + 1);
return nextBlockConfig.getChainId();
}
public CompletableFuture<Void> switchToShortSync() {
return syncManager.switchToShortSync();
}
@Override
public void exitOn(long number) {
worldManager.getBlockchain().setExitOn(number);
}
@Override
public void initSyncing() {
worldManager.initSyncing();
}
/**
* For testing purposes and 'hackers'
*/
public ApplicationContext getApplicationContext() {
return ctx;
}
@Override
public boolean isAutoStartup() {
return false;
}
/**
* Shutting down all app beans
*/
@Override
public void stop(Runnable callback) {
logger.info("Shutting down Ethereum instance...");
worldManager.close();
callback.run();
}
@Override
public void start() {}
@Override
public void stop() {}
@Override
public boolean isRunning() {
return true;
}
/**
* Called first on shutdown lifecycle
*/
@Override
public int getPhase() {
return Integer.MAX_VALUE;
}
}
| 13,779
| 30.247166
| 144
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/facade/Ethereum.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.facade;
import org.ethereum.core.*;
import org.ethereum.crypto.ECKey;
import org.ethereum.listener.EthereumListener;
import org.ethereum.manager.AdminInfo;
import org.ethereum.manager.BlockLoader;
import org.ethereum.mine.BlockMiner;
import org.ethereum.net.client.PeerClient;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.ChannelManager;
import org.ethereum.net.shh.Whisper;
import org.ethereum.vm.program.ProgramResult;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
/**
* @author Roman Mandeleil
* @since 27.07.2014
*/
public interface Ethereum {
void startPeerDiscovery();
void stopPeerDiscovery();
void connect(InetAddress addr, int port, String remoteId);
void connect(String ip, int port, String remoteId);
void connect(Node node);
Blockchain getBlockchain();
void addListener(EthereumListener listener);
PeerClient getDefaultPeer();
boolean isConnected();
void close();
/**
* Gets the current sync state
*/
SyncStatus getSyncStatus();
/**
* Factory for general transaction
*
*
* @param nonce - account nonce, based on number of transaction submited by
* this account
* @param gasPrice - gas price bid by miner , the user ask can be based on
* lastr submited block
* @param gas - the quantity of gas requested for the transaction
* @param receiveAddress - the target address of the transaction
* @param value - the ether value of the transaction
* @param data - can be init procedure for creational transaction,
* also msg data for invoke transaction for only value
* transactions this one is empty.
* @return newly created transaction
*/
Transaction createTransaction(BigInteger nonce,
BigInteger gasPrice,
BigInteger gas,
byte[] receiveAddress,
BigInteger value, byte[] data);
/**
* @param transaction submit transaction to the net, return option to wait for net
* return this transaction as approved
*/
Future<Transaction> submitTransaction(Transaction transaction);
/**
* Executes the transaction based on the specified block but doesn't change the blockchain state
* and doesn't send the transaction to the network
* @param tx The transaction to execute. No need to sign the transaction and specify the correct nonce
* @param block Transaction is executed the same way as if it was executed after all transactions existing
* in that block. I.e. the root state is the same as this block's root state and this block
* is assumed to be the current block
* @return receipt of the executed transaction
*/
TransactionReceipt callConstant(Transaction tx, Block block);
/**
* Executes Txes of the block in the same order and from the same state root
* as they were executed during regular block import
* This method doesn't make changes in blockchain state
*
* <b>Note:</b> requires block's ancestor to be presented in the database
*
* @param block block to be replayed
* @return block summary with receipts and execution summaries
* <b>Note:</b> it doesn't include block rewards info
*/
BlockSummary replayBlock(Block block);
/**
* Call a contract function locally without sending transaction to the network
* and without changing contract storage.
* @param receiveAddress hex encoded contract address
* @param function contract function
* @param funcArgs function arguments
* @return function result. The return value can be fetched via {@link ProgramResult#getHReturn()}
* and decoded with {@link org.ethereum.core.CallTransaction.Function#decodeResult(byte[])}.
*/
ProgramResult callConstantFunction(String receiveAddress, CallTransaction.Function function,
Object... funcArgs);
/**
* Call a contract function locally without sending transaction to the network
* and without changing contract storage.
* @param receiveAddress hex encoded contract address
* @param senderPrivateKey Normally the constant call doesn't require a sender though
* in some cases it may affect the result (e.g. if function refers to msg.sender)
* @param function contract function
* @param funcArgs function arguments
* @return function result. The return value can be fetched via {@link ProgramResult#getHReturn()}
* and decoded with {@link org.ethereum.core.CallTransaction.Function#decodeResult(byte[])}.
*/
ProgramResult callConstantFunction(String receiveAddress, ECKey senderPrivateKey,
CallTransaction.Function function, Object... funcArgs);
/**
* Returns the Repository instance which always refers to the latest (best block) state
* It is always better using {@link #getLastRepositorySnapshot()} to work on immutable
* state as this instance can change its state between calls (when a new block is imported)
*
* @return - repository for all state data.
*/
Repository getRepository();
/**
* Returns the latest (best block) Repository snapshot
*/
Repository getLastRepositorySnapshot();
/**
* @return - pending state repository
*/
Repository getPendingState();
// 2. // is blockchain still loading - if buffer is not empty
Repository getSnapshotTo(byte[] root);
AdminInfo getAdminInfo();
ChannelManager getChannelManager();
/**
* @return - currently pending transactions received from the net
*/
List<Transaction> getWireTransactions();
/**
* @return - currently pending transactions sent to the net
*/
List<Transaction> getPendingStateTransactions();
BlockLoader getBlockLoader();
/**
* @return Whisper implementation if the protocol is available
*/
Whisper getWhisper();
/**
* Gets the Miner component
*/
BlockMiner getBlockMiner();
/**
* Initiates blockchain syncing process
*/
void initSyncing();
/**
* @deprecated
* Calculates a 'reasonable' Gas price based on statistics of the latest transaction's Gas prices
* Normally the price returned should be sufficient to execute a transaction since ~25% of the latest
* transactions were executed at this or lower price.
* If the transaction is wanted to be executed promptly with higher chances the returned price might
* be increased at some ratio (e.g. * 1.2)
*
* <b>UPDATED</b>: Old version of gas tracking greatly fluctuates in networks with big number of transactions
* like Ethereum MainNet. But it's light and simple and still could be used for test networks. If you
* want to get accurate recommended gas price use {@link org.ethereum.listener.RecommendedGasPriceTracker}
* instead by adding it to listener and polling data.
* Updated tracker is not enabled by default because it needs noticeable resources
* and is excessive for most users.
*/
@Deprecated
long getGasPrice();
/**
* Chain id for next block.
* Introduced in EIP-155
* @return chain id or null
*/
Integer getChainIdForNextBlock();
/**
* Manual switch to Short Sync mode
* Maybe useful in small private and detached networks when automatic detection fails
* @return Future, which completes when syncDone is turned to True in {@link org.ethereum.sync.SyncManager}
*/
CompletableFuture<Void> switchToShortSync();
void exitOn(long number);
}
| 8,812
| 36.029412
| 113
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/facade/Repository.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.facade;
import org.ethereum.vm.DataWord;
import javax.annotation.Nullable;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
public interface Repository {
/**
* @param addr - account to check
* @return - true if account exist,
* false otherwise
*/
boolean isExist(byte[] addr);
/**
* Retrieve balance of an account
*
* @param addr of the account
* @return balance of the account as a <code>BigInteger</code> value
*/
BigInteger getBalance(byte[] addr);
/**
* Get current nonce of a given account
*
* @param addr of the account
* @return value of the nonce
*/
BigInteger getNonce(byte[] addr);
/**
* Retrieve the code associated with an account
*
* @param addr of the account
* @return code in byte-array format
*/
byte[] getCode(byte[] addr);
/**
* Retrieve storage value from an account for a given key
*
* @param addr of the account
* @param key associated with this value
* @return data in the form of a <code>DataWord</code>
*/
DataWord getStorageValue(byte[] addr, DataWord key);
/**
* Retrieve storage size for a given account
*
* @param addr of the account
* @return storage entries count
*/
int getStorageSize(byte[] addr);
/**
* Retrieve all storage keys for a given account
*
* @param addr of the account
* @return set of storage keys or empty set if account with specified address not exists
*/
Set<DataWord> getStorageKeys(byte[] addr);
/**
* Retrieve storage entries from an account for given keys
*
* @param addr of the account
* @param keys
* @return storage entries for specified keys, or full storage if keys parameter is <code>null</code>
*/
Map<DataWord, DataWord> getStorage(byte[] addr, @Nullable Collection<DataWord> keys);
}
| 2,805
| 27.343434
| 105
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/facade/Blockchain.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.facade;
import org.ethereum.core.Block;
import org.ethereum.core.Transaction;
import org.ethereum.db.BlockStore;
import java.math.BigInteger;
import java.util.List;
import java.util.Set;
public interface Blockchain {
/**
* Get block by number from the best chain
* @param number - number of the block
* @return block by that number
*/
Block getBlockByNumber(long number);
/**
* Get block by hash
* @param hash - hash of the block
* @return - bloc by that hash
*/
Block getBlockByHash(byte[] hash);
/**
* Get total difficulty from the start
* and until the head of the chain
*
* @return - total difficulty
*/
BigInteger getTotalDifficulty();
/**
* Get the underlying BlockStore
* @return Blockstore
*/
BlockStore getBlockStore();
/**
* @return - last added block from blockchain
*/
Block getBestBlock();
/**
* Flush the content of local storage objects to disk
*/
void flush();
}
| 1,848
| 25.797101
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListener.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.listener;
import org.ethereum.core.*;
import org.ethereum.net.eth.message.StatusMessage;
import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.HelloMessage;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.Channel;
import java.util.List;
/**
* @author Roman Mandeleil
* @since 27.07.2014
*/
public interface EthereumListener {
enum PendingTransactionState {
/**
* Transaction may be dropped due to:
* - Invalid transaction (invalid nonce, low gas price, insufficient account funds,
* invalid signature)
* - Timeout (when pending transaction is not included to any block for
* last [transaction.outdated.threshold] blocks
* This is the final state
*/
DROPPED,
/**
* The same as PENDING when transaction is just arrived
* Next state can be either PENDING or INCLUDED
*/
NEW_PENDING,
/**
* State when transaction is not included to any blocks (on the main chain), and
* was executed on the last best block. The repository state is reflected in the PendingState
* Next state can be either INCLUDED, DROPPED (due to timeout)
* or again PENDING when a new block (without this transaction) arrives
*/
PENDING,
/**
* State when the transaction is included to a block.
* This could be the final state, however next state could also be
* PENDING: when a fork became the main chain but doesn't include this tx
* INCLUDED: when a fork became the main chain and tx is included into another
* block from the new main chain
* DROPPED: If switched to a new (long enough) main chain without this Tx
*/
INCLUDED;
public boolean isPending() {
return this == NEW_PENDING || this == PENDING;
}
}
enum SyncState {
/**
* When doing fast sync UNSECURE sync means that the full state is downloaded,
* chain is on the latest block, and blockchain operations may be executed
* (such as state querying, transaction submission)
* but the state isn't yet confirmed with the whole block chain and can't be
* trusted.
* At this stage historical blocks and receipts are unavailable yet
*/
UNSECURE,
/**
* When doing fast sync SECURE sync means that the full state is downloaded,
* chain is on the latest block, and blockchain operations may be executed
* (such as state querying, transaction submission)
* The state is now confirmed by the full chain (all block headers are
* downloaded and verified) and can be trusted
* At this stage historical blocks and receipts are unavailable yet
*/
SECURE,
/**
* Sync is fully complete. All blocks and receipts are downloaded.
*/
COMPLETE
}
void trace(String output);
void onNodeDiscovered(Node node);
void onHandShakePeer(Channel channel, HelloMessage helloMessage);
void onEthStatusUpdated(Channel channel, StatusMessage status);
void onRecvMessage(Channel channel, Message message);
void onSendMessage(Channel channel, Message message);
void onBlock(BlockSummary blockSummary);
default void onBlock(BlockSummary blockSummary, boolean best) {
onBlock(blockSummary);
}
void onPeerDisconnect(String host, long port);
/**
* @deprecated use onPendingTransactionUpdate filtering state NEW_PENDING
* Will be removed in the next release
*/
void onPendingTransactionsReceived(List<Transaction> transactions);
/**
* PendingState changes on either new pending transaction or new best block receive
* When a new transaction arrives it is executed on top of the current pending state
* When a new best block arrives the PendingState is adjusted to the new Repository state
* and all transactions which remain pending are executed on top of the new PendingState
*/
void onPendingStateChanged(PendingState pendingState);
/**
* Is called when PendingTransaction arrives, executed or dropped and included to a block
*
* @param txReceipt Receipt of the tx execution on the current PendingState
* @param state Current state of pending tx
* @param block The block which the current pending state is based on (for PENDING tx state)
* or the block which tx was included to (for INCLUDED state)
*/
void onPendingTransactionUpdate(TransactionReceipt txReceipt, PendingTransactionState state, Block block);
void onSyncDone(SyncState state);
void onNoConnections();
void onVMTraceCreated(String transactionHash, String trace);
void onTransactionExecuted(TransactionExecutionSummary summary);
void onPeerAddedToSyncPool(Channel peer);
}
| 5,798
| 36.655844
| 110
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/listener/TxStatus.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.listener;
/**
* Created by Anton Nashatyrev on 15.07.2016.
*/
public class TxStatus {
public static final TxStatus REJECTED = new TxStatus(0);
public static final TxStatus PENDING = new TxStatus(0);
public static TxStatus getConfirmed(int blocks) {
return new TxStatus(blocks);
}
public final int confirmed;
private TxStatus(int confirmed) {
this.confirmed = confirmed;
}
@Override
public String toString() {
if (this == REJECTED) return "REJECTED";
if (this == PENDING) return "PENDING";
return "CONFIRMED_" + confirmed;
}
}
| 1,424
| 31.386364
| 80
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/listener/CompositeEthereumListener.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.listener;
import org.ethereum.core.*;
import org.ethereum.net.eth.message.StatusMessage;
import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.HelloMessage;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author Roman Mandeleil
* @since 12.11.2014
*/
public class CompositeEthereumListener implements EthereumListener {
private static abstract class RunnableInfo implements Runnable {
private EthereumListener listener;
private String info;
public RunnableInfo(EthereumListener listener, String info) {
this.listener = listener;
this.info = info;
}
@Override
public String toString() {
return "RunnableInfo: " + info + " [listener: " + listener.getClass() + "]";
}
}
@Autowired
EventDispatchThread eventDispatchThread = EventDispatchThread.getDefault();
protected List<EthereumListener> listeners = new CopyOnWriteArrayList<>();
public void addListener(EthereumListener listener) {
listeners.add(listener);
}
public void removeListener(EthereumListener listener) {
listeners.remove(listener);
}
@Override
public void trace(final String output) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "trace") {
@Override
public void run() {
listener.trace(output);
}
});
}
}
@Override
public void onBlock(final BlockSummary blockSummary) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onBlock") {
@Override
public void run() {
listener.onBlock(blockSummary);
}
});
}
}
@Override
public void onBlock(final BlockSummary blockSummary, final boolean best) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onBlock") {
@Override
public void run() {
listener.onBlock(blockSummary, best);
}
});
}
}
@Override
public void onRecvMessage(final Channel channel, final Message message) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onRecvMessage") {
@Override
public void run() {
listener.onRecvMessage(channel, message);
}
});
}
}
@Override
public void onSendMessage(final Channel channel, final Message message) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onSendMessage") {
@Override
public void run() {
listener.onSendMessage(channel, message);
}
});
}
}
@Override
public void onPeerDisconnect(final String host, final long port) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onPeerDisconnect") {
@Override
public void run() {
listener.onPeerDisconnect(host, port);
}
});
}
}
@Override
public void onPendingTransactionsReceived(final List<Transaction> transactions) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onPendingTransactionsReceived") {
@Override
public void run() {
listener.onPendingTransactionsReceived(transactions);
}
});
}
}
@Override
public void onPendingStateChanged(final PendingState pendingState) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onPendingStateChanged") {
@Override
public void run() {
listener.onPendingStateChanged(pendingState);
}
});
}
}
@Override
public void onSyncDone(final SyncState state) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onSyncDone") {
@Override
public void run() {
listener.onSyncDone(state);
}
});
}
}
@Override
public void onNoConnections() {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onNoConnections") {
@Override
public void run() {
listener.onNoConnections();
}
});
}
}
@Override
public void onHandShakePeer(final Channel channel, final HelloMessage helloMessage) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onHandShakePeer") {
@Override
public void run() {
listener.onHandShakePeer(channel, helloMessage);
}
});
}
}
@Override
public void onVMTraceCreated(final String transactionHash, final String trace) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onVMTraceCreated") {
@Override
public void run() {
listener.onVMTraceCreated(transactionHash, trace);
}
});
}
}
@Override
public void onNodeDiscovered(final Node node) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onNodeDiscovered") {
@Override
public void run() {
listener.onNodeDiscovered(node);
}
});
}
}
@Override
public void onEthStatusUpdated(final Channel channel, final StatusMessage status) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onEthStatusUpdated") {
@Override
public void run() {
listener.onEthStatusUpdated(channel, status);
}
});
}
}
@Override
public void onTransactionExecuted(final TransactionExecutionSummary summary) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onTransactionExecuted") {
@Override
public void run() {
listener.onTransactionExecuted(summary);
}
});
}
}
@Override
public void onPeerAddedToSyncPool(final Channel peer) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onPeerAddedToSyncPool") {
@Override
public void run() {
listener.onPeerAddedToSyncPool(peer);
}
});
}
}
@Override
public void onPendingTransactionUpdate(final TransactionReceipt txReceipt, final PendingTransactionState state,
final Block block) {
for (final EthereumListener listener : listeners) {
eventDispatchThread.invokeLater(new RunnableInfo(listener, "onPendingTransactionUpdate") {
@Override
public void run() {
listener.onPendingTransactionUpdate(txReceipt, state, block);
}
});
}
}
}
| 9,287
| 33.4
| 115
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/listener/BlockReplay.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.listener;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.ethereum.core.*;
import org.ethereum.db.BlockStore;
import org.ethereum.db.TransactionStore;
import org.ethereum.net.eth.message.StatusMessage;
import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.HelloMessage;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.Channel;
import org.ethereum.util.FastByteComparisons;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import static org.ethereum.sync.BlockDownloader.MAX_IN_REQUEST;
/**
* Class capable of replaying stored blocks prior to 'going online' and
* notifying on newly imported blocks
*
* All other EthereumListener events are just forwarded to the supplied listener.
*
* For example of usage, look at {@link org.ethereum.samples.EventListenerSample}
*
* Created by Anton Nashatyrev on 18.07.2016.
*/
public class BlockReplay extends EthereumListenerAdapter {
private static final Logger logger = LoggerFactory.getLogger("events");
private static final int HALF_BUFFER = MAX_IN_REQUEST;
BlockStore blockStore;
TransactionStore transactionStore;
EthereumListener listener;
long firstBlock;
boolean replayComplete = false;
Block lastReplayedBlock;
CircularFifoQueue<BlockSummary> onBlockBuffer = new CircularFifoQueue<>(HALF_BUFFER * 2);
public BlockReplay(BlockStore blockStore, TransactionStore transactionStore, EthereumListener listener, long firstBlock) {
this.blockStore = blockStore;
this.transactionStore = transactionStore;
this.listener = listener;
this.firstBlock = firstBlock;
}
/**
* Replay blocks asynchronously
*/
public void replayAsync() {
new Thread(this::replay).start();
}
/**
* Replay blocks synchronously
*/
public void replay() {
long lastBlock = blockStore.getMaxNumber();
logger.info("Replaying blocks from " + firstBlock + ", current best block: " + lastBlock);
int cnt = 0;
long num = firstBlock;
while(!replayComplete) {
for (; num <= lastBlock; num++) {
replayBlock(num);
cnt++;
if (cnt % 1000 == 0) {
logger.info("Replayed " + cnt + " blocks so far. Current block: " + num);
}
}
synchronized (this) {
if (onBlockBuffer.size() < onBlockBuffer.maxSize()) {
replayComplete = true;
} else {
// So we'll have half of the buffer for new blocks until not synchronized replay finish
long newLastBlock = blockStore.getMaxNumber() - HALF_BUFFER;
if (lastBlock >= newLastBlock) {
replayComplete = true;
} else {
lastBlock = newLastBlock;
}
}
}
}
logger.info("Replay complete.");
}
private void replayBlock(long num) {
Block block = blockStore.getChainBlockByNumber(num);
lastReplayedBlock = block;
List<TransactionReceipt> receipts = new ArrayList<>();
for (Transaction tx : block.getTransactionsList()) {
TransactionInfo info = transactionStore.get(tx.getHash(), block.getHash());
TransactionReceipt receipt = info.getReceipt();
receipt.setTransaction(tx);
receipts.add(receipt);
}
BlockSummary blockSummary = new BlockSummary(block, null, receipts, null);
blockSummary.setTotalDifficulty(BigInteger.valueOf(num));
listener.onBlock(blockSummary);
}
@Override
public synchronized void onBlock(BlockSummary blockSummary) {
if (replayComplete) {
if (onBlockBuffer.isEmpty()) {
listener.onBlock(blockSummary);
} else {
logger.info("Replaying cached " + onBlockBuffer.size() + " blocks...");
boolean lastBlockFound = lastReplayedBlock == null || onBlockBuffer.size() < onBlockBuffer.maxSize();
for (BlockSummary block : onBlockBuffer) {
if (!lastBlockFound) {
lastBlockFound = FastByteComparisons.equal(block.getBlock().getHash(), lastReplayedBlock.getHash());
} else {
listener.onBlock(block);
}
}
onBlockBuffer.clear();
listener.onBlock(blockSummary);
logger.info("Cache replay complete. Switching to online mode.");
}
} else {
onBlockBuffer.add(blockSummary);
}
}
@Override
public void onPendingTransactionUpdate(TransactionReceipt transactionReceipt, PendingTransactionState pendingTransactionState, Block block) {
listener.onPendingTransactionUpdate(transactionReceipt, pendingTransactionState, block);
}
@Override
public void onPeerDisconnect(String s, long l) {
listener.onPeerDisconnect(s, l);
}
@Override
public void onPendingTransactionsReceived(List<Transaction> list) {
listener.onPendingTransactionsReceived(list);
}
@Override
public void onPendingStateChanged(PendingState pendingState) {
listener.onPendingStateChanged(pendingState);
}
@Override
public void onSyncDone(SyncState state) {
listener.onSyncDone(state);
}
@Override
public void onNoConnections() {
listener.onNoConnections();
}
@Override
public void onVMTraceCreated(String s, String s1) {
listener.onVMTraceCreated(s, s1);
}
@Override
public void onTransactionExecuted(TransactionExecutionSummary transactionExecutionSummary) {
listener.onTransactionExecuted(transactionExecutionSummary);
}
@Override
public void onPeerAddedToSyncPool(Channel channel) {
listener.onPeerAddedToSyncPool(channel);
}
@Override
public void trace(String s) {
listener.trace(s);
}
@Override
public void onNodeDiscovered(Node node) {
listener.onNodeDiscovered(node);
}
@Override
public void onHandShakePeer(Channel channel, HelloMessage helloMessage) {
listener.onHandShakePeer(channel, helloMessage);
}
@Override
public void onEthStatusUpdated(Channel channel, StatusMessage statusMessage) {
listener.onEthStatusUpdated(channel, statusMessage);
}
@Override
public void onRecvMessage(Channel channel, Message message) {
listener.onRecvMessage(channel, message);
}
@Override
public void onSendMessage(Channel channel, Message message) {
listener.onSendMessage(channel, message);
}
}
| 7,731
| 33.212389
| 145
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/listener/EventListener.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.listener;
import org.ethereum.core.Block;
import org.ethereum.core.BlockSummary;
import org.ethereum.core.Bloom;
import org.ethereum.core.CallTransaction;
import org.ethereum.core.PendingStateImpl;
import org.ethereum.core.TransactionReceipt;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.listener.EthereumListener.PendingTransactionState;
import org.ethereum.util.ByteArrayMap;
import org.ethereum.util.Utils;
import org.ethereum.vm.LogInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.ethereum.sync.BlockDownloader.MAX_IN_REQUEST;
import static org.ethereum.util.ByteUtil.toHexString;
/**
* The base class for tracking events generated by a Solidity contract
* For initializing the contract with its address use the [initContractAddress] method
* For initializing the contract with some topic and any address use the [initContractTopic] method
*
* Alternatively you could override initialization and [onLogMatch] method for very specific parsing
*
* For example of usage, look at {@link org.ethereum.samples.EventListenerSample}
*
* @param <EventData> this is the data generated by the implementing class for
* a Solidity Event. It is created by the [onEvent] implementation
*/
public abstract class EventListener<EventData> {
private static final Logger logger = LoggerFactory.getLogger("events");
/**
* The container class for [EventData] instance(s) with the respect
* to the transaction which generated events.
* The transaction pending state is tracked via
* - onPendingTransactionUpdate callback: to handle Tx state changes on block inclusion, rebranches and rejects
* - onBlock callback: to handle confirming blocks after the Tx is included
*/
protected class PendingEvent {
// The latest transaction receipt either pending/rejected or best branch included
public TransactionReceipt receipt;
// The Solidity Events (represented as EventData) generated by transaction
public List<EventData> eventData;
// null if pending/rejected
public Block includedTo;
// the latest block from the main branch
public Block bestConfirmingBlock;
// if came from a block we take block time, it pending we take current time
public long created;
// status of the Ethereum Tx
public TxStatus txStatus;
public PendingEvent(long created) {
this.created = created;
}
public void update(TransactionReceipt receipt, List<EventData> txs, PendingTransactionState state, Block includedTo) {
this.receipt = receipt;
this.eventData = txs;
this.bestConfirmingBlock = state == PendingTransactionState.INCLUDED ? includedTo : null;
this.includedTo = state == PendingTransactionState.INCLUDED ? includedTo : null;
txStatus = state.isPending() ? TxStatus.PENDING :
(state == PendingTransactionState.DROPPED ? TxStatus.REJECTED : TxStatus.getConfirmed(1));
}
public boolean setBestConfirmingBlock(Block bestConfirmingBlock) {
if (txStatus == TxStatus.REJECTED || txStatus == TxStatus.PENDING) return false;
if (this.bestConfirmingBlock.isEqual(bestConfirmingBlock)) return false;
this.bestConfirmingBlock = bestConfirmingBlock;
txStatus = TxStatus.getConfirmed((int) (bestConfirmingBlock.getNumber() - includedTo.getNumber() + 1));
return true;
}
@Override
public String toString() {
return "PendingEvent{" +
"eventData=" + eventData +
", includedTo=" + (includedTo == null ? "null" : includedTo.getShortDescr()) +
", bestConfirmingBlock=" + (bestConfirmingBlock == null ? "null" : bestConfirmingBlock.getShortDescr()) +
", created=" + created +
", txStatus=" + txStatus +
", tx=" + receipt.getTransaction() +
'}';
}
}
protected LogFilter logFilter;
protected CallTransaction.Contract contract;
protected PendingStateImpl pendingState;
private boolean initialized = false;
// txHash => PendingEvent
protected ByteArrayMap<PendingEvent> pendings = new ByteArrayMap<>(new LinkedHashMap<ByteArrayWrapper, PendingEvent>());
protected Block bestBlock;
BigInteger lastTotDiff = BigInteger.ZERO;
// executing EthereumListener callbacks on a separate thread to avoid long running
// handlers (die to DB access) messing up core
ExecutorService executor = Executors.newSingleThreadExecutor(r -> new Thread(r, EventListener.this.getClass().getSimpleName() + "-exec"));
public final EthereumListener listener = new EthereumListenerAdapter() {
@Override
public void onBlock(BlockSummary blockSummary) {
executor.submit(() -> onBlockImpl(blockSummary));
}
@Override
public void onPendingTransactionUpdate(TransactionReceipt txReceipt, PendingTransactionState state, Block block) {
executor.submit(() -> onPendingTransactionUpdateImpl(txReceipt, state, block));
}
};
public EventListener(PendingStateImpl pendingState) {
this.pendingState = pendingState;
}
public void onBlockImpl(BlockSummary blockSummary) {
if (!initialized) throw new RuntimeException("Event listener should be initialized");
try {
logger.debug("onBlock: " + blockSummary.getBlock().getShortDescr());
// ignoring spurious old blocks
if (bestBlock != null && blockSummary.getBlock().getNumber() < bestBlock.getNumber() - MAX_IN_REQUEST) {
logger.debug("Ignoring block as too old: " + blockSummary.getBlock().getShortDescr());
return;
}
if (logFilter.matchBloom(new Bloom(blockSummary.getBlock().getLogBloom()))) {
for (int i = 0; i < blockSummary.getReceipts().size(); i++) {
TransactionReceipt receipt = blockSummary.getReceipts().get(i);
if (logFilter.matchBloom(receipt.getBloomFilter())) {
if (!pendings.containsKey(receipt.getTransaction().getHash())) {
// ask PendingState to track candidate transactions from blocks since there is
// no guarantee the transaction of interest received as a pending
// on included transaction PendingState should call onPendingTransactionUpdateImpl
// with INCLUDED state
// if Tx was included into fork block PendingState should call onPendingTransactionUpdateImpl
// with PENDING state
pendingState.trackTransaction(receipt.getTransaction());
}
}
}
}
if (blockSummary.betterThan(lastTotDiff)) {
lastTotDiff = blockSummary.getTotalDifficulty();
bestBlock = blockSummary.getBlock();
// we need to update pendings bestConfirmingBlock
newBestBlock(blockSummary.getBlock());
}
} catch (Exception e) {
logger.error("Unexpected error while processing onBlock", e);
}
}
public void onPendingTransactionUpdateImpl(TransactionReceipt txReceipt, PendingTransactionState state, Block block) {
try {
if (state != PendingTransactionState.DROPPED || pendings.containsKey(txReceipt.getTransaction().getHash())) {
logger.debug("onPendingTransactionUpdate: " + toHexString(txReceipt.getTransaction().getHash()) + ", " + state);
}
onReceipt(txReceipt, block, state);
} catch (Exception e) {
logger.error("Unexpected error while processing onPendingTransactionUpdate", e);
}
}
/**
* Initialize listener with the contract of interest and its address
*/
public synchronized void initContractAddress(String abi, byte[] contractAddress) {
if (initialized) throw new RuntimeException("Already initialized");
contract = new CallTransaction.Contract(abi);
logFilter = new LogFilter().withContractAddress(contractAddress);
initialized = true;
}
/**
* Initialize listener with the contract of interest and topic to search for
*/
public synchronized void initContractTopic(String abi, byte[] topic) {
if (initialized) throw new RuntimeException("Already initialized");
contract = new CallTransaction.Contract(abi);
logFilter = new LogFilter().withTopic(topic);
initialized = true;
}
// checks the Tx receipt for the contract LogEvents
// initiated on [onPendingTransactionUpdateImpl] callback only
private synchronized void onReceipt(TransactionReceipt receipt, Block block, PendingTransactionState state) {
if (!initialized) throw new RuntimeException("Event listener should be initialized");
byte[] txHash = receipt.getTransaction().getHash();
if (logFilter.matchBloom(receipt.getBloomFilter())) {
int txCount = 0; // several transactions are possible withing a single Ethereum Tx
List<EventData> matchedTxs = new ArrayList<>();
for (LogInfo logInfo : receipt.getLogInfoList()) {
if (logFilter.matchBloom(logInfo.getBloom()) &&
logFilter.matchesExactly(logInfo)) {
// This is our contract event, asking implementing class to process it
EventData matchedTx = onLogMatch(logInfo, block, receipt, txCount, state);
// implementing class may return null if the event is not interesting
if (matchedTx != null) {
txCount++;
matchedTxs.add(matchedTx);
}
}
}
if (!matchedTxs.isEmpty()) {
// cool, we've got some Events from this Tx, let's track further Tx lifecycle
onEventData(receipt, block, state, matchedTxs);
}
} else if (state == PendingTransactionState.DROPPED && pendings.containsKey(txHash)) {
PendingEvent event = pendings.get(txHash);
onEventData(receipt, block, state, event.eventData);
}
}
// process the list of [EventData] generated by the Tx
// initiated on [onPendingTransactionUpdateImpl] callback only
private void onEventData(TransactionReceipt receipt, Block block,
PendingTransactionState state, List<EventData> matchedTxs) {
byte[] txHash = receipt.getTransaction().getHash();
PendingEvent event = pendings.get(txHash);
boolean newEvent = false;
if (event == null) {
// new Tx
event = new PendingEvent(state.isPending() ? Utils.toUnixTime(System.currentTimeMillis()) : block.getTimestamp());
pendings.put(txHash, event);
newEvent = true;
}
// If the Tx is not new, then update its data with the latest results
// Tx may change its state (and thus results) several times if it was included
// to block(s) from different fork branches
event.update(receipt, matchedTxs, state, block);
logger.debug("Event " + (newEvent ? "created" : "updated") + ": " + event);
if (pendingTransactionUpdated(event)) {
pendings.remove(txHash);
}
pendingTransactionsUpdated();
}
protected EventData onLogMatch(LogInfo logInfo, Block block, TransactionReceipt receipt, int txCount, PendingTransactionState state) {
CallTransaction.Invocation event = contract.parseEvent(logInfo);
if (event == null) {
logger.error("Can't parse log: " + logInfo);
return null;
}
return onEvent(event, block, receipt, txCount, state);
}
/**
* The implementing subclass should create an EventData instance with the data extracted from
* Solidity [event]
* @param event Representation of the Solidity event which contains ABI to parse Event arguments and the
* actual Event arguments
* @param block Either block where Tx was included, or PENDING block
* @param receipt
* @param txCount The sequence number of this event generated by this Tx. A single Tx might produce
* several Events of interest, so the unique key of an Event is TxHash + SeqNumber
* @param state The state of Transaction (Pending/Rejected/Included)
* @return Either null if this [event] is not interesting for implementation class, or [event] representation
*/
protected abstract EventData onEvent(CallTransaction.Invocation event, Block block, TransactionReceipt receipt,
int txCount, PendingTransactionState state);
/**
* Called after one or more transactions updated
* (normally on a new best block all the included Txs are updated with confirmed block)
*/
protected abstract void pendingTransactionsUpdated();
/**
* Called on a single transaction update
* @return true if the implementation is not interested in further tracking of this Tx
* (i.e. the transaction is assumed 100% confirmed or it was rejected)
*/
protected abstract boolean pendingTransactionUpdated(PendingEvent evt);
// Updates included [pendings] with a new confirming block
// and removes those we are not interested in anymore
private synchronized void newBestBlock(Block newBlock) {
List<byte[]> toRemove = new ArrayList<>();
boolean updated = false;
for (PendingEvent event : pendings.values()) {
if (event.setBestConfirmingBlock(newBlock)) {
boolean remove = pendingTransactionUpdated(event);
if (remove) {
logger.info("Removing event from pending: " + event);
toRemove.add(event.receipt.getTransaction().getHash());
}
updated = true;
}
}
pendings.keySet().removeAll(toRemove);
if (updated) {
pendingTransactionsUpdated();
}
}
}
| 15,517
| 45.600601
| 142
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/listener/GasPriceTracker.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.listener;
import org.ethereum.core.BlockSummary;
import org.ethereum.core.Transaction;
import org.ethereum.core.TransactionExecutionSummary;
import org.ethereum.util.ByteUtil;
import java.util.Arrays;
/**
* Calculates a 'reasonable' Gas price based on statistics of the latest transaction's Gas prices
*
* Normally the price returned should be sufficient to execute a transaction since ~25% of the latest
* transactions were executed at this or lower price.
*
* Created by Anton Nashatyrev on 22.09.2015.
*/
public class GasPriceTracker extends EthereumListenerAdapter {
private static final long defaultPrice = 70_000_000_000L;
private long[] window = new long[512];
private int idx = window.length - 1;
private boolean filled = false;
private long lastVal;
@Override
public void onBlock(BlockSummary blockSummary) {
for (Transaction tx : blockSummary.getBlock().getTransactionsList()) {
onTransaction(tx);
}
}
public void onTransaction(Transaction tx) {
if (idx == -1) {
idx = window.length - 1;
filled = true;
lastVal = 0; // recalculate only 'sometimes'
}
window[idx--] = ByteUtil.byteArrayToLong(tx.getGasPrice());
}
public long getGasPrice() {
if (!filled) {
return defaultPrice;
} else {
if (lastVal == 0) {
long[] longs = Arrays.copyOf(window, window.length);
Arrays.sort(longs);
lastVal = longs[longs.length / 4]; // 25% percentile
}
return lastVal;
}
}
}
| 2,450
| 32.121622
| 101
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListenerAdapter.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.listener;
import org.ethereum.core.*;
import org.ethereum.net.eth.message.StatusMessage;
import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.HelloMessage;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.Channel;
import java.util.List;
/**
* @author Roman Mandeleil
* @since 08.08.2014
*/
public class EthereumListenerAdapter implements EthereumListener {
@Override
public void trace(String output) {
}
public void onBlock(Block block, List<TransactionReceipt> receipts) {
}
@Override
public void onBlock(BlockSummary blockSummary) {
onBlock(blockSummary.getBlock(), blockSummary.getReceipts());
}
@Override
public void onRecvMessage(Channel channel, Message message) {
}
@Override
public void onSendMessage(Channel channel, Message message) {
}
@Override
public void onPeerDisconnect(String host, long port) {
}
@Override
public void onPendingTransactionsReceived(List<Transaction> transactions) {
}
@Override
public void onPendingStateChanged(PendingState pendingState) {
}
@Override
public void onSyncDone(SyncState state) {
}
@Override
public void onHandShakePeer(Channel channel, HelloMessage helloMessage) {
}
@Override
public void onNoConnections() {
}
@Override
public void onVMTraceCreated(String transactionHash, String trace) {
}
@Override
public void onNodeDiscovered(Node node) {
}
@Override
public void onEthStatusUpdated(Channel channel, StatusMessage statusMessage) {
}
@Override
public void onTransactionExecuted(TransactionExecutionSummary summary) {
}
@Override
public void onPeerAddedToSyncPool(Channel peer) {
}
@Override
public void onPendingTransactionUpdate(TransactionReceipt txReceipt, PendingTransactionState state, Block block) {
}
}
| 2,748
| 23.327434
| 118
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/listener/RecommendedGasPriceTracker.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.listener;
import org.ethereum.core.Block;
import org.ethereum.core.BlockSummary;
import org.ethereum.core.Transaction;
import org.ethereum.util.ByteUtil;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Calculates a 'reasonable' Gas price based on statistics of the latest transaction's Gas prices.
* This is an updated version that returns more accurate data
* in networks with large number of transactions like Ethereum MainNet.
* However it needs more CPU and memory resources for processing.
*
* Normally the price returned should be sufficient to execute a transaction since ~25%
* (if {@link #getPercentileShare()} is not overridden) of the latest transactions were
* executed at this or lower price.
*/
public class RecommendedGasPriceTracker extends EthereumListenerAdapter {
private static final Long DEFAULT_PRICE = null;
private static final int MIN_BLOCKS = 128;
private static final int BLOCKS_RECOUNT = 1;
private static final int MIN_TRANSACTIONS = 512;
private static final int PERCENTILE_SHARE = 4;
private LinkedList<long[]> blockGasPrices = new LinkedList<>();
private int idx = 0;
private Long recommendedGasPrice = getDefaultPrice();
@Override
public void onBlock(BlockSummary blockSummary) {
onBlock(blockSummary.getBlock());
}
protected void onBlock(Block block) {
if (onTransactions(block.getTransactionsList())) {
++idx;
if (idx >= getBlocksRecount()) {
Long newGasPrice = getGasPrice();
if (newGasPrice != null) {
this.recommendedGasPrice = newGasPrice;
}
idx = 0;
}
}
}
private synchronized boolean onTransactions(List<Transaction> txs) {
if (txs.isEmpty()) return false;
long[] gasPrices = new long[txs.size()];
for (int i = 0; i < txs.size(); ++i) {
gasPrices[i] = ByteUtil.byteArrayToLong(txs.get(i).getGasPrice());
}
blockGasPrices.add(gasPrices);
while (blockGasPrices.size() > getMinBlocks() &&
(calcGasPricesSize() - blockGasPrices.getFirst().length) >= getMinTransactions()) {
blockGasPrices.removeFirst();
}
return true;
}
private int calcGasPricesSize() {
return blockGasPrices.stream().map(Array::getLength).mapToInt(Integer::intValue).sum();
}
private synchronized Long getGasPrice() {
int size = calcGasPricesSize();
// Don't override default value until we have minTransactions and minBlocks
if (size < getMinTransactions() ||
blockGasPrices.size() < getMinBlocks()) return null;
long[] difficulties = new long[size];
int index = 0;
for (long[] currentBlock : blockGasPrices) {
for (long currentDifficulty : currentBlock) {
difficulties[index] = currentDifficulty;
++index;
}
}
Arrays.sort(difficulties);
return difficulties[difficulties.length/getPercentileShare()];
}
/**
* Returns recommended gas price calculated with class settings
* when enough data is gathered.
* Until this {@link #getDefaultPrice()} is returned
* @return recommended gas price for transaction
*/
public Long getRecommendedGasPrice() {
return recommendedGasPrice;
}
/**
* Override to set your value
*
* Minimum number of blocks used for recommended gas price calculation
* If minimum number of blocks includes less than {@link #getMinTransactions()} in total,
* data for blocks before last {@link #getMinBlocks()} is used when available
* @return minimum number of blocks
*/
public int getMinBlocks() {
return MIN_BLOCKS;
}
/**
* Override to set your value
*
* Used when not enough data gathered
* @return default transaction price
*/
public Long getDefaultPrice() {
return DEFAULT_PRICE;
}
/**
* Override to set your value
*
* Recount every N blocks
* @return number of blocks
*/
public int getBlocksRecount() {
return BLOCKS_RECOUNT;
}
/**
* Override to set your value
*
* Required number of gasPrice data from transactions
* to override default value on recount
* @return minimum number of transactions for calculation
*/
public int getMinTransactions() {
return MIN_TRANSACTIONS;
}
/**
* Override to set your value
*
* Defines lowest part share for difficulties slice
* So 4 means lowest 25%, 8 lowest 12.5% etc
* @return percentile share
*/
public int getPercentileShare() {
return PERCENTILE_SHARE;
}
}
| 5,699
| 31.571429
| 99
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/listener/LogFilter.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.listener;
import org.ethereum.core.Bloom;
import org.ethereum.vm.DataWord;
import org.ethereum.vm.LogInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.ethereum.crypto.HashUtil.sha3;
/**
* Created by Anton Nashatyrev on 12.04.2016.
*/
public class LogFilter {
private List<byte[][]> topics = new ArrayList<>(); // [[addr1, addr2], null, [A, B], [C]]
private byte[][] contractAddresses = new byte[0][];
private Bloom[][] filterBlooms;
public LogFilter withContractAddress(byte[] ... orAddress) {
contractAddresses = orAddress;
return this;
}
public LogFilter withTopic(byte[] ... orTopic) {
topics.add(orTopic);
return this;
}
private void initBlooms() {
if (filterBlooms != null) return;
List<byte[][]> addrAndTopics = new ArrayList<>(topics);
addrAndTopics.add(contractAddresses);
filterBlooms = new Bloom[addrAndTopics.size()][];
for (int i = 0; i < addrAndTopics.size(); i++) {
byte[][] orTopics = addrAndTopics.get(i);
if (orTopics == null || orTopics.length == 0) {
filterBlooms[i] = new Bloom[] {new Bloom()}; // always matches
} else {
filterBlooms[i] = new Bloom[orTopics.length];
for (int j = 0; j < orTopics.length; j++) {
filterBlooms[i][j] = Bloom.create(sha3(orTopics[j]));
}
}
}
}
public boolean matchBloom(Bloom blockBloom) {
initBlooms();
for (Bloom[] andBloom : filterBlooms) {
boolean orMatches = false;
for (Bloom orBloom : andBloom) {
if (blockBloom.matches(orBloom)) {
orMatches = true;
break;
}
}
if (!orMatches) return false;
}
return true;
}
public boolean matchesContractAddress(byte[] toAddr) {
initBlooms();
for (byte[] address : contractAddresses) {
if (Arrays.equals(address, toAddr)) return true;
}
return contractAddresses.length == 0;
}
public boolean matchesExactly(LogInfo logInfo) {
initBlooms();
if (!matchesContractAddress(logInfo.getAddress())) return false;
List<DataWord> logTopics = logInfo.getTopics();
for (int i = 0; i < this.topics.size(); i++) {
if (i >= logTopics.size()) return false;
byte[][] orTopics = topics.get(i);
if (orTopics != null && orTopics.length > 0) {
boolean orMatches = false;
DataWord logTopic = logTopics.get(i);
for (byte[] orTopic : orTopics) {
if (DataWord.of(orTopic).equals(logTopic)) {
orMatches = true;
break;
}
}
if (!orMatches) return false;
}
}
return true;
}
}
| 3,848
| 32.763158
| 95
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/json/JSONHelper.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.json;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.AccountState;
import org.ethereum.core.Block;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.db.ContractDetails;
import org.ethereum.core.Repository;
import org.ethereum.util.ByteUtil;
import org.ethereum.vm.DataWord;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* JSON Helper class to format data into ObjectNodes
* to match PyEthereum blockstate output
*
* Dump format:
* {
* "address":
* {
* "nonce": "n1",
* "balance": "b1",
* "stateRoot": "s1",
* "codeHash": "c1",
* "code": "c2",
* "storage":
* {
* "key1": "value1",
* "key2": "value2"
* }
* }
* }
*
* @author Roman Mandeleil
* @since 26.06.2014
*/
public class JSONHelper {
@SuppressWarnings("uncheked")
public static void dumpState(ObjectNode statesNode, String address, AccountState state, ContractDetails details) {
List<DataWord> storageKeys = new ArrayList<>(details.getStorage().keySet());
Collections.sort(storageKeys);
ObjectNode account = statesNode.objectNode();
ObjectNode storage = statesNode.objectNode();
for (DataWord key : storageKeys) {
storage.put("0x" + Hex.toHexString(key.getData()),
"0x" + Hex.toHexString(details.getStorage().get(key).getNoLeadZeroesData()));
}
if (state == null)
state = new AccountState(SystemProperties.getDefault().getBlockchainConfig().getCommonConstants().getInitialNonce(),
BigInteger.ZERO);
account.put("balance", state.getBalance() == null ? "0" : state.getBalance().toString());
// account.put("codeHash", details.getCodeHash() == null ? "0x" : "0x" + Hex.toHexString(details.getCodeHash()));
account.put("code", details.getCode() == null ? "0x" : "0x" + Hex.toHexString(details.getCode()));
account.put("nonce", state.getNonce() == null ? "0" : state.getNonce().toString());
account.set("storage", storage);
account.put("storage_root", state.getStateRoot() == null ? "" : Hex.toHexString(state.getStateRoot()));
statesNode.set(address, account);
}
public static void dumpBlock(ObjectNode blockNode, Block block,
long gasUsed, byte[] state, List<ByteArrayWrapper> keys,
Repository repository) {
blockNode.put("coinbase", Hex.toHexString(block.getCoinbase()));
blockNode.put("difficulty", new BigInteger(1, block.getDifficulty()).toString());
blockNode.put("extra_data", "0x");
blockNode.put("gas_used", String.valueOf(gasUsed));
blockNode.put("nonce", "0x" + Hex.toHexString(block.getNonce()));
blockNode.put("number", String.valueOf(block.getNumber()));
blockNode.put("prevhash", "0x" + Hex.toHexString(block.getParentHash()));
ObjectNode statesNode = blockNode.objectNode();
for (ByteArrayWrapper key : keys) {
byte[] keyBytes = key.getData();
AccountState accountState = repository.getAccountState(keyBytes);
ContractDetails details = repository.getContractDetails(keyBytes);
dumpState(statesNode, Hex.toHexString(keyBytes), accountState, details);
}
blockNode.set("state", statesNode);
blockNode.put("state_root", Hex.toHexString(state));
blockNode.put("timestamp", String.valueOf(block.getTimestamp()));
ArrayNode transactionsNode = blockNode.arrayNode();
blockNode.set("transactions", transactionsNode);
blockNode.put("tx_list_root", ByteUtil.toHexString(block.getTxTrieRoot()));
blockNode.put("uncles_hash", "0x" + Hex.toHexString(block.getUnclesHash()));
// JSONHelper.dumpTransactions(blockNode,
// stateRoot, codeHash, code, storage);
}
}
| 5,001
| 37.775194
| 128
|
java
|
ethereumj
|
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/json/EtherObjectMapper.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.json;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.io.SegmentedStringWriter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
/**
* An extended {@link com.fasterxml.jackson.databind.ObjectMapper ObjectMapper} class to
* customize ethereum state dumps.
*
* @author Alon Muroch
*/
public class EtherObjectMapper extends ObjectMapper {
@Override
public String writeValueAsString(Object value)
throws JsonProcessingException {
// alas, we have to pull the recycler directly here...
SegmentedStringWriter sw = new SegmentedStringWriter(_jsonFactory._getBufferRecycler());
try {
JsonGenerator ge = _jsonFactory.createGenerator(sw);
// set ethereum custom pretty printer
EtherPrettyPrinter pp = new EtherPrettyPrinter();
ge.setPrettyPrinter(pp);
_configAndWriteValue(ge, value);
} catch (JsonProcessingException e) { // to support [JACKSON-758]
throw e;
} catch (IOException e) { // shouldn't really happen, but is declared as possibility so:
throw JsonMappingException.fromUnexpectedIOE(e);
}
return sw.getAndClear();
}
/**
* An extended {@link com.fasterxml.jackson.core.util.DefaultPrettyPrinter} class to customize
* an ethereum {@link com.fasterxml.jackson.core.PrettyPrinter Pretty Printer} Generator
*
* @author Alon Muroch
*/
public class EtherPrettyPrinter extends DefaultPrettyPrinter {
public EtherPrettyPrinter() {
super();
}
@Override
public void writeObjectFieldValueSeparator(JsonGenerator jg)
throws IOException, JsonGenerationException {
/**
* Custom object separator (Default is " : ") to make it easier to compare state dumps with other
* ethereum client implementations
*/
jg.writeRaw(": ");
}
}
}
| 3,075
| 36.975309
| 109
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/VisitorStateTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.collect.Streams.concat;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Locale.ENGLISH;
import static javax.tools.StandardLocation.ANNOTATION_PROCESSOR_PATH;
import com.google.common.base.Splitter;
import com.google.common.base.StandardSystemProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.suppliers.Supplier;
import com.sun.source.tree.ClassTree;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.BasicJavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link VisitorState}. */
@RunWith(JUnit4.class)
public class VisitorStateTest {
@Test
public void symbolFromString_defaultPackage() {
assertThat(VisitorState.inferBinaryName("InDefaultPackage")).isEqualTo("InDefaultPackage");
}
@Test
public void symbolFromString_nestedTypeInDefaultPackage() {
assertThat(VisitorState.inferBinaryName("InDefaultPackage.Nested"))
.isEqualTo("InDefaultPackage$Nested");
}
@Test
public void symbolFromString_regularClass() {
assertThat(VisitorState.inferBinaryName("test.RegularClass")).isEqualTo("test.RegularClass");
assertThat(VisitorState.inferBinaryName("com.google.RegularClass"))
.isEqualTo("com.google.RegularClass");
}
@Test
public void symbolFromString_nestedTypeInRegularPackage() {
assertThat(VisitorState.inferBinaryName("test.RegularClass.Nested"))
.isEqualTo("test.RegularClass$Nested");
assertThat(VisitorState.inferBinaryName("com.google.RegularClass.Nested"))
.isEqualTo("com.google.RegularClass$Nested");
}
@Test
public void getConstantExpression() {
JavacTask task =
JavacTool.create()
.getTask(
/* out= */ null,
FileManagers.testFileManager(),
/* diagnosticListener= */ null,
/* options= */ ImmutableList.of(),
/* classes= */ ImmutableList.of(),
/* compilationUnits= */ ImmutableList.of());
Context context = ((BasicJavacTask) task).getContext();
VisitorState visitorState = VisitorState.createForUtilityPurposes(context);
assertThat(visitorState.getConstantExpression("hello ' world")).isEqualTo("\"hello ' world\"");
assertThat(visitorState.getConstantExpression("hello \n world"))
.isEqualTo("\"hello \\n world\"");
assertThat(visitorState.getConstantExpression('\'')).isEqualTo("'\\''");
}
// The following is taken from ErrorProneJavacPluginTest. There may be an easier way.
// It's possible that it's overkill for what we need here.
/** A bugpattern for testing. */
@BugPattern(summary = "", severity = ERROR)
public static class CheckThatTriesToMemoizeBasedOnTreePath extends BugChecker
implements ClassTreeMatcher {
// The following is bogus: The value is cached per compilation, not per compilation unit!
// We'll test that the plugin throws an exception about that problem.
private final Supplier<Optional<ClassTree>> firstClassTreeInCompilationUnit =
VisitorState.memoize(
s ->
s.getPath().getCompilationUnit().getTypeDecls().stream()
.filter(t -> t.getKind().asInterface().equals(ClassTree.class))
.map(ClassTree.class::cast)
.findFirst());
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return buildDescription(tree)
.setMessage(
"Found "
+ tree.getSimpleName()
+ " in file whose main class is "
+ firstClassTreeInCompilationUnit.get(state).map(ClassTree::getSimpleName))
.build();
}
}
@Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void memoizeCannotAccessTreePath() throws IOException {
File libJar = tempFolder.newFile("lib.jar");
try (var fis = new FileOutputStream(libJar);
var jos = new JarOutputStream(fis)) {
jos.putNextEntry(new JarEntry("META-INF/services/" + BugChecker.class.getName()));
jos.write(CheckThatTriesToMemoizeBasedOnTreePath.class.getName().getBytes(UTF_8));
}
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path source = fileSystem.getPath("Test.java");
Files.write(
source,
ImmutableList.of(
"import java.util.HashSet;",
"import java.util.Set;",
"class Test {",
" void f() {",
" return;",
" }",
"}"),
UTF_8);
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
fileManager.setLocation(
ANNOTATION_PROCESSOR_PATH,
concat(
Stream.of(libJar),
Splitter.on(File.pathSeparatorChar)
.splitToStream(StandardSystemProperty.JAVA_CLASS_PATH.value())
.map(File::new))
.collect(toImmutableList()));
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
JavacTask task =
JavacTool.create()
.getTask(
null,
fileManager,
diagnosticCollector,
ImmutableList.of(
"-Xplugin:ErrorProne -XepDisableAllChecks"
+ " -Xep:CheckThatTriesToMemoizeBasedOnTreePath:ERROR",
"-XDcompilePolicy=byfile"),
ImmutableList.of(),
fileManager.getJavaFileObjects(source));
assertThat(task.call()).isFalse();
Diagnostic<? extends JavaFileObject> diagnostic =
diagnosticCollector.getDiagnostics().stream()
.filter(d -> d.getKind() == Diagnostic.Kind.ERROR)
.collect(onlyElement());
assertThat(diagnostic.getMessage(ENGLISH)).contains("UnsupportedOperationException");
}
}
| 7,754
| 38.974227
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/CommandLineFlagTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.FileObjects.forResources;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.bugpatterns.EmptyIfStatement;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.scanner.BuiltInCheckerSuppliers;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.source.tree.ReturnTree;
import com.sun.tools.javac.main.Main.Result;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.tools.JavaFileObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit4.class)
public class CommandLineFlagTest {
@BugPattern(
altNames = "foo",
summary = "Disableable checker that flags all return statements as errors",
explanation = "Disableable checker that flags all return statements as errors",
severity = ERROR)
public static class DisableableChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@BugPattern(
summary = "NondisableableChecker checker that flags all return statements as errors",
explanation = "NondisableableChecker checker that flags all return statements as errors",
disableable = false,
severity = ERROR)
public static class NondisableableChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@BugPattern(
summary = "Checker that flags all return statements as warnings",
explanation = "Checker that flags all return statements as warnings",
severity = WARNING)
public static class WarningChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@BugPattern(
summary = "Checker that flags all return statements as errors",
explanation = "Checker that flags all return statements as errors",
severity = ERROR)
public static class ErrorChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
private ErrorProneTestCompiler.Builder builder;
private DiagnosticTestHelper diagnosticHelper;
private Writer output;
@Before
public void setUp() {
output = new StringWriter();
diagnosticHelper = new DiagnosticTestHelper();
builder =
new ErrorProneTestCompiler.Builder()
.report(BuiltInCheckerSuppliers.defaultChecks())
.listenToDiagnostics(diagnosticHelper.collector)
.redirectOutputTo(new PrintWriter(output, true));
}
/* Tests for new-style ("-Xep:") flags */
@Test
public void malformedFlag() {
ErrorProneTestCompiler compiler = builder.build();
List<String> badArgs =
Arrays.asList(
"-Xep:Foo:WARN:jfkdlsdf", // too many parts
"-Xep:", // no check name
"-Xep:Foo:FJDKFJSD"); // nonexistent severity level
for (String badArg : badArgs) {
InvalidCommandLineOptionException expected =
assertThrows(
InvalidCommandLineOptionException.class,
() ->
compiler.compile(new String[] {badArg}, Collections.<JavaFileObject>emptyList()));
assertThat(expected).hasMessageThat().contains("invalid flag");
}
}
// We have to use one of the built-in checkers for the following two tests because there is no
// way to specify a custom checker and have it be off by default.
@Test
public void canEnableWithDefaultSeverity() {
ErrorProneTestCompiler compiler = builder.build();
ImmutableList<JavaFileObject> sources =
forResources(EmptyIfStatement.class, "testdata/EmptyIfStatementPositiveCases.java");
Result exitCode = compiler.compile(sources);
assertThat(exitCode).isEqualTo(Result.OK);
assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
exitCode = compiler.compile(new String[] {"-Xep:EmptyIf"}, sources);
assertThat(exitCode).isEqualTo(Result.ERROR);
}
@Test
public void canEnableWithOverriddenSeverity() {
ErrorProneTestCompiler compiler = builder.build();
ImmutableList<JavaFileObject> sources =
forResources(EmptyIfStatement.class, "testdata/EmptyIfStatementPositiveCases.java");
Result exitCode = compiler.compile(sources);
assertThat(exitCode).isEqualTo(Result.OK);
assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
diagnosticHelper.clearDiagnostics();
exitCode = compiler.compile(new String[] {"-Xep:EmptyIf:WARN"}, sources);
assertThat(exitCode).isEqualTo(Result.OK);
assertThat(diagnosticHelper.getDiagnostics()).isNotEmpty();
assertThat(diagnosticHelper.getDiagnostics().toString()).contains("[EmptyIf]");
}
@Test
public void canPromoteToError() {
ErrorProneTestCompiler compiler =
builder.report(ScannerSupplier.fromBugCheckerClasses(WarningChecker.class)).build();
ImmutableList<JavaFileObject> sources =
forResources(getClass(), "CommandLineFlagTestFile.java");
Result exitCode = compiler.compile(sources);
assertThat(exitCode).isEqualTo(Result.OK);
assertThat(diagnosticHelper.getDiagnostics()).isNotEmpty();
exitCode = compiler.compile(new String[] {"-Xep:WarningChecker:ERROR"}, sources);
assertThat(exitCode).isEqualTo(Result.ERROR);
}
@Test
public void canDemoteToWarning() {
ErrorProneTestCompiler compiler =
builder.report(ScannerSupplier.fromBugCheckerClasses(ErrorChecker.class)).build();
ImmutableList<JavaFileObject> sources =
forResources(getClass(), "CommandLineFlagTestFile.java");
Result exitCode = compiler.compile(sources);
assertThat(exitCode).isEqualTo(Result.ERROR);
diagnosticHelper.clearDiagnostics();
exitCode = compiler.compile(new String[] {"-Xep:ErrorChecker:WARN"}, sources);
assertThat(exitCode).isEqualTo(Result.OK);
assertThat(diagnosticHelper.getDiagnostics()).isNotEmpty();
}
@Test
public void canDisable() {
ErrorProneTestCompiler compiler =
builder.report(ScannerSupplier.fromBugCheckerClasses(DisableableChecker.class)).build();
ImmutableList<JavaFileObject> sources =
forResources(getClass(), "CommandLineFlagTestFile.java");
Result exitCode = compiler.compile(sources);
assertThat(exitCode).isEqualTo(Result.ERROR);
diagnosticHelper.clearDiagnostics();
exitCode = compiler.compile(new String[] {"-Xep:DisableableChecker:OFF"}, sources);
assertThat(exitCode).isEqualTo(Result.OK);
assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
}
@Test
public void cantDisableNondisableableCheck() {
ErrorProneTestCompiler compiler =
builder.report(ScannerSupplier.fromBugCheckerClasses(NondisableableChecker.class)).build();
ImmutableList<JavaFileObject> sources =
forResources(getClass(), "CommandLineFlagTestFile.java");
InvalidCommandLineOptionException expected =
assertThrows(
InvalidCommandLineOptionException.class,
() -> compiler.compile(new String[] {"-Xep:NondisableableChecker:OFF"}, sources));
assertThat(expected).hasMessageThat().contains("NondisableableChecker may not be disabled");
}
@Test
public void cantOverrideNonexistentCheck() {
ErrorProneTestCompiler compiler = builder.build();
ImmutableList<JavaFileObject> sources =
forResources(getClass(), "CommandLineFlagTestFile.java");
List<String> badOptions =
Arrays.asList(
"-Xep:BogusChecker:ERROR",
"-Xep:BogusChecker:WARN",
"-Xep:BogusChecker:OFF",
"-Xep:BogusChecker");
for (String badOption : badOptions) {
InvalidCommandLineOptionException expected =
assertThrows(
InvalidCommandLineOptionException.class,
() -> compiler.compile(new String[] {badOption}, sources));
assertThat(expected).hasMessageThat().contains("BogusChecker is not a valid checker name");
}
}
@Test
public void ignoreUnknownChecksFlagAllowsOverridingUnknownCheck() {
ErrorProneTestCompiler compiler = builder.build();
ImmutableList<JavaFileObject> sources =
forResources(getClass(), "CommandLineFlagTestFile.java");
List<String> badOptions =
Arrays.asList(
"-Xep:BogusChecker:ERROR",
"-Xep:BogusChecker:WARN",
"-Xep:BogusChecker:OFF",
"-Xep:BogusChecker");
for (String badOption : badOptions) {
Result exitCode =
compiler.compile(new String[] {"-XepIgnoreUnknownCheckNames", badOption}, sources);
assertThat(exitCode).isEqualTo(Result.OK);
}
}
}
| 10,139
| 36.695167
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/ErrorProneJavacPluginTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.MoreCollectors.onlyElement;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Locale.ENGLISH;
import static org.junit.Assert.assertThrows;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.StandardSystemProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Streams;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ReturnTree;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.stream.Stream;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link ErrorProneJavacPlugin}Test */
@RunWith(JUnit4.class)
public class ErrorProneJavacPluginTest {
@Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void hello() throws IOException {
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path source = fileSystem.getPath("Test.java");
Files.write(
source,
ImmutableList.of(
"package test;",
"import java.util.HashSet;",
"import java.util.Set;",
"class Test {",
" public static void main(String[] args) {",
" Set<Short> s = new HashSet<>();",
" for (short i = 0; i < 100; i++) {",
" s.add(i);",
" s.remove(i - 1);",
" }",
" System.out.println(s.size());",
" }",
"}"),
UTF_8);
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
JavacTask task =
JavacTool.create()
.getTask(
null,
fileManager,
diagnosticCollector,
ImmutableList.of("-Xplugin:ErrorProne", "-XDcompilePolicy=byfile"),
ImmutableList.of(),
fileManager.getJavaFileObjects(source));
assertThat(task.call()).isFalse();
Diagnostic<? extends JavaFileObject> diagnostic =
diagnosticCollector.getDiagnostics().stream()
.filter(d -> d.getKind() == Diagnostic.Kind.ERROR)
.collect(onlyElement());
assertThat(diagnostic.getMessage(ENGLISH)).contains("[CollectionIncompatibleType]");
}
@Test
public void applyFixes() throws IOException {
// TODO(b/63064865): Test is broken on Windows. Disable for now.
Assume.assumeFalse(StandardSystemProperty.OS_NAME.value().startsWith("Windows"));
Path tmp = temporaryFolder.newFolder().toPath();
Path fileA = tmp.resolve("A.java");
Path fileB = tmp.resolve("B.java");
Files.write(
fileA,
ImmutableList.of(
"class A implements Runnable {", //
" public void run() {}",
"}"),
UTF_8);
Files.write(
fileB,
ImmutableList.of(
"class B implements Runnable {", //
" public void run() {}",
"}"),
UTF_8);
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
JavacTask task =
JavacTool.create()
.getTask(
null,
fileManager,
diagnosticCollector,
ImmutableList.of(
"-Xplugin:ErrorProne"
+ " -XepPatchChecks:MissingOverride -XepPatchLocation:IN_PLACE",
"-XDcompilePolicy=byfile"),
ImmutableList.of(),
fileManager.getJavaFileObjects(fileA, fileB));
assertWithMessage(Joiner.on('\n').join(diagnosticCollector.getDiagnostics()))
.that(task.call())
.isTrue();
assertThat(Files.readAllLines(fileA, UTF_8))
.containsExactly(
"class A implements Runnable {", //
" @Override public void run() {}",
"}")
.inOrder();
assertThat(Files.readAllLines(fileB, UTF_8))
.containsExactly(
"class B implements Runnable {", //
" @Override public void run() {}",
"}")
.inOrder();
}
@Test
public void applyToPatchFile() throws IOException {
// TODO(b/63064865): Test is broken on Windows. Disable for now.
Assume.assumeFalse(StandardSystemProperty.OS_NAME.value().startsWith("Windows"));
Path tmp = temporaryFolder.newFolder().toPath();
Path patchDir = temporaryFolder.newFolder().toPath();
Files.createDirectories(patchDir);
Path patchFile = patchDir.resolve("error-prone.patch");
// verify that any existing content in the patch file is deleted
Files.write(patchFile, ImmutableList.of("--- C.java", "--- D.java"), UTF_8);
Path fileA = tmp.resolve("A.java");
Path fileB = tmp.resolve("B.java");
Files.write(
fileA,
ImmutableList.of(
"class A implements Runnable {", //
" public void run() {}",
"}"),
UTF_8);
Files.write(
fileB,
ImmutableList.of(
"class B implements Runnable {", //
" public void run() {}",
"}"),
UTF_8);
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
JavacTask task =
JavacTool.create()
.getTask(
null,
fileManager,
diagnosticCollector,
ImmutableList.of(
"-Xplugin:ErrorProne"
+ " -XepPatchChecks:MissingOverride -XepPatchLocation:"
+ patchDir,
"-XDcompilePolicy=byfile"),
ImmutableList.of(),
fileManager.getJavaFileObjects(fileA, fileB));
assertWithMessage(Joiner.on('\n').join(diagnosticCollector.getDiagnostics()))
.that(task.call())
.isTrue();
assertThat(
Files.readAllLines(patchFile, UTF_8).stream()
.filter(l -> l.startsWith("--- "))
.map(l -> Paths.get(l.substring("--- ".length())).getFileName().toString())
.collect(toImmutableList()))
.containsExactly("A.java", "B.java");
}
@Test
public void noPolicyGiven() throws IOException {
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path source = fileSystem.getPath("Test.java");
Files.write(source, "class Test {}".getBytes(UTF_8));
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
StringWriter sw = new StringWriter();
JavacTask task =
JavacTool.create()
.getTask(
new PrintWriter(sw, true),
fileManager,
diagnosticCollector,
ImmutableList.of("-Xplugin:ErrorProne"),
ImmutableList.of(),
fileManager.getJavaFileObjects(source));
RuntimeException expected = assertThrows(RuntimeException.class, () -> task.call());
assertThat(expected)
.hasMessageThat()
.contains("The default compilation policy (by-todo) is not supported");
}
@Test
public void explicitBadPolicyGiven() throws IOException {
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path source = fileSystem.getPath("Test.java");
Files.write(source, "class Test {}".getBytes(UTF_8));
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
StringWriter sw = new StringWriter();
JavacTask task =
JavacTool.create()
.getTask(
new PrintWriter(sw, true),
fileManager,
diagnosticCollector,
ImmutableList.of("-XDcompilePolicy=bytodo", "-Xplugin:ErrorProne"),
ImmutableList.of(),
fileManager.getJavaFileObjects(source));
RuntimeException expected = assertThrows(RuntimeException.class, () -> task.call());
assertThat(expected).hasMessageThat().contains("-XDcompilePolicy=bytodo is not supported");
}
@Test
public void stopOnErrorPolicy() throws IOException {
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path one = fileSystem.getPath("One.java");
Path two = fileSystem.getPath("Two.java");
Files.write(
one,
ImmutableList.of(
"package test;",
"import java.util.HashSet;",
"import java.util.Set;",
"class One {",
" public static void main(String[] args) {",
" Set<Short> s = new HashSet<>();",
" for (short i = 0; i < 100; i++) {",
" s.add(i);",
" s.remove(i - 1);",
" }",
" System.out.println(s.size());",
" }",
"}"),
UTF_8);
Files.write(
two,
ImmutableList.of(
"package test;",
"class Two {",
" public static void main(String[] args) {",
" new Exception();",
" }",
"}"),
UTF_8);
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
JavacTask task =
JavacTool.create()
.getTask(
null,
fileManager,
diagnosticCollector,
ImmutableList.of(
"-Xplugin:ErrorProne",
"-XDcompilePolicy=byfile",
"-XDshould-stop.ifError=LOWER"),
ImmutableList.of(),
fileManager.getJavaFileObjects(one, two));
assertThat(task.call()).isFalse();
ImmutableList<String> diagnostics =
diagnosticCollector.getDiagnostics().stream()
.filter(d -> d.getKind() == Diagnostic.Kind.ERROR)
.map(d -> d.getMessage(ENGLISH))
.collect(toImmutableList());
assertThat(diagnostics).hasSize(2);
assertThat(diagnostics.get(0)).contains("[CollectionIncompatibleType]");
assertThat(diagnostics.get(1)).contains("[DeadException]");
}
/** A bugpattern for testing. */
@BugPattern(summary = "", severity = SeverityLevel.ERROR)
public static class TestCompilesWithFix extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
// add a no-op fix to exercise compilesWithFix
SuggestedFix fix = SuggestedFix.postfixWith(tree, "//");
return SuggestedFixes.compilesWithFix(fix, state)
? describeMatch(tree, fix)
: Description.NO_MATCH;
}
}
@Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void compilesWithFix() throws IOException {
File libJar = tempFolder.newFile("lib.jar");
try (FileOutputStream fis = new FileOutputStream(libJar);
JarOutputStream jos = new JarOutputStream(fis)) {
jos.putNextEntry(new JarEntry("META-INF/services/" + BugChecker.class.getName()));
jos.write(TestCompilesWithFix.class.getName().getBytes(UTF_8));
}
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path source = fileSystem.getPath("Test.java");
Files.write(
source,
ImmutableList.of(
"import java.util.HashSet;",
"import java.util.Set;",
"class Test {",
" void f() {",
" return;",
" }",
"}"),
UTF_8);
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
fileManager.setLocation(
StandardLocation.ANNOTATION_PROCESSOR_PATH,
Streams.concat(
Stream.of(libJar),
Streams.stream(
Splitter.on(File.pathSeparatorChar)
.split(StandardSystemProperty.JAVA_CLASS_PATH.value()))
.map(File::new))
.collect(toImmutableList()));
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
JavacTask task =
JavacTool.create()
.getTask(
null,
fileManager,
diagnosticCollector,
ImmutableList.of(
"-Xplugin:ErrorProne -XepDisableAllChecks -Xep:TestCompilesWithFix:ERROR",
"-XDcompilePolicy=byfile"),
ImmutableList.of(),
fileManager.getJavaFileObjects(source));
assertThat(task.call()).isFalse();
Diagnostic<? extends JavaFileObject> diagnostic =
diagnosticCollector.getDiagnostics().stream()
.filter(d -> d.getKind() == Diagnostic.Kind.ERROR)
.collect(onlyElement());
assertThat(diagnostic.getMessage(ENGLISH)).contains("[TestCompilesWithFix]");
}
}
| 15,211
| 38.105398
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/MatcherChecker.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ExpressionStatementTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.Tree;
/**
* A {@link BugChecker} that flags {@link ExpressionStatementTree}s that satisfy both of the
* following:
*
* <ul>
* <li>The text of the tree is the same as the given {@code expressionStatement}, and
* <li>The given {@code matcher} matches the tree
* </ul>
*
* <p>Useful for testing {@link Matcher}s.
*/
public abstract class MatcherChecker extends BugChecker implements ExpressionStatementTreeMatcher {
private final String expressionStatement;
private final Matcher<Tree> matcher;
public MatcherChecker(String expressionStatement, Matcher<Tree> matcher) {
this.expressionStatement = expressionStatement;
this.matcher = matcher;
}
@Override
public Description matchExpressionStatement(ExpressionStatementTree tree, VisitorState state) {
return (expressionStatement.equals(state.getSourceForNode(tree))
&& matcher.matches(tree, state))
? describeMatch(tree)
: Description.NO_MATCH;
}
}
| 1,921
| 34.592593
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/ErrorProneCompilerIntegrationTest.java
|
/*
* Copyright 2011 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.DiagnosticTestHelper.diagnosticMessage;
import static com.google.errorprone.FileObjects.forResources;
import static com.google.errorprone.FileObjects.forSourceLines;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.constValue;
import static java.util.Locale.ENGLISH;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assume.assumeTrue;
import com.google.common.base.Ascii;
import com.google.common.base.StandardSystemProperty;
import com.google.common.collect.Iterables;
import com.google.errorprone.bugpatterns.BadShiftAmount;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ExpressionStatementTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.bugpatterns.NonAtomicVolatileUpdate;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.scanner.BuiltInCheckerSuppliers;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.main.Main.Result;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
import javax.lang.model.element.Name;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Integration tests for the Error Prone compiler.
*
* @author alexeagle@google.com (Alex Eagle)
*/
@RunWith(JUnit4.class)
public class ErrorProneCompilerIntegrationTest {
private DiagnosticTestHelper diagnosticHelper;
private StringWriter outputStream;
private ErrorProneTestCompiler.Builder compilerBuilder;
ErrorProneTestCompiler compiler;
@Rule public final TemporaryFolder tmpFolder = new TemporaryFolder();
@Before
public void setUp() {
diagnosticHelper = new DiagnosticTestHelper();
outputStream = new StringWriter();
compilerBuilder =
new ErrorProneTestCompiler.Builder()
.report(BuiltInCheckerSuppliers.defaultChecks())
.redirectOutputTo(new PrintWriter(outputStream, true))
.listenToDiagnostics(diagnosticHelper.collector);
compiler = compilerBuilder.build();
}
@Test
public void fileWithError() {
Result exitCode =
compiler.compile(
forResources(BadShiftAmount.class, "testdata/BadShiftAmountPositiveCases.java"));
assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[BadShiftAmount]")));
assertWithMessage("Error should be found. " + diagnosticHelper.describe())
.that(matcher.matches(diagnosticHelper.getDiagnostics()))
.isTrue();
}
@Test
public void fileWithWarning() {
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(NonAtomicVolatileUpdate.class));
compiler = compilerBuilder.build();
Result exitCode =
compiler.compile(
forResources(
NonAtomicVolatileUpdate.class,
"testdata/NonAtomicVolatileUpdatePositiveCases.java"));
assertThat(outputStream.toString(), exitCode, is(Result.OK));
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[NonAtomicVolatileUpdate]")));
assertWithMessage("Warning should be found. " + diagnosticHelper.describe())
.that(matcher.matches(diagnosticHelper.getDiagnostics()))
.isTrue();
}
@Test
public void fileWithMultipleTopLevelClasses() {
Result exitCode =
compiler.compile(
forResources(getClass(), "testdata/MultipleTopLevelClassesWithNoErrors.java"));
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
@Test
public void fileWithMultipleTopLevelClassesExtends() {
Result exitCode =
compiler.compile(
forResources(
getClass(),
"testdata/MultipleTopLevelClassesWithNoErrors.java",
"testdata/ExtendedMultipleTopLevelClassesWithNoErrors.java"));
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
/**
* Regression test for a bug in which multiple top-level classes may cause NullPointerExceptions
* in the matchers.
*/
@Test
public void fileWithMultipleTopLevelClassesExtendsWithError() {
Result exitCode =
compiler.compile(
forResources(
getClass(),
"testdata/MultipleTopLevelClassesWithErrors.java",
"testdata/ExtendedMultipleTopLevelClassesWithErrors.java"));
assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[SelfAssignment]")));
assertWithMessage("Warning should be found. " + diagnosticHelper.describe())
.that(matcher.matches(diagnosticHelper.getDiagnostics()))
.isTrue();
assertThat(diagnosticHelper.getDiagnostics()).hasSize(4);
}
@BugPattern(name = "", explanation = "", summary = "", severity = ERROR)
public static class Throwing extends BugChecker implements ExpressionStatementTreeMatcher {
@Override
public Description matchExpressionStatement(ExpressionStatementTree tree, VisitorState state) {
throw new IllegalStateException("test123");
}
}
@Test
public void unhandledExceptionsAreReportedWithoutBugParadeLink() {
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(Throwing.class));
compiler = compilerBuilder.build();
Result exitCode =
compiler.compile(
forResources(
getClass(),
"testdata/MultipleTopLevelClassesWithErrors.java",
"testdata/ExtendedMultipleTopLevelClassesWithErrors.java"));
assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(
diagnosticMessage(
CoreMatchers.<String>allOf(
containsString("IllegalStateException: test123"),
containsString("unhandled exception was thrown by the Error Prone"))));
assertWithMessage("Error should be reported. " + diagnosticHelper.describe())
.that(matcher.matches(diagnosticHelper.getDiagnostics()))
.isTrue();
}
/** Regression test for Issue 188, error-prone doesn't work with annotation processors. */
@Test
public void annotationProcessingWorks() {
Result exitCode =
compiler.compile(
forResources(getClass(), "testdata/UsesAnnotationProcessor.java"),
Arrays.asList(new NullAnnotationProcessor()));
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
/** Test that if javac does dataflow on a class twice error-prone only analyses it once. */
@Test
public void reportReadyForAnalysisOnce() {
Result exitCode =
compiler.compile(
forResources(
getClass(),
"testdata/FlowConstants.java",
"testdata/FlowSub.java",
// This order is important: the superclass needs to occur after the subclass in
// the sources so it goes through flow twice (once so it can be used when the
// subclass is desugared, once normally).
"testdata/FlowSuper.java"));
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
@BugPattern(explanation = "", severity = ERROR, summary = "")
public static class ConstructorMatcher extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@Test
public void ignoreGeneratedConstructors() {
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(ConstructorMatcher.class));
compiler = compilerBuilder.build();
Result exitCode =
compiler.compile(
Arrays.asList(
forSourceLines(
"Test.java", //
"public class Test {}")));
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
not(hasItem(diagnosticMessage(containsString("[ConstructorMatcher]"))));
assertWithMessage("Warning should be found. " + diagnosticHelper.describe())
.that(matcher.matches(diagnosticHelper.getDiagnostics()))
.isTrue();
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
@BugPattern(explanation = "", severity = ERROR, summary = "")
static class SuperCallMatcher extends BugChecker implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Tree select = tree.getMethodSelect();
Name name;
if (select instanceof MemberSelectTree) {
name = ((MemberSelectTree) select).getIdentifier();
} else if (select instanceof IdentifierTree) {
name = ((IdentifierTree) select).getName();
} else {
return NO_MATCH;
}
return name.contentEquals("super") ? describeMatch(tree) : Description.NO_MATCH;
}
}
// TODO(cushon) - how can we distinguish between synthetic super() calls and real ones?
@Ignore
@Test
public void ignoreGeneratedSuperInvocations() {
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(SuperCallMatcher.class));
compiler = compilerBuilder.build();
Result exitCode =
compiler.compile(
Arrays.asList(
forSourceLines(
"Test.java", //
"public class Test {",
" public Test() {}",
"}")));
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
not(hasItem(diagnosticMessage(containsString("[SuperCallMatcher]"))));
assertWithMessage("Warning should be found. " + diagnosticHelper.describe())
.that(matcher.matches(diagnosticHelper.getDiagnostics()))
.isTrue();
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
@Test
public void invalidFlagCausesCmdErrResult() {
String[] args = {"-Xep:"};
assertThrows(
InvalidCommandLineOptionException.class,
() ->
compiler.compile(
args,
Arrays.asList(
forSourceLines(
"Test.java", //
"public class Test {",
" public Test() {}",
"}"))));
}
@Test
public void flagEnablesCheck() {
String[] testFile = {
"package test;", //
"public class Test {",
" public Test() {",
" if (true);",
" }",
"}"
};
List<JavaFileObject> fileObjects = Arrays.asList(forSourceLines("Test.java", testFile));
Result exitCode = compiler.compile(fileObjects);
outputStream.flush();
assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
assertThat(outputStream.toString(), exitCode, is(Result.OK));
String[] args = {"-Xep:EmptyIf"};
exitCode = compiler.compile(args, fileObjects);
outputStream.flush();
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[EmptyIf]")));
assertWithMessage("Error should be found. " + diagnosticHelper.describe())
.that(matcher.matches(diagnosticHelper.getDiagnostics()))
.isTrue();
assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
}
@Test
public void severityIsResetOnNextCompilation() {
String[] testFile = {
"package test;", //
"public class Test {",
" void doIt (int i) {",
" i = i;",
" }",
"}"
};
List<JavaFileObject> fileObjects = Arrays.asList(forSourceLines("Test.java", testFile));
String[] args = {"-Xep:SelfAssignment:WARN"};
Result exitCode = compiler.compile(args, fileObjects);
outputStream.flush();
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[SelfAssignment]")));
assertThat(outputStream.toString(), exitCode, is(Result.OK));
assertWithMessage("Warning should be found. " + diagnosticHelper.describe())
.that(matcher.matches(diagnosticHelper.getDiagnostics()))
.isTrue();
// Should reset to default severity (ERROR)
exitCode = compiler.compile(fileObjects);
outputStream.flush();
assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
}
@Test
public void maturityIsResetOnNextCompilation() {
String[] testFile = {
"package test;", //
"public class Test {",
" public Test() {",
" if (true);",
" }",
"}"
};
List<JavaFileObject> fileObjects = Arrays.asList(forSourceLines("Test.java", testFile));
String[] args = {"-Xep:EmptyIf"};
Result exitCode = compiler.compile(args, fileObjects);
outputStream.flush();
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[EmptyIf]")));
assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
assertWithMessage("Error should be found. " + diagnosticHelper.describe())
.that(matcher.matches(diagnosticHelper.getDiagnostics()))
.isTrue();
diagnosticHelper.clearDiagnostics();
exitCode = compiler.compile(fileObjects);
outputStream.flush();
assertThat(outputStream.toString(), exitCode, is(Result.OK));
assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
}
@Test
public void suppressGeneratedWarning() {
String[] generatedFile = {
"import java.util.List;",
"@javax.annotation.Generated(\"Foo\")",
"class Generated {",
" public Generated() {}",
"}"
};
List<JavaFileObject> fileObjects =
Arrays.asList(forSourceLines("Generated.java", generatedFile));
{
String[] args = {"-Xep:RemoveUnusedImports:WARN"};
Result exitCode = compiler.compile(args, fileObjects);
outputStream.flush();
assertThat(diagnosticHelper.getDiagnostics()).hasSize(1);
assertThat(diagnosticHelper.getDiagnostics().get(0).getMessage(ENGLISH))
.contains("[RemoveUnusedImports]");
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
diagnosticHelper.clearDiagnostics();
{
String[] args = {"-Xep:RemoveUnusedImports:WARN", "-XepDisableWarningsInGeneratedCode"};
Result exitCode = compiler.compile(args, fileObjects);
outputStream.flush();
assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
}
@Test
public void suppressGeneratedWarningJava9() {
assumeTrue(StandardSystemProperty.JAVA_VERSION.value().startsWith("9"));
String[] generatedFile = {
"@javax.annotation.processing.Generated(\"Foo\")",
"class Generated {",
" public Generated() {",
" if (true);",
" }",
"}"
};
List<JavaFileObject> fileObjects =
Arrays.asList(forSourceLines("Generated.java", generatedFile));
{
String[] args = {"-Xep:EmptyIf:WARN"};
Result exitCode = compiler.compile(args, fileObjects);
outputStream.flush();
assertThat(diagnosticHelper.getDiagnostics()).hasSize(1);
assertThat(diagnosticHelper.getDiagnostics().get(0).getMessage(ENGLISH))
.contains("[EmptyIf]");
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
diagnosticHelper.clearDiagnostics();
{
String[] args = {"-Xep:EmptyIf:WARN", "-XepDisableWarningsInGeneratedCode"};
Result exitCode = compiler.compile(args, fileObjects);
outputStream.flush();
assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
}
@Test
public void cannotSuppressGeneratedError() {
String[] generatedFile = {
"@javax.annotation.Generated(\"Foo\")",
"class Generated {",
" public Generated() {",
" if (true);",
" }",
"}"
};
String[] args = {"-Xep:EmptyIf:ERROR", "-XepDisableWarningsInGeneratedCode"};
Result exitCode =
compiler.compile(args, Arrays.asList(forSourceLines("Generated.java", generatedFile)));
outputStream.flush();
assertThat(diagnosticHelper.getDiagnostics()).hasSize(1);
assertThat(diagnosticHelper.getDiagnostics().get(0).getMessage(ENGLISH)).contains("[EmptyIf]");
assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
}
@BugPattern(explanation = "", summary = "", severity = ERROR)
public static class CrashOnReturn extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
throw new NullPointerException();
}
}
@Test
public void crashSourcePosition() {
compiler =
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(CrashOnReturn.class)).build();
Result exitCode =
compiler.compile(
Arrays.asList(
forSourceLines(
"test/Test.java",
"package Test;",
"class Test {",
" void f() {",
" return;",
" }",
"}")));
assertWithMessage(outputStream.toString()).that(exitCode).isEqualTo(Result.ERROR);
assertThat(diagnosticHelper.getDiagnostics()).hasSize(1);
Diagnostic<? extends JavaFileObject> diag =
Iterables.getOnlyElement(diagnosticHelper.getDiagnostics());
assertThat(diag.getLineNumber()).isEqualTo(4);
assertThat(diag.getColumnNumber()).isEqualTo(5);
assertThat(diag.getSource().toUri().toString()).endsWith("test/Test.java");
assertThat(diag.getMessage(ENGLISH))
.contains("An unhandled exception was thrown by the Error Prone static analysis plugin");
}
@Test
public void compilePolicy_bytodo() {
InvalidCommandLineOptionException e =
assertThrows(
InvalidCommandLineOptionException.class,
() ->
compiler.compile(
new String[] {"-XDcompilePolicy=bytodo"},
Collections.<JavaFileObject>emptyList()));
assertThat(e).hasMessageThat().contains("-XDcompilePolicy=bytodo is not supported");
}
@Test
public void compilePolicy_byfile() {
Result exitCode =
compiler.compile(
new String[] {"-XDcompilePolicy=byfile"},
Arrays.asList(
forSourceLines(
"Test.java", //
"package test;",
"class Test {}")));
outputStream.flush();
assertWithMessage(outputStream.toString()).that(exitCode).isEqualTo(Result.OK);
}
@Test
public void compilePolicy_simple() {
Result exitCode =
compiler.compile(
new String[] {"-XDcompilePolicy=simple"},
Arrays.asList(
forSourceLines(
"Test.java", //
"package test;",
"class Test {}")));
outputStream.flush();
assertWithMessage(outputStream.toString()).that(exitCode).isEqualTo(Result.OK);
}
@BugPattern(
summary = "Using 'return' is considered harmful",
explanation = "Please refactor your code into continuation passing style.",
severity = ERROR)
public static class CPSChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@Test
public void compilationWithError() {
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(CPSChecker.class));
compiler = compilerBuilder.build();
compiler.compile(
new String[] {
"-XDshouldStopPolicyIfError=LOWER",
},
Arrays.asList(
forSourceLines(
"Test.java",
"package test;",
"public class Test {",
" Object f() { return new NoSuch(); }",
"}")));
outputStream.flush();
String output = diagnosticHelper.getDiagnostics().toString();
assertThat(output).contains("error: cannot find symbol");
assertThat(output).doesNotContain("Using 'return' is considered harmful");
}
/**
* Trivial bug checker for testing command line flags. Forbids methods from returning the string
* provided by "-XepOpt:Forbidden=<VALUE>" flag.
*/
@BugPattern(summary = "Please don't return this const value", severity = ERROR)
public static class ForbiddenString extends BugChecker implements ReturnTreeMatcher {
private final String forbiddenString;
@Inject
ForbiddenString(ErrorProneFlags flags) {
forbiddenString = flags.get("Forbidden").orElse("default");
}
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
if (Ascii.equalsIgnoreCase(
this.forbiddenString, constValue(tree.getExpression()).toString())) {
return describeMatch(tree);
} else {
return NO_MATCH;
}
}
}
@Test
public void checkerWithFlags() {
String[] args = {
"-XepOpt:Forbidden=xylophone",
};
List<JavaFileObject> sources =
Arrays.asList(
forSourceLines(
"Test.java",
"package test;",
"public class Test {",
" Object f() { return \"XYLOPHONE\"; }",
"}"));
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(ForbiddenString.class));
compiler = compilerBuilder.build();
compiler.compile(args, sources);
outputStream.flush();
String output = diagnosticHelper.getDiagnostics().toString();
assertThat(output).contains("Please don't return this const value");
}
@Test
public void flagsAreResetOnNextCompilation() {
String[] args = {"-XepOpt:Forbidden=bananas"};
List<JavaFileObject> sources =
Arrays.asList(
forSourceLines(
"Test.java",
"package test;",
"public class Test {",
" Object f() { return \"BANANAS\"; }",
"}"));
// First compile forbids "bananas", should fail.
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(ForbiddenString.class));
compiler = compilerBuilder.build();
Result exitCode = compiler.compile(args, sources);
outputStream.flush();
assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
// Flags should reset, compile should succeed.
exitCode = compiler.compile(sources);
outputStream.flush();
assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
}
| 24,936
| 36.499248
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/ErrorProneTestCompiler.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.tools.javac.main.Main.Result;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import javax.annotation.processing.Processor;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
/** Wraps {@link com.google.errorprone.ErrorProneJavaCompiler}. */
public class ErrorProneTestCompiler {
/** {@link ErrorProneTestCompiler.Builder} */
public static class Builder {
private DiagnosticListener<? super JavaFileObject> listener;
private ScannerSupplier scannerSupplier;
private PrintWriter printWriter;
public ErrorProneTestCompiler build() {
return new ErrorProneTestCompiler(listener, scannerSupplier, printWriter);
}
@CanIgnoreReturnValue
public Builder listenToDiagnostics(DiagnosticListener<? super JavaFileObject> listener) {
this.listener = listener;
return this;
}
@CanIgnoreReturnValue
public Builder report(ScannerSupplier scannerSupplier) {
this.scannerSupplier = scannerSupplier;
return this;
}
@CanIgnoreReturnValue
public Builder redirectOutputTo(PrintWriter printWriter) {
this.printWriter = printWriter;
return this;
}
}
private final DiagnosticListener<? super JavaFileObject> listener;
private final ScannerSupplier scannerSupplier;
private final PrintWriter printWriter;
public ErrorProneTestCompiler(
DiagnosticListener<? super JavaFileObject> listener,
ScannerSupplier scannerSupplier,
PrintWriter printWriter) {
this.listener = listener;
this.scannerSupplier = scannerSupplier;
this.printWriter = printWriter;
}
public Result compile(List<JavaFileObject> sources) {
return compile(sources, null);
}
public Result compile(String[] args, List<JavaFileObject> sources) {
return compile(args, sources, null);
}
public Result compile(List<JavaFileObject> sources, List<? extends Processor> processors) {
return compile(new String[] {}, sources, processors);
}
public Result compile(
String[] args, List<JavaFileObject> sources, List<? extends Processor> processors) {
if (processors == null || processors.isEmpty()) {
List<String> processedArgs =
CompilationTestHelper.disableImplicitProcessing(Arrays.asList(args));
args = processedArgs.toArray(new String[0]);
}
CompilationTask task =
new BaseErrorProneJavaCompiler(scannerSupplier)
.getTask(
printWriter,
FileManagers.testFileManager(),
listener,
Arrays.asList(args),
null,
sources);
if (processors != null) {
task.setProcessors(processors);
}
return task.call() ? Result.OK : Result.ERROR;
}
}
| 3,585
| 31.6
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/SubContextTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import com.sun.tools.javac.util.Context;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link SubContext}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@RunWith(JUnit4.class)
public class SubContextTest {
private static final Context.Key<String> KEY1 = new Context.Key<>();
private static final Context.Key<String> KEY2 = new Context.Key<>();
enum Enum1 {
VALUE1,
VALUE2;
}
enum Enum2 {
VALUE;
}
@Test
public void overlay() {
Context base = new Context();
base.put(KEY1, "key1");
base.put(Enum1.class, Enum1.VALUE1);
Context overlay = new SubContext(base);
overlay.put(KEY2, "key2");
overlay.put(Enum2.class, Enum2.VALUE);
assertThat(overlay.get(KEY1)).isEqualTo("key1");
assertThat(overlay.get(Enum1.class)).isEqualTo(Enum1.VALUE1);
assertThat(overlay.get(KEY2)).isEqualTo("key2");
assertThat(overlay.get(Enum2.class)).isEqualTo(Enum2.VALUE);
assertThat(base.get(KEY2)).isNull();
assertThat(base.get(Enum2.class)).isNull();
}
@Test
public void override() {
Context base = new Context();
base.put(KEY1, "key1");
base.put(Enum1.class, Enum1.VALUE1);
Context overlay = new SubContext(base);
overlay.put(KEY1, "key2");
overlay.put(Enum1.class, Enum1.VALUE2);
assertThat(overlay.get(KEY1)).isEqualTo("key2");
assertThat(overlay.get(Enum1.class)).isEqualTo(Enum1.VALUE2);
assertThat(base.get(KEY1)).isEqualTo("key1");
assertThat(base.get(Enum1.class)).isEqualTo(Enum1.VALUE1);
}
}
| 2,275
| 28.179487
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/NullAnnotationProcessor.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
/**
* A minimal annotation processor that claims all annotations and does nothing else.
*
* @author Eddie Aftandilian (eaftan@google.com)
*/
@SupportedAnnotationTypes("*")
public class NullAnnotationProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
return true;
}
}
| 1,391
| 31.372093
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/ErrorProneJavaCompilerTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.DiagnosticTestHelper.diagnosticMessage;
import static com.google.errorprone.FileObjects.forResources;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Locale.ENGLISH;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.errorprone.bugpatterns.ArrayEquals;
import com.google.errorprone.bugpatterns.BadShiftAmount;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.ChainingConstructorIgnoresParameter;
import com.google.errorprone.bugpatterns.Finally;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.scanner.ScannerSupplier;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.file.JavacFileManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.lang.model.SourceVersion;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import org.hamcrest.Matcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cushon@google.com (Liam Miller-Cushon)
*/
@RunWith(JUnit4.class)
public class ErrorProneJavaCompilerTest {
@Rule public final TemporaryFolder tempDir = new TemporaryFolder();
@Test
public void isSupportedOption() {
ErrorProneJavaCompiler compiler = new ErrorProneJavaCompiler();
// javac options should be passed through
assertThat(compiler.isSupportedOption("-source")).isEqualTo(1);
// error-prone options should be handled
assertThat(compiler.isSupportedOption("-Xep:")).isEqualTo(0);
assertThat(compiler.isSupportedOption("-XepIgnoreUnknownCheckNames")).isEqualTo(0);
assertThat(compiler.isSupportedOption("-XepDisableWarningsInGeneratedCode")).isEqualTo(0);
// old-style error-prone options are not supported
assertThat(compiler.isSupportedOption("-Xepdisable:")).isEqualTo(-1);
}
interface JavaFileObjectDiagnosticListener extends DiagnosticListener<JavaFileObject> {}
@Test
public void getStandardJavaFileManager() {
JavaCompiler mockCompiler = mock(JavaCompiler.class);
ErrorProneJavaCompiler compiler = new ErrorProneJavaCompiler(mockCompiler);
JavaFileObjectDiagnosticListener listener = mock(JavaFileObjectDiagnosticListener.class);
Locale locale = Locale.CANADA;
compiler.getStandardFileManager(listener, locale, null);
verify(mockCompiler).getStandardFileManager(listener, locale, null);
}
@Test
public void run() {
JavaCompiler mockCompiler = mock(JavaCompiler.class);
ErrorProneJavaCompiler compiler = new ErrorProneJavaCompiler(mockCompiler);
InputStream in = mock(InputStream.class);
OutputStream out = mock(OutputStream.class);
OutputStream err = mock(OutputStream.class);
String[] arguments = {"-source", "8", "-target", "8"};
compiler.run(in, out, err, arguments);
verify(mockCompiler).run(in, out, err, arguments);
}
@Test
public void sourceVersion() {
ErrorProneJavaCompiler compiler = new ErrorProneJavaCompiler();
assertThat(compiler.getSourceVersions()).contains(SourceVersion.latest());
assertThat(compiler.getSourceVersions()).doesNotContain(SourceVersion.RELEASE_5);
}
@Test
public void fileWithErrorIntegrationTest() {
CompilationResult result =
doCompile(
Arrays.asList("bugpatterns/testdata/SelfAssignmentPositiveCases1.java"),
Collections.<String>emptyList(),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isFalse();
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[SelfAssignment]")));
assertThat(matcher.matches(result.diagnosticHelper.getDiagnostics())).isTrue();
}
@Test
public void withDisabledCheck() {
CompilationResult result =
doCompile(
Arrays.asList("bugpatterns/testdata/SelfAssignmentPositiveCases1.java"),
Collections.<String>emptyList(),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isFalse();
result =
doCompile(
Arrays.asList("bugpatterns/testdata/SelfAssignmentPositiveCases1.java"),
Arrays.asList("-Xep:SelfAssignment:OFF"),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isTrue();
}
@Test
public void withCheckPromotedToError() {
CompilationResult result =
doCompile(
Arrays.asList("bugpatterns/testdata/WaitNotInLoopPositiveCases.java"),
Collections.<String>emptyList(),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isTrue();
assertThat(result.diagnosticHelper.getDiagnostics().size()).isGreaterThan(0);
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[WaitNotInLoop]")));
assertThat(matcher.matches(result.diagnosticHelper.getDiagnostics())).isTrue();
result =
doCompile(
Arrays.asList("bugpatterns/testdata/WaitNotInLoopPositiveCases.java"),
Arrays.asList("-Xep:WaitNotInLoop:ERROR"),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isFalse();
assertThat(result.diagnosticHelper.getDiagnostics().size()).isGreaterThan(0);
assertThat(matcher.matches(result.diagnosticHelper.getDiagnostics())).isTrue();
}
@Test
public void withCheckDemotedToWarning() {
CompilationResult result =
doCompile(
Arrays.asList("bugpatterns/testdata/SelfAssignmentPositiveCases1.java"),
Collections.<String>emptyList(),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isFalse();
assertThat(result.diagnosticHelper.getDiagnostics().size()).isGreaterThan(0);
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[SelfAssignment]")));
assertThat(matcher.matches(result.diagnosticHelper.getDiagnostics())).isTrue();
result =
doCompile(
Arrays.asList("bugpatterns/testdata/SelfAssignmentPositiveCases1.java"),
Arrays.asList("-Xep:SelfAssignment:WARN"),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isTrue();
assertThat(result.diagnosticHelper.getDiagnostics().size()).isGreaterThan(0);
assertThat(matcher.matches(result.diagnosticHelper.getDiagnostics())).isTrue();
}
@Test
public void withNonDefaultCheckOn() {
CompilationResult result =
doCompile(
Arrays.asList("bugpatterns/testdata/EmptyIfStatementPositiveCases.java"),
Collections.<String>emptyList(),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isTrue();
assertThat(result.diagnosticHelper.getDiagnostics()).isEmpty();
result =
doCompile(
Arrays.asList("bugpatterns/testdata/EmptyIfStatementPositiveCases.java"),
Arrays.asList("-Xep:EmptyIf"),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isFalse();
assertThat(result.diagnosticHelper.getDiagnostics().size()).isGreaterThan(0);
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[EmptyIf]")));
assertThat(matcher.matches(result.diagnosticHelper.getDiagnostics())).isTrue();
}
@Test
public void badFlagThrowsException() {
try {
doCompile(
Arrays.asList("bugpatterns/testdata/EmptyIfStatementPositiveCases.java"),
Arrays.asList("-Xep:foo:bar:baz"),
Collections.<Class<? extends BugChecker>>emptyList());
fail();
} catch (RuntimeException expected) {
assertThat(expected).hasMessageThat().contains("invalid flag");
}
}
@BugPattern(
name = "ArrayEquals",
summary = "Reference equality used to compare arrays",
explanation = "",
severity = ERROR,
disableable = false)
public static class UnsuppressibleArrayEquals extends ArrayEquals {}
@Test
public void cantDisableNonDisableableCheck() {
try {
doCompile(
Arrays.asList("bugpatterns/testdata/ArrayEqualsPositiveCases.java"),
Arrays.asList("-Xep:ArrayEquals:OFF"),
ImmutableList.<Class<? extends BugChecker>>of(UnsuppressibleArrayEquals.class));
fail();
} catch (RuntimeException expected) {
assertThat(expected).hasMessageThat().contains("ArrayEquals may not be disabled");
}
}
@Test
public void withCustomCheckPositive() {
CompilationResult result =
doCompile(
Arrays.asList("bugpatterns/testdata/BadShiftAmountPositiveCases.java"),
Collections.<String>emptyList(),
Arrays.<Class<? extends BugChecker>>asList(BadShiftAmount.class));
assertThat(result.succeeded).isFalse();
assertThat(result.diagnosticHelper.getDiagnostics().size()).isGreaterThan(0);
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[BadShiftAmount]")));
assertThat(matcher.matches(result.diagnosticHelper.getDiagnostics())).isTrue();
}
@Test
public void withCustomCheckNegative() {
CompilationResult result =
doCompile(
Arrays.asList("bugpatterns/testdata/SelfAssignmentPositiveCases1.java"),
Collections.<String>emptyList(),
Arrays.<Class<? extends BugChecker>>asList(Finally.class));
assertThat(result.succeeded).isTrue();
assertThat(result.diagnosticHelper.getDiagnostics()).isEmpty();
}
@Test
public void severityResetsAfterOverride() throws IOException {
DiagnosticTestHelper diagnosticHelper = new DiagnosticTestHelper();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, UTF_8), true);
JavacFileManager fileManager = FileManagers.testFileManager();
JavaCompiler errorProneJavaCompiler = new ErrorProneJavaCompiler();
List<String> args =
Lists.newArrayList(
"-d",
tempDir.getRoot().getAbsolutePath(),
"-proc:none",
"-Xep:ChainingConstructorIgnoresParameter:WARN");
ImmutableList<JavaFileObject> sources =
forResources(
ChainingConstructorIgnoresParameter.class,
"testdata/ChainingConstructorIgnoresParameterPositiveCases.java");
JavaCompiler.CompilationTask task =
errorProneJavaCompiler.getTask(
printWriter, fileManager, diagnosticHelper.collector, args, null, sources);
boolean succeeded = task.call();
assertThat(succeeded).isTrue();
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[ChainingConstructorIgnoresParameter]")));
assertThat(matcher.matches(diagnosticHelper.getDiagnostics())).isTrue();
// reset state between compilations
diagnosticHelper.clearDiagnostics();
sources =
forResources(
ChainingConstructorIgnoresParameter.class,
"testdata/ChainingConstructorIgnoresParameterPositiveCases.java");
args.remove("-Xep:ChainingConstructorIgnoresParameter:WARN");
task =
errorProneJavaCompiler.getTask(
printWriter, fileManager, diagnosticHelper.collector, args, null, sources);
succeeded = task.call();
assertThat(succeeded).isFalse();
assertThat(matcher.matches(diagnosticHelper.getDiagnostics())).isTrue();
}
@Test
public void maturityResetsAfterOverride() throws Exception {
DiagnosticTestHelper diagnosticHelper = new DiagnosticTestHelper();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, UTF_8), true);
JavaCompiler errorProneJavaCompiler = new ErrorProneJavaCompiler();
List<String> args =
Lists.newArrayList("-d", tempDir.getRoot().getAbsolutePath(), "-proc:none", "-Xep:EmptyIf");
ImmutableList<JavaFileObject> sources =
forResources(BadShiftAmount.class, "testdata/EmptyIfStatementPositiveCases.java");
JavaCompiler.CompilationTask task =
errorProneJavaCompiler.getTask(
printWriter, null, diagnosticHelper.collector, args, null, sources);
boolean succeeded = task.call();
assertThat(succeeded).isFalse();
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticMessage(containsString("[EmptyIf]")));
assertThat(matcher.matches(diagnosticHelper.getDiagnostics())).isTrue();
diagnosticHelper.clearDiagnostics();
args.remove("-Xep:EmptyIf");
task =
errorProneJavaCompiler.getTask(
printWriter, null, diagnosticHelper.collector, args, null, sources);
succeeded = task.call();
assertThat(succeeded).isTrue();
assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
}
@BugPattern(
summary =
"You appear to be using methods; prefer to implement all program logic inside the main"
+ " function by flipping bits in a single long[].",
explanation = "",
severity = ERROR,
disableable = false)
public static class DeleteMethod extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
MethodTree ctor = (MethodTree) Iterables.getOnlyElement(tree.getMembers());
Preconditions.checkArgument(ASTHelpers.isGeneratedConstructor(ctor));
return describeMatch(tree, SuggestedFix.delete(ctor));
}
}
@Test
public void fixGeneratedConstructor() {
CompilationResult result =
doCompile(
Arrays.asList("testdata/DeleteGeneratedConstructorTestCase.java"),
Collections.<String>emptyList(),
ImmutableList.<Class<? extends BugChecker>>of(DeleteMethod.class));
assertThat(result.succeeded).isFalse();
assertThat(result.output).isEmpty();
assertThat(result.diagnosticHelper.getDiagnostics()).hasSize(1);
assertThat(
Iterables.getOnlyElement(result.diagnosticHelper.getDiagnostics()).getMessage(ENGLISH))
.contains("IllegalArgumentException: Cannot edit synthetic AST nodes");
}
@Test
public void withExcludedPaths() {
CompilationResult result =
doCompile(
Arrays.asList("bugpatterns/testdata/SelfAssignmentPositiveCases1.java"),
Collections.<String>emptyList(),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isFalse();
result =
doCompile(
Arrays.asList("bugpatterns/testdata/SelfAssignmentPositiveCases1.java"),
Arrays.asList("-XepExcludedPaths:.*/bugpatterns/.*"),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isTrue();
// ensure regexp must match the full path
result =
doCompile(
Arrays.asList("bugpatterns/testdata/SelfAssignmentPositiveCases1.java"),
Arrays.asList("-XepExcludedPaths:bugpatterns"),
Collections.<Class<? extends BugChecker>>emptyList());
assertThat(result.succeeded).isFalse();
}
private static class CompilationResult {
public final boolean succeeded;
public final String output;
public final DiagnosticTestHelper diagnosticHelper;
public CompilationResult(
boolean succeeded, String output, DiagnosticTestHelper diagnosticHelper) {
this.succeeded = succeeded;
this.output = output;
this.diagnosticHelper = diagnosticHelper;
}
}
private CompilationResult doCompile(
List<String> fileNames,
List<String> extraArgs,
List<Class<? extends BugChecker>> customCheckers) {
DiagnosticTestHelper diagnosticHelper = new DiagnosticTestHelper();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, UTF_8), true);
JavacFileManager fileManager = FileManagers.testFileManager();
List<String> args = Lists.newArrayList("-d", tempDir.getRoot().getAbsolutePath(), "-proc:none");
args.addAll(extraArgs);
JavaCompiler errorProneJavaCompiler =
(customCheckers.isEmpty())
? new ErrorProneJavaCompiler()
: new ErrorProneJavaCompiler(ScannerSupplier.fromBugCheckerClasses(customCheckers));
JavaCompiler.CompilationTask task =
errorProneJavaCompiler.getTask(
printWriter,
fileManager,
diagnosticHelper.collector,
args,
null,
forResources(getClass(), fileNames.toArray(new String[0])));
return new CompilationResult(
task.call(), new String(outputStream.toByteArray(), UTF_8), diagnosticHelper);
}
}
| 18,828
| 40.201313
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/DiagnosticKindTest.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.FileObjects.forSourceLines;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.source.tree.ReturnTree;
import com.sun.tools.javac.main.Main.Result;
import java.util.Arrays;
import javax.tools.Diagnostic;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests that {@link BugPattern.SeverityLevel}s map to appropriate {@link
* javax.tools.Diagnostic.Kind}s and are displayed in some reasonable way on the command line.
*/
@RunWith(JUnit4.class)
public class DiagnosticKindTest {
/**
* The mock code we are going to analyze in our tests. Only needs a return for the matcher to
* match on.
*/
private static final String[] TEST_CODE = {
"class Test {", " void doIt() {", " return;", " }", "}"
};
private DiagnosticTestHelper diagnosticHelper;
private ErrorProneTestCompiler.Builder compilerBuilder;
@Before
public void setUp() {
diagnosticHelper = new DiagnosticTestHelper();
compilerBuilder =
new ErrorProneTestCompiler.Builder().listenToDiagnostics(diagnosticHelper.collector);
}
@BugPattern(
summary = "This is an error!",
explanation = "Don't do this!",
severity = SeverityLevel.ERROR)
public static class ErrorChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@Test
public void error() {
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(ErrorChecker.class));
ErrorProneTestCompiler compiler = compilerBuilder.build();
Result result = compiler.compile(Arrays.asList(forSourceLines("Test.java", TEST_CODE)));
assertThat(diagnosticHelper.getDiagnostics()).hasSize(1);
assertThat(diagnosticHelper.getDiagnostics().get(0).getKind()).isEqualTo(Diagnostic.Kind.ERROR);
assertThat(diagnosticHelper.getDiagnostics().get(0).toString()).contains("error:");
assertThat(result).isEqualTo(Result.ERROR);
}
@BugPattern(
summary = "This is a warning!",
explanation = "Please don't do this!",
severity = SeverityLevel.WARNING)
public static class WarningChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@Test
public void warning() {
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(WarningChecker.class));
ErrorProneTestCompiler compiler = compilerBuilder.build();
Result result = compiler.compile(Arrays.asList(forSourceLines("Test.java", TEST_CODE)));
assertThat(diagnosticHelper.getDiagnostics()).hasSize(1);
assertThat(diagnosticHelper.getDiagnostics().get(0).getKind())
.isEqualTo(Diagnostic.Kind.WARNING);
assertThat(diagnosticHelper.getDiagnostics().get(0).toString()).contains("warning:");
assertThat(result).isEqualTo(Result.OK);
}
@BugPattern(
summary = "This is a suggestion!",
explanation = "Don't do this. Or do it. I'm a suggestion, not a cop.",
severity = SeverityLevel.SUGGESTION)
public static class SuggestionChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@Test
public void suggestion() {
compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(SuggestionChecker.class));
ErrorProneTestCompiler compiler = compilerBuilder.build();
Result result = compiler.compile(Arrays.asList(forSourceLines("Test.java", TEST_CODE)));
assertThat(diagnosticHelper.getDiagnostics()).hasSize(1);
assertThat(diagnosticHelper.getDiagnostics().get(0).getKind()).isEqualTo(Diagnostic.Kind.NOTE);
assertThat(diagnosticHelper.getDiagnostics().get(0).toString()).contains("Note:");
assertThat(result).isEqualTo(Result.OK);
}
}
| 4,952
| 36.80916
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/MethodHasParametersTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.ALL;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.isPrimitiveType;
import static com.google.errorprone.matchers.Matchers.variableType;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.MethodTree;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit4.class)
public class MethodHasParametersTest extends CompilerBasedAbstractTest {
final List<ScannerTest> tests = new ArrayList<>();
@Before
public void setUp() {
tests.clear();
writeFile(
"SampleAnnotation1.java", "package com.google;", "public @interface SampleAnnotation1 {}");
writeFile(
"SampleAnnotation2.java", "package com.google;", "public @interface SampleAnnotation2 {}");
}
@After
public void tearDown() {
for (ScannerTest test : tests) {
test.assertDone();
}
}
@Test
public void shouldMatchSingleParameter() {
writeFile(
"A.java", "package com.google;", "public class A {", " public void A(int i) {}", "}");
assertCompiles(
methodMatches(
/* shouldMatch= */ true,
new MethodHasParameters(AT_LEAST_ONE, variableType(isPrimitiveType()))));
assertCompiles(
methodMatches(
/* shouldMatch= */ true,
new MethodHasParameters(ALL, variableType(isPrimitiveType()))));
}
@Test
public void shouldNotMatchNoParameters() {
writeFile("A.java", "package com.google;", "public class A {", " public void A() {}", "}");
assertCompiles(
methodMatches(
/* shouldMatch= */ false,
new MethodHasParameters(AT_LEAST_ONE, variableType(isPrimitiveType()))));
assertCompiles(
methodMatches(
/* shouldMatch= */ true,
new MethodHasParameters(ALL, variableType(isPrimitiveType()))));
}
@Test
public void shouldNotMatchNonmatchingParameter() {
writeFile(
"A.java", "package com.google;", "public class A {", " public void A(Object obj) {}", "}");
assertCompiles(
methodMatches(
/* shouldMatch= */ false,
new MethodHasParameters(AT_LEAST_ONE, variableType(isPrimitiveType()))));
assertCompiles(
methodMatches(
/* shouldMatch= */ false,
new MethodHasParameters(ALL, variableType(isPrimitiveType()))));
}
@Test
public void multipleParameters() {
writeFile(
"A.java",
"package com.google;",
"public class A {",
" public void A(int i, Object obj) {}",
"}");
assertCompiles(
methodMatches(
/* shouldMatch= */ true,
new MethodHasParameters(AT_LEAST_ONE, variableType(isPrimitiveType()))));
assertCompiles(
methodMatches(
/* shouldMatch= */ false,
new MethodHasParameters(ALL, variableType(isPrimitiveType()))));
}
private abstract class ScannerTest extends Scanner {
public abstract void assertDone();
}
private Scanner methodMatches(boolean shouldMatch, MethodHasParameters toMatch) {
ScannerTest test =
new ScannerTest() {
private boolean matched = false;
@Override
public Void visitMethod(MethodTree node, VisitorState visitorState) {
visitorState = visitorState.withPath(getCurrentPath());
if (!isConstructor(node) && toMatch.matches(node, visitorState)) {
matched = true;
}
return super.visitMethod(node, visitorState);
}
private boolean isConstructor(MethodTree node) {
return node.getName().contentEquals("<init>");
}
@Override
public void assertDone() {
assertThat(shouldMatch).isEqualTo(matched);
}
};
tests.add(test);
return test;
}
}
| 4,892
| 31.62
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/ConstructorOfClassTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.ALL;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.methodHasVisibility;
import com.google.errorprone.VisitorState;
import com.google.errorprone.matchers.MethodVisibility.Visibility;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.ClassTree;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author eaftan@google.com (Eddie Aftandilian)
* <p>TODO(eaftan): Add test for correct matching of nodes.
*/
@RunWith(JUnit4.class)
public class ConstructorOfClassTest extends CompilerBasedAbstractTest {
final List<ScannerTest> tests = new ArrayList<>();
@Before
public void setUp() {
tests.clear();
}
@After
public void tearDown() {
for (ScannerTest test : tests) {
test.assertDone();
}
}
@Test
public void shouldMatchSingleConstructor() {
writeFile("A.java", "package com.google;", "public class A {", " private A() {}", "}");
assertCompiles(
classMatches(
/* shouldMatch= */ true,
new ConstructorOfClass(AT_LEAST_ONE, methodHasVisibility(Visibility.PRIVATE))));
assertCompiles(
classMatches(
/* shouldMatch= */ true,
new ConstructorOfClass(ALL, methodHasVisibility(Visibility.PRIVATE))));
}
@Test
public void shouldNotMatchNoConstructors() {
writeFile("A.java", "package com.google;", "public class A {", "}");
assertCompiles(
classMatches(
/* shouldMatch= */ false,
new ConstructorOfClass(AT_LEAST_ONE, methodHasVisibility(Visibility.PRIVATE))));
assertCompiles(
classMatches(
/* shouldMatch= */ false,
new ConstructorOfClass(ALL, methodHasVisibility(Visibility.PRIVATE))));
}
@Test
public void shouldNotMatchNonmatchingConstructor() {
writeFile("A.java", "package com.google;", "public class A {", " public A() {}", "}");
assertCompiles(
classMatches(
/* shouldMatch= */ false,
new ConstructorOfClass(AT_LEAST_ONE, methodHasVisibility(Visibility.PRIVATE))));
assertCompiles(
classMatches(
/* shouldMatch= */ false,
new ConstructorOfClass(ALL, methodHasVisibility(Visibility.PRIVATE))));
}
@Test
public void multipleConstructors() {
writeFile(
"A.java",
"package com.google;",
"public class A {",
" private A() {}",
" public A(int i) {}",
"}");
assertCompiles(
classMatches(
/* shouldMatch= */ true,
new ConstructorOfClass(AT_LEAST_ONE, methodHasVisibility(Visibility.PRIVATE))));
assertCompiles(
classMatches(
/* shouldMatch= */ false,
new ConstructorOfClass(ALL, methodHasVisibility(Visibility.PRIVATE))));
}
private abstract class ScannerTest extends Scanner {
public abstract void assertDone();
}
private Scanner classMatches(boolean shouldMatch, ConstructorOfClass toMatch) {
ScannerTest test =
new ScannerTest() {
private boolean matched = false;
@Override
public Void visitClass(ClassTree node, VisitorState visitorState) {
visitorState = visitorState.withPath(getCurrentPath());
if (toMatch.matches(node, visitorState)) {
matched = true;
}
return super.visitClass(node, visitorState);
}
@Override
public void assertDone() {
assertThat(shouldMatch).isEqualTo(matched);
}
};
tests.add(test);
return test;
}
}
| 4,569
| 31.183099
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/AnnotationDoesNotHaveArgumentTest.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.AnnotationTree;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link AnnotationDoesNotHaveArgument}.
*
* @author mwacker@google.com (Mike Wacker)
*/
@RunWith(JUnit4.class)
public class AnnotationDoesNotHaveArgumentTest extends CompilerBasedAbstractTest {
@Before
public void createAnnotation() {
writeFile(
"Annotation.java", "public @interface Annotation {", " String value() default \"\";", "}");
}
@Test
public void matchesWhenArgumentIsNotPresent() {
writeFile("Class.java", "@Annotation", "public class Class {}");
assertCompiles(annotationMatches(true));
}
@Test
public void matchesWhenArgumentIsNotPresent_otherArgumentPresent() {
writeFile(
"Annotation2.java",
"public @interface Annotation2 {",
" String value() default \"\";",
" String otherValue() default \"\";",
"}");
writeFile("Class.java", "@Annotation2(otherValue = \"literal\")", "public class Class {}");
assertCompiles(annotationMatches(true));
}
@Test
public void doesNotMatchWhenArgumentIsPresent_implicit() {
writeFile("Class.java", "@Annotation(\"literal\")", "public class Class {}");
assertCompiles(annotationMatches(false));
}
@Test
public void doesNotMatchWhenArgumentIsPresent_explicit() {
writeFile("Class.java", "@Annotation(value = \"literal\")", "public class Class {}");
assertCompiles(annotationMatches(false));
}
private Scanner annotationMatches(boolean shouldMatch) {
AnnotationDoesNotHaveArgument toMatch = new AnnotationDoesNotHaveArgument("value");
return new Scanner() {
@Override
public Void visitAnnotation(AnnotationTree node, VisitorState visitorState) {
assertWithMessage(node.toString())
.that(!shouldMatch ^ toMatch.matches(node, visitorState))
.isTrue();
return super.visitAnnotation(node, visitorState);
}
};
}
}
| 2,833
| 31.953488
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/HasIdentifierTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.matchers.Matchers.hasIdentifier;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
@RunWith(JUnit4.class)
public class HasIdentifierTest extends CompilerBasedAbstractTest {
final List<ScannerTest> tests = new ArrayList<>();
@After
public void tearDown() {
for (ScannerTest test : tests) {
test.assertDone();
}
}
@Test
public void shouldMatchThis() {
writeFile("A.java", "public class A {", " A() { this(0); }", " A(int foo) {}", "}");
assertCompiles(
methodHasIdentifierMatching(
/* shouldMatch= */ true,
hasIdentifier(
new Matcher<IdentifierTree>() {
@Override
public boolean matches(IdentifierTree tree, VisitorState state) {
return tree.getName().contentEquals("this");
}
})));
}
@Test
public void shouldMatchLocalVar() {
writeFile(
"A.java",
"public class A {",
" A() {",
" int foo = 1;",
" int bar = foo;",
" }",
"}");
assertCompiles(
methodHasIdentifierMatching(
/* shouldMatch= */ true,
hasIdentifier(
new Matcher<IdentifierTree>() {
@Override
public boolean matches(IdentifierTree tree, VisitorState state) {
return tree.getName().contentEquals("foo");
}
})));
}
@Test
public void shouldMatchParam() {
writeFile("A.java", "public class A {", " A(int foo) {", " int bar = foo;", " }", "}");
assertCompiles(
methodHasIdentifierMatching(
/* shouldMatch= */ true,
hasIdentifier(
new Matcher<IdentifierTree>() {
@Override
public boolean matches(IdentifierTree tree, VisitorState state) {
return tree.getName().contentEquals("foo");
}
})));
}
@Test
public void shouldNotMatchDeclaration() {
writeFile("A.java", "public class A {", " A() {", " int foo = 1;", " }", "}");
assertCompiles(
methodHasIdentifierMatching(
/* shouldMatch= */ false,
hasIdentifier(
new Matcher<IdentifierTree>() {
@Override
public boolean matches(IdentifierTree tree, VisitorState state) {
return tree.getName().contentEquals("foo");
}
})));
}
/**
* Tests that the matcher doesn't throw an exception when applied to a tree that doesn't contain
* any identifiers or classes. Here, we apply the matcher to every LiteralTree.
*/
@Test
public void doesNotThrowWhenMatcherIsAppliedDirectlyToLiteral() {
writeFile("A.java", "public class A {", " A() {", " int foo = 1;", " }", "}");
assertCompiles(
literalHasIdentifierMatching(
/* shouldMatch= */ false,
hasIdentifier(
new Matcher<IdentifierTree>() {
@Override
public boolean matches(IdentifierTree tree, VisitorState state) {
return tree.getName().contentEquals("somethingElse");
}
})));
}
private abstract static class ScannerTest extends Scanner {
abstract void assertDone();
}
private Scanner methodHasIdentifierMatching(boolean shouldMatch, Matcher<Tree> toMatch) {
ScannerTest test =
new ScannerTest() {
private boolean matched = false;
@Override
public Void visitMethod(MethodTree node, VisitorState visitorState) {
visitorState = visitorState.withPath(getCurrentPath());
if (toMatch.matches(node, visitorState)) {
matched = true;
}
return super.visitMethod(node, visitorState);
}
@Override
public void assertDone() {
assertThat(shouldMatch).isEqualTo(matched);
}
};
tests.add(test);
return test;
}
private Scanner literalHasIdentifierMatching(boolean shouldMatch, Matcher<Tree> toMatch) {
ScannerTest test =
new ScannerTest() {
private boolean matched = false;
@Override
public Void visitLiteral(LiteralTree node, VisitorState visitorState) {
visitorState = visitorState.withPath(getCurrentPath());
if (toMatch.matches(node, visitorState)) {
matched = true;
}
return super.visitLiteral(node, visitorState);
}
@Override
void assertDone() {
assertThat(shouldMatch).isEqualTo(matched);
}
};
tests.add(test);
return test;
}
}
| 5,953
| 31.183784
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/MethodReturnsNonNullToStringTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author deminguyen@google.com (Demi Nguyen)
*/
@RunWith(JUnit4.class)
public class MethodReturnsNonNullToStringTest extends CompilerBasedAbstractTest {
@Test
public void shouldMatch() {
writeFile(
"A.java",
"public class A {",
" public String testToString() {",
" Object obj = new Object();",
" return obj.toString();",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ true, Matchers.methodReturnsNonNull()));
}
@Test
public void shouldMatchDescendants() {
writeFile(
"A.java",
"public class A {",
" public String testThisToString() {",
" return toString();",
" }",
" public String testInstanceToString() {",
" Object o = new Object();",
" return o.toString();",
" }",
" public String testStringToString() {",
" String str = \"a string\";",
" return str.toString();",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ true, Matchers.methodReturnsNonNull()));
}
@Test
public void shouldMatchBareOverride() {
writeFile(
"A.java",
"public class A {",
" public String toString() {",
" return \"a string\";",
" }",
" public String testToString() {",
" return toString();",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ true, Matchers.methodReturnsNonNull()));
}
@Test
public void shouldNotMatchWhenMethodNameDiffers() {
writeFile(
"A.java",
"public class A {",
" public String ToString() {",
" return \"match should be case sensitive\";",
" }",
" public String testMethodWithDifferentCase() {",
" return ToString();",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ false, Matchers.methodReturnsNonNull()));
}
@Test
public void shouldNotMatchWhenMethodSignatureDiffers() {
writeFile(
"A.java",
" public String toString(int i) {",
" return \"toString method with param\";",
" }",
" public String testMethodWithParam() {",
" return toString(3);",
" }",
"}");
}
private Scanner methodInvocationMatches(boolean shouldMatch, Matcher<ExpressionTree> toMatch) {
return new Scanner() {
@Override
public Void visitMethodInvocation(MethodInvocationTree node, VisitorState visitorState) {
ExpressionTree methodSelect = node.getMethodSelect();
if (!methodSelect.toString().equals("super")) {
assertWithMessage(methodSelect.toString())
.that(!shouldMatch ^ toMatch.matches(node, visitorState))
.isTrue();
}
return super.visitMethodInvocation(node, visitorState);
}
};
}
}
| 3,977
| 29.6
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/NextStatementTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.StatementTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test for {@link NextStatement}. */
@RunWith(JUnit4.class)
public final class NextStatementTest {
/** A bugchecker to test the ability to notice the 'next statement' */
@BugPattern(
name = "CompoundAssignmentBeforeReturn",
summary = "This is a compound assignment before another statement in the same block",
severity = ERROR)
public static class CompoundBeforeAnythingChecker extends BugChecker
implements BugChecker.CompoundAssignmentTreeMatcher {
@Override
public Description matchCompoundAssignment(CompoundAssignmentTree cat, VisitorState state) {
StatementTree exprStat =
ASTHelpers.findEnclosingNode(state.getPath(), ExpressionStatementTree.class);
assertThat(exprStat).isNotNull();
if (Matchers.nextStatement(Matchers.<StatementTree>anything()).matches(exprStat, state)) {
return describeMatch(cat);
}
return Description.NO_MATCH;
}
}
// If a statement is inside an if statement with no block braces, the NextStatement should return
// false, since there's no other statement inside the block.
@Test
public void singleStatementBlock() {
CompilationTestHelper.newInstance(CompoundBeforeAnythingChecker.class, getClass())
.addSourceLines(
"B.java",
"public class B {",
" public boolean getHash() {",
" int a = 0;",
" if (true) a += 1;",
" else a += 2;",
" return false;",
" }",
"}")
.doTest();
}
@Test
public void nextStatementInBlock() {
CompilationTestHelper.newInstance(CompoundBeforeAnythingChecker.class, getClass())
.addSourceLines(
"A.java",
"public class A {",
" public boolean getHash() {",
" int a = 0;",
" if (a == 0) {",
" // BUG: Diagnostic contains: This is a compound assignment",
" a += 1;",
" return true;",
" }",
" return false;",
" }",
"}")
.doTest();
}
}
| 3,376
| 34.547368
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/AnnotationMatcherTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.ALL;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Matchers.isType;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreePath;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author eaftan@google.com (Eddie Aftandilian)
* <p>TODO(eaftan): Add test for correct matching of nodes.
*/
@RunWith(JUnit4.class)
public class AnnotationMatcherTest extends CompilerBasedAbstractTest {
final List<ScannerTest> tests = new ArrayList<>();
@Before
public void setUp() {
tests.clear();
writeFile(
"SampleAnnotation1.java", "package com.google;", "public @interface SampleAnnotation1 {}");
writeFile(
"SampleAnnotation2.java", "package com.google;", "public @interface SampleAnnotation2 {}");
writeFile(
"SampleNestedAnnotation.java",
"package com.google;",
"public class SampleNestedAnnotation {",
" public @interface Annotation {}",
"}");
}
@After
public void tearDown() {
for (ScannerTest test : tests) {
test.assertDone();
}
}
@Test
public void shouldNotMatchNoAnnotations() {
writeFile("A.java", "package com.google;", "public class A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ false,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ false,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchSingleAnnotationOnClass() {
writeFile("A.java", "package com.google;", "@SampleAnnotation1", "public class A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchSingleFullyQualifiedAnnotationOnClass() {
writeFile(
"A.java", "package com.google.foo;", "@com.google.SampleAnnotation1", "public class A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchSingleNestedAnnotationOnClass() {
writeFile(
"A.java", "package com.google;", "@SampleNestedAnnotation.Annotation", "public class A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(
AT_LEAST_ONE, isType("com.google.SampleNestedAnnotation.Annotation"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(
ALL, isType("com.google.SampleNestedAnnotation.Annotation"))));
}
@Test
public void shouldNotMatchNonmatchingSingleAnnotationOnClass() {
writeFile("A.java", "package com.google;", "@SampleAnnotation1", "public class A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ false,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.WrongAnnotation"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ false,
new AnnotationMatcher<Tree>(ALL, isType("com.google.WrongAnnotation"))));
}
@Test
public void shouldNotMatchNonmatchingSingleFullyQualifiedAnnotationOnClass() {
writeFile(
"A.java", "package com.google.foo;", "@com.google.SampleAnnotation1", "public class A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ false,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.WrongAnnotation"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ false,
new AnnotationMatcher<Tree>(ALL, isType("com.google.WrongAnnotation"))));
}
@Test
public void shouldNotMatchNonmatchingNestedAnnotationOnClass() {
writeFile(
"A.java",
"package com.google;",
"@com.google.SampleNestedAnnotation.Annotation",
"public class A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ false,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.WrongAnnotation"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ false,
new AnnotationMatcher<Tree>(ALL, isType("com.google.WrongAnnotation"))));
}
@Test
public void shouldMatchAllAnnotationsOnClass() {
writeFile(
"A.java",
"package com.google;",
"@SampleAnnotation1 @SampleAnnotation2",
"public class A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(
AT_LEAST_ONE,
Matchers.<AnnotationTree>anyOf(
isType("com.google.SampleAnnotation1"),
isType("com.google.SampleAnnotation2")))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(
ALL,
Matchers.<AnnotationTree>anyOf(
isType("com.google.SampleAnnotation1"),
isType("com.google.SampleAnnotation2")))));
}
@Test
public void matchOneAnnotationsOnClass() {
writeFile(
"A.java",
"package com.google;",
"@SampleAnnotation1 @SampleAnnotation2",
"public class A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ false,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchAnnotationOnInterface() {
writeFile("A.java", "package com.google;", "@SampleAnnotation1", "public interface A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchAnnotationOnEnum() {
writeFile("A.java", "package com.google;", "@SampleAnnotation1", "public enum A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchAnnotationOnField() {
writeFile(
"A.java",
"package com.google;",
"public class A {",
" @SampleAnnotation1",
" public int i;",
"}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchAnnotationOnMethod() {
writeFile(
"A.java",
"package com.google;",
"public class A {",
" @SampleAnnotation1",
" public void foo() {}",
"}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchAnnotationOnParameter() {
writeFile(
"A.java",
"package com.google;",
"public class A {",
" public void foo(@SampleAnnotation1 int i) {}",
"}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchAnnotationOnConstructor() {
writeFile(
"A.java",
"package com.google;",
"public class A {",
" @SampleAnnotation1",
" public A() {}",
"}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchAnnotationOnLocalVariable() {
writeFile(
"A.java",
"package com.google;",
"public class A {",
" public void foo() {",
" @SampleAnnotation1",
" int i = 0;",
" }",
"}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchAnnotationOnAnnotation() {
writeFile("A.java", "package com.google;", "@SampleAnnotation1", "public @interface A {}");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
@Test
public void shouldMatchAnnotationOnPackage() {
writeFile("package-info.java", "@SampleAnnotation1", "package com.google;");
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(AT_LEAST_ONE, isType("com.google.SampleAnnotation1"))));
assertCompiles(
nodeWithAnnotationMatches(
/* shouldMatch= */ true,
new AnnotationMatcher<Tree>(ALL, isType("com.google.SampleAnnotation1"))));
}
private abstract class ScannerTest extends Scanner {
public abstract void assertDone();
}
private Scanner nodeWithAnnotationMatches(boolean shouldMatch, AnnotationMatcher<Tree> toMatch) {
ScannerTest test =
new ScannerTest() {
private boolean matched = false;
@Override
public Void visitAnnotation(AnnotationTree node, VisitorState visitorState) {
TreePath currPath = getCurrentPath().getParentPath();
Tree parent = currPath.getLeaf();
if (parent.getKind() == Kind.MODIFIERS) {
currPath = currPath.getParentPath();
parent = currPath.getLeaf();
}
visitorState = visitorState.withPath(currPath);
if (toMatch.matches(parent, visitorState)) {
matched = true;
}
visitorState = visitorState.withPath(getCurrentPath());
return super.visitAnnotation(node, visitorState);
}
@Override
public void assertDone() {
assertThat(shouldMatch).isEqualTo(matched);
}
};
tests.add(test);
return test;
}
}
| 13,880
| 34.230964
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/MethodReturnsTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.google.errorprone.suppliers.Suppliers;
import com.sun.source.tree.MethodTree;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
@RunWith(JUnit4.class)
public class MethodReturnsTest extends CompilerBasedAbstractTest {
final List<ScannerTest> tests = new ArrayList<>();
@After
public void tearDown() {
for (ScannerTest test : tests) {
test.assertDone();
}
}
@Test
public void returnsString() {
writeFile("A.java", "public class A {", " static String foo() { return null; }", "}");
assertCompiles(fooReturnsType(/* shouldMatch= */ true, "java.lang.String"));
}
@Test
public void notReturnsString() {
writeFile("A.java", "public class A {", " static int foo() { return 0; }", "}");
assertCompiles(fooReturnsType(/* shouldMatch= */ false, "java.lang.String"));
}
@Test
public void returnsInt() {
writeFile("A.java", "public class A {", " static int foo() { return 0; }", "}");
assertCompiles(fooReturnsType(/* shouldMatch= */ true, "int"));
}
private abstract static class ScannerTest extends Scanner {
abstract void assertDone();
}
private Scanner fooReturnsType(boolean shouldMatch, String typeString) {
ScannerTest test =
new ScannerTest() {
private boolean matched = false;
@Override
public Void visitMethod(MethodTree node, VisitorState visitorState) {
if (methodReturns(Suppliers.typeFromString(typeString)).matches(node, visitorState)) {
matched = true;
}
return super.visitMethod(node, visitorState);
}
@Override
void assertDone() {
assertThat(shouldMatch).isEqualTo(matched);
}
};
tests.add(test);
return test;
}
}
| 2,811
| 29.901099
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/MethodReturnsNonNullStringTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author deminguyen@google.com (Demi Nguyen)
*/
@RunWith(JUnit4.class)
public class MethodReturnsNonNullStringTest extends CompilerBasedAbstractTest {
@Test
public void shouldMatchInstanceMethod() {
writeFile(
"A.java",
"public class A {",
" public void testInstanceMethods() {",
" String testStr = \"test string\";",
" testStr.charAt(0);",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ true, Matchers.methodReturnsNonNull()));
}
@Test
public void shouldMatchStaticMethod() {
writeFile(
"A.java",
"public class A {",
" public void testStaticMethods() {",
" String.valueOf(123);",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ true, Matchers.methodReturnsNonNull()));
}
@Test
public void shouldNotMatchConstructorInvocation() {
writeFile(
"A.java",
"public class A {",
" public String getString() {",
" String str = new String(\"hi\");",
" return str;",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ false, Matchers.methodReturnsNonNull()));
}
@Test
public void shouldNotMatchOtherClasses() {
writeFile(
"A.java",
"public class A {",
" public String getString() {",
" return \"test string\";",
" }",
" public void testMethodInvocation() {",
" getString();",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ false, Matchers.methodReturnsNonNull()));
}
private Scanner methodInvocationMatches(boolean shouldMatch, Matcher<ExpressionTree> toMatch) {
return new Scanner() {
@Override
public Void visitMethodInvocation(MethodInvocationTree node, VisitorState visitorState) {
ExpressionTree methodSelect = node.getMethodSelect();
if (!methodSelect.toString().equals("super")) {
assertWithMessage(methodSelect.toString())
.that(!shouldMatch ^ toMatch.matches(node, visitorState))
.isTrue();
}
return super.visitMethodInvocation(node, visitorState);
}
};
}
}
| 3,295
| 29.803738
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/MethodMatchersTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.constructor;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.google.errorprone.matchers.method.MethodMatchers.MethodNameMatcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link MethodMatchers}Test */
@RunWith(JUnit4.class)
public class MethodMatchersTest {
/** A bugchecker to test constructor matching. */
@BugPattern(summary = "Deletes constructors", severity = ERROR)
public static class ConstructorDeleter extends BugChecker
implements BugChecker.MethodInvocationTreeMatcher,
BugChecker.NewClassTreeMatcher,
BugChecker.MemberReferenceTreeMatcher {
static final Matcher<ExpressionTree> CONSTRUCTOR =
constructor().forClass("test.Foo").withParameters("java.lang.String");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return match(tree, state);
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
return match(tree, state);
}
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
return match(tree, state);
}
private Description match(ExpressionTree tree, VisitorState state) {
if (CONSTRUCTOR.matches(tree, state)) {
return describeMatch(tree, SuggestedFix.delete(tree));
}
return NO_MATCH;
}
}
@Test
public void constructorMatcherTest_this() {
CompilationTestHelper.newInstance(ConstructorDeleter.class, getClass())
.addSourceLines(
"test/Foo.java",
"package test;",
"public class Foo { ",
" public Foo(String s) {}",
" public Foo() {",
" // BUG: Diagnostic contains:",
" this(\"\");",
" }",
"}")
.doTest();
}
@Test
public void constructorMatcherTest_super() {
CompilationTestHelper.newInstance(ConstructorDeleter.class, getClass())
.addSourceLines(
"test/Foo.java",
"package test;",
"public class Foo { ",
" public Foo(String s) {}",
"}")
.addSourceLines(
"test/Bar.java", //
"package test;",
"public class Bar extends Foo {",
" public Bar() {",
" // BUG: Diagnostic contains:",
" super(\"\");",
" }",
"}")
.doTest();
}
@Test
public void constructorMatcherTest_reference() {
CompilationTestHelper.newInstance(ConstructorDeleter.class, getClass())
.addSourceLines(
"test/Foo.java",
"package test;",
"import java.util.function.Function;",
"public class Foo { ",
" public Foo(String s) {}",
" // BUG: Diagnostic contains:",
" private static final Function<String, Foo> make = Foo::new;",
"}")
.doTest();
}
@Test
public void constructorMatcherTest_regular() {
CompilationTestHelper.newInstance(ConstructorDeleter.class, getClass())
.addSourceLines(
"test/Foo.java",
"package test;",
"public class Foo { ",
" public Foo(String s) {}",
"}")
.addSourceLines(
"test/Test.java", //
"package test;",
"public class Test {",
" public void f() {",
" // BUG: Diagnostic contains:",
" new Foo(\"\");",
" }",
"}")
.doTest();
}
/** This is javadoc. */
@BugPattern(name = "CrashyParameterMatcherTestChecker", summary = "", severity = ERROR)
public static class CrashyerMatcherTestChecker extends BugChecker
implements MethodInvocationTreeMatcher {
public static final Matcher<ExpressionTree> MATCHER =
instanceMethod().anyClass().withAnyName().withParameters("NOSUCH");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return MATCHER.matches(tree, state) ? describeMatch(tree) : NO_MATCH;
}
}
@Test
public void varargsParameterMatcher() {
CompilationTestHelper.newInstance(CrashyerMatcherTestChecker.class, getClass())
.addSourceLines("Lib.java", "abstract class Lib { ", " void f(int x) {}", "}")
.addSourceLines(
"test/Test.java", //
"class Test {",
" void f(Lib l) {",
" l.f(42);",
" }",
"}")
.doTest();
}
/** Test BugChecker for namedAnyOf(...) */
@BugPattern(name = "FlagMethodNames", summary = "", severity = ERROR)
public static class FlagMethodNamesChecker extends BugChecker
implements MethodInvocationTreeMatcher, MemberReferenceTreeMatcher {
private static final MethodNameMatcher INSTANCE_MATCHER =
instanceMethod().anyClass().namedAnyOf("foo", "bar");
private static final MethodNameMatcher STATIC_MATCHER =
staticMethod().anyClass().namedAnyOf("fizz", "buzz");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return match(tree, state);
}
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
return match(tree, state);
}
private Description match(ExpressionTree tree, VisitorState state) {
if (INSTANCE_MATCHER.matches(tree, state)) {
return buildDescription(tree).setMessage("instance varargs").build();
}
if (STATIC_MATCHER.matches(tree, state)) {
return buildDescription(tree).setMessage("static varargs").build();
}
return NO_MATCH;
}
}
@Test
public void namedAnyOfTest() {
CompilationTestHelper.newInstance(FlagMethodNamesChecker.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" void foo() {}",
" void bar() {}",
" static void fizz() {}",
" static void buzz() {}",
" void anotherMethod() {}",
" static void yetAnother() {}",
" void f() {",
" // BUG: Diagnostic contains: instance varargs",
" this.foo();",
" // BUG: Diagnostic contains: instance varargs",
" this.bar();",
" // BUG: Diagnostic contains: static varargs",
" Test.fizz();",
" // BUG: Diagnostic contains: static varargs",
" Test.buzz();",
" // BUG: Diagnostic contains: static varargs",
" Runnable r = Test::fizz;",
" // These ones are ok",
" this.anotherMethod();",
" Test.yetAnother();",
" }",
"}")
.doTest();
}
}
| 8,494
| 34.248963
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/NonNullLiteralTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberSelectTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author deminguyen@google.com (Demi Nguyen)
*/
@RunWith(JUnit4.class)
public class NonNullLiteralTest extends CompilerBasedAbstractTest {
@Test
public void shouldMatchPrimitiveLiterals() {
writeFile(
"A.java",
"public class A {",
" public int getInt() {",
" return 2;",
" }",
" public long getLong() {",
" return 3L;",
" }",
" public float getFloat() {",
" return 4.0f;",
" }",
" public double getDouble() {",
" return 5.0d;",
" }",
" public boolean getBool() {",
" return true;",
" }",
" public char getChar() {",
" return 'c';",
" }",
" public String getString() {",
" return \"test string\";",
" }",
"}");
assertCompiles(nonNullLiteralMatches(/* shouldMatch= */ true, Matchers.nonNullLiteral()));
}
@Test
public void shouldMatchClassLiteral() {
writeFile(
"A.java",
"import java.lang.reflect.Type;",
"public class A {",
" public void testClassLiteral() {",
" Type klass = String.class;",
" }",
"}");
assertCompiles(nonNullLiteralMatches(/* shouldMatch= */ true, Matchers.nonNullLiteral()));
}
@Test
public void shouldNotMatchClassDeclaration() {
writeFile(
"A.java",
"public class A {",
" protected class B {",
" private class C {",
" }",
" }",
"}");
assertCompiles(nonNullLiteralMatches(/* shouldMatch= */ false, Matchers.nonNullLiteral()));
}
@Test
public void shouldNotMatchMemberAccess() {
writeFile(
"A.java",
"package com.google;",
"public class A {",
" public String stringVar;",
" public void testMemberAccess() {",
" this.stringVar = new String();",
" }",
"}");
writeFile(
"B.java",
"import com.google.A;",
"public class B {",
" public void testInstanceMemberAccess() {",
" A foo = new A();",
" foo.stringVar = new String();",
" }",
"}");
assertCompiles(nonNullLiteralMatches(/* shouldMatch= */ false, Matchers.nonNullLiteral()));
}
private Scanner nonNullLiteralMatches(boolean shouldMatch, Matcher<ExpressionTree> toMatch) {
return new Scanner() {
@Override
public Void visitLiteral(LiteralTree node, VisitorState visitorState) {
assertWithMessage(node.toString())
.that(!shouldMatch ^ toMatch.matches(node, visitorState))
.isTrue();
return super.visitLiteral(node, visitorState);
}
@Override
public Void visitMemberSelect(MemberSelectTree node, VisitorState visitorState) {
assertWithMessage(node.toString())
.that(!shouldMatch ^ toMatch.matches(node, visitorState))
.isTrue();
return super.visitMemberSelect(node, visitorState);
}
@Override
public Void visitImport(ImportTree node, VisitorState visitorState) {
return null;
}
@Override
public Void visitCompilationUnit(CompilationUnitTree node, VisitorState visitorState) {
return null;
}
};
}
}
| 4,421
| 28.878378
| 95
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/MatchersTest.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.inLoop;
import static com.google.errorprone.matchers.Matchers.isPrimitiveOrVoidType;
import static com.google.errorprone.matchers.Matchers.isPrimitiveType;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.isVoidType;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.suppliers.Suppliers.typeFromString;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.MatcherChecker;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.google.errorprone.scanner.ErrorProneScanner;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link Matchers}. */
@RunWith(JUnit4.class)
public class MatchersTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(InLoopChecker.class, getClass());
@Test
public void methodNameWithParenthesisThrows() {
try {
Matchers.instanceMethod().onExactClass("java.lang.String").named("getBytes()");
fail("Expected an IAE to be throw but wasn't");
} catch (IllegalArgumentException expected) {
}
try {
Matchers.instanceMethod().onExactClass("java.lang.String").named("getBytes)");
fail("Expected an IAE to be throw but wasn't");
} catch (IllegalArgumentException expected) {
}
try {
Matchers.instanceMethod().onExactClass("java.lang.String").named("getBytes(");
fail("Expected an IAE to be throw but wasn't");
} catch (IllegalArgumentException expected) {
}
}
@Test
public void inLoopShouldMatchInWhileLoop() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public void doIt() {",
" while (true) {",
" // BUG: Diagnostic contains:",
" System.out.println();",
" }",
" }",
"}")
.doTest();
}
@Test
public void inLoopShouldMatchInDoLoop() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public void doIt() {",
" do {",
" // BUG: Diagnostic contains:",
" System.out.println();",
" } while (true);",
" }",
"}")
.doTest();
}
@Test
public void inLoopShouldMatchInForLoop() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public void doIt() {",
" for (; true; ) {",
" // BUG: Diagnostic contains:",
" System.out.println();",
" }",
" }",
"}")
.doTest();
}
@Test
public void inLoopShouldMatchInEnhancedForLoop() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"public class Test {",
" public void doIt(List<String> strings) {",
" for (String s : strings) {",
" // BUG: Diagnostic contains:",
" System.out.println();",
" }",
" }",
"}")
.doTest();
}
@Test
public void inLoopShouldNotMatchInInitializerWithoutLoop() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"public class Test {",
" {",
" System.out.println();",
" }",
"}")
.doTest();
}
@Test
public void inLoopShouldMatchInInitializerInLoop() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.List;",
"public class Test {",
" {",
" int count = 0;",
" while (count < 10) {",
" // BUG: Diagnostic contains:",
" System.out.println();",
" }",
" }",
"}")
.doTest();
}
@Test
public void inLoopShouldNotMatchInAnonymousInnerClassDefinedInLoop() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.*;",
"public class Test {",
" public void sort(List<List<String>> stringLists) {",
" for (List<String> stringList : stringLists) {",
" Collections.sort(stringList, new Comparator<String>() {",
" {",
" System.out.println();",
" }",
" public int compare(String s1, String s2) {",
" return 0;",
" }",
" public boolean equals(Object obj) {",
" return false;",
" }",
" });",
" }",
" }",
"}")
.doTest();
}
@Test
public void methodWithClassAndName() {
Matcher<MethodTree> matcher =
Matchers.methodWithClassAndName("com.google.errorprone.foo.bar.Test", "myMethod");
CompilationTestHelper.newInstance(methodTreeCheckerSupplier(matcher), getClass())
.addSourceLines(
"com/google/errorprone/foo/bar/Test.java",
"package com.google.errorprone.foo.bar;",
"public class Test {",
" // BUG: Diagnostic contains:",
" public void myMethod() {}",
"}")
.doTest();
}
@Test
public void methodReturnsSubtype() {
Matcher<MethodTree> matcher = methodReturns(isSubtypeOf("java.util.List"));
CompilationTestHelper.newInstance(methodTreeCheckerSupplier(matcher), getClass())
.addSourceLines(
"test/MethodReturnsSubtypeTest.java",
"package test;",
"public class MethodReturnsSubtypeTest {",
" // BUG: Diagnostic contains:",
" public java.util.ArrayList<String> matches() {",
" return null;",
" }",
" public java.util.HashSet<String> doesntMatch() {",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void methodReturnsType() {
Matcher<MethodTree> matcher = methodReturns(typeFromString("java.lang.Number"));
CompilationTestHelper.newInstance(methodTreeCheckerSupplier(matcher), getClass())
.addSourceLines(
"test/MethodReturnsSubtypeTest.java",
"package test;",
"public class MethodReturnsSubtypeTest {",
" public java.lang.Integer doesntMatch() {",
" return 0;",
" }",
" // BUG: Diagnostic contains:",
" public java.lang.Number matches() {",
" return 0;",
" }",
"}")
.doTest();
}
@Test
public void methodReturnsPrimitiveType() {
Matcher<MethodTree> matcher = methodReturns(isPrimitiveType());
CompilationTestHelper.newInstance(methodTreeCheckerSupplier(matcher), getClass())
.addSourceLines(
"test/MethodReturnsPrimitiveTypeTest.java",
"package test;",
"public class MethodReturnsPrimitiveTypeTest {",
" // BUG: Diagnostic contains:",
" public boolean matches1() {",
" return false;",
" }",
" public void doesntMatch() {",
" }",
" // BUG: Diagnostic contains:",
" public int matches2() {",
" return 42;",
" }",
"}")
.doTest();
}
@Test
public void methodReturnsVoidType() {
Matcher<MethodTree> matcher =
Matchers.allOf(methodReturns(typeFromString("void")), methodReturns(isVoidType()));
CompilationTestHelper.newInstance(methodTreeCheckerSupplier(matcher), getClass())
.addSourceLines(
"test/MethodReturnsVoidTypeTest.java",
"package test;",
"public class MethodReturnsVoidTypeTest {",
" public boolean doesntMatch1() {",
" return true;",
" }",
" public Object doesntMatch2() {",
" return Integer.valueOf(42);",
" }",
" // BUG: Diagnostic contains:",
" public void matches() {",
" System.out.println(42);",
" }",
"}")
.doTest();
}
@Test
public void methodReturnsPrimitiveOrVoidType() {
Matcher<MethodTree> matcher = methodReturns(isPrimitiveOrVoidType());
CompilationTestHelper.newInstance(methodTreeCheckerSupplier(matcher), getClass())
.addSourceLines(
"test/MethodReturnsPrimitiveOrVoidTypeTest.java",
"package test;",
"public class MethodReturnsPrimitiveOrVoidTypeTest {",
" public Object doesntMatch() {",
" return null;",
" }",
" // BUG: Diagnostic contains:",
" public boolean doesMatch1() {",
" return true;",
" }",
" // BUG: Diagnostic contains:",
" public void doesMatch2() {",
" }",
" // BUG: Diagnostic contains:",
" public double doesMatch3() {",
" return 42.0;",
" }",
"}")
.doTest();
}
@Test
public void methodReturnsNonPrimitiveType() {
Matcher<MethodTree> matcher = Matchers.methodReturnsNonPrimitiveType();
CompilationTestHelper.newInstance(methodTreeCheckerSupplier(matcher), getClass())
.addSourceLines(
"test/MethodReturnsSubtypeTest.java",
"package test;",
"public class MethodReturnsSubtypeTest {",
" public int doesntMatch() {",
" return 0;",
" }",
" public void doesntMatch2() {",
" }",
" // BUG: Diagnostic contains:",
" public String matches() {",
" return \"\";",
" }",
"}")
.doTest();
}
@Test
public void methodInvocationDoesntMatchAnnotation() {
CompilationTestHelper.newInstance(NoAnnotatedCallsChecker.class, getClass())
.addSourceLines(
"test/MethodInvocationDoesntMatchAnnotation.java",
"package test;",
"public class MethodInvocationDoesntMatchAnnotation {",
" @Deprecated",
" public void matches() {",
" }",
" public void doesntMatch() {",
" matches();",
" }",
"}")
.doTest();
}
@Test
public void methodInvocationHasDeclarationAnnotation() {
CompilationTestHelper.newInstance(NoAnnotatedDeclarationCallsChecker.class, getClass())
.addSourceLines(
"test/MethodInvocationMatchesDeclAnnotation.java",
"package test;",
"public class MethodInvocationMatchesDeclAnnotation {",
" @Deprecated",
" public void matches() {",
" }",
" public void callsMatch() {",
" // BUG: Diagnostic contains:",
" matches();",
" }",
"}")
.doTest();
}
@Test
public void sameArgumentGoesOutOfBounds() {
AssertionError thrown =
assertThrows(
AssertionError.class,
() ->
CompilationTestHelper.newInstance(SameArgumentChecker.class, getClass())
.addSourceLines(
"test/SameArgumentCheckerTest.java",
"package test;",
"public class SameArgumentCheckerTest {",
" public void matches(Object... args) {",
" }",
" public void callsMatch() {",
" Object obj = new Object();",
" matches(obj, \"some arg\");",
" }",
"}")
.doTest());
assertThat(thrown).hasMessageThat().contains("IndexOutOfBoundsException");
}
@Test
public void booleanConstantMatchesTrue() {
CompilationTestHelper.newInstance(BooleanConstantTrueChecker.class, getClass())
.addSourceLines(
"test/BooleanConstantTrueCheckerTest.java",
"package test;",
"public class BooleanConstantTrueCheckerTest {",
" public void function() {",
" // BUG: Diagnostic contains:",
" method(Boolean.TRUE);",
" method(Boolean.FALSE);",
" }",
" void method(Object value) {}",
"}")
.doTest();
}
@Test
public void packageNameChecker() {
CompilationTestHelper.newInstance(PackageNameChecker.class, getClass())
.addSourceLines(
"test/foo/ClassName.java",
"package test.foo;",
"// BUG: Diagnostic contains:",
"public class ClassName {}")
.doTest();
CompilationTestHelper.newInstance(PackageNameChecker.class, getClass())
.addSourceLines(
"test/foo/ClassName.java",
"package testyfoo;",
// No match, the "." is escaped correctly in the regex "test.foo".
"public class ClassName {}")
.doTest();
CompilationTestHelper.newInstance(PackageNameChecker.class, getClass())
.addSourceLines(
"test/foo/bar/ClassName.java",
"package test.foo.bar;",
"// BUG: Diagnostic contains:",
"public class ClassName {}")
.doTest();
CompilationTestHelper.newInstance(PackageNameChecker.class, getClass())
.addSourceLines(
"test/ClassName.java", // Do not wrap.
"package test;",
"public class ClassName {}")
.doTest();
CompilationTestHelper.newInstance(PackageNameChecker.class, getClass())
.addSourceLines(
"test/foobar/ClassName.java",
"package test.foobar;",
"// BUG: Diagnostic contains:",
"public class ClassName {}")
.doTest();
}
@BugPattern(
summary = "Checker that flags the given expression statement if the given matcher matches",
severity = ERROR)
public static class InLoopChecker extends MatcherChecker {
public InLoopChecker() {
super("System.out.println();", inLoop());
}
}
private static ScannerSupplier methodTreeCheckerSupplier(Matcher<MethodTree> matcher) {
return ScannerSupplier.fromScanner(new ErrorProneScanner(new MethodTreeChecker(matcher)));
}
@BugPattern(
summary = "Checker that flags the given method declaration if the given matcher matches",
severity = ERROR)
static class MethodTreeChecker extends BugChecker implements MethodTreeMatcher {
private final Matcher<MethodTree> matcher;
public MethodTreeChecker(Matcher<MethodTree> matcher) {
this.matcher = matcher;
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
return matcher.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH;
}
}
/** Simple checker to make sure hasAnnotation doesn't match on MethodInvocationTree. */
@BugPattern(
name = "MethodInvocationTreeChecker",
summary = "Checker that flags the given method invocation if the given matcher matches",
severity = ERROR)
public static class NoAnnotatedCallsChecker extends BugChecker
implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (Matchers.hasAnnotation("java.lang.Deprecated").matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
}
/** Simple checker to make sure sameArgument doesn't throw IndexOutOfBoundsException. */
@BugPattern(
summary = "Checker that matches invocation if the first argument is repeated",
severity = ERROR)
public static class SameArgumentChecker extends BugChecker
implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
// intentionally go above arg size.
for (int i = 1; i <= tree.getArguments().size(); i++) {
if (Matchers.sameArgument(0, i).matches(tree, state)) {
return describeMatch(tree);
}
}
return Description.NO_MATCH;
}
}
/** Checker that makes sure symbolHasAnnotation matches on MethodInvocationTree. */
@BugPattern(
summary = "Checker that flags the given method invocation if the given matcher matches",
severity = ERROR)
public static class NoAnnotatedDeclarationCallsChecker extends BugChecker
implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (Matchers.symbolHasAnnotation("java.lang.Deprecated").matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
}
/** Checker that checks if a class is in a particular package. */
@BugPattern(summary = "Checks the name of the package", severity = ERROR)
public static class PackageNameChecker extends BugChecker implements ClassTreeMatcher {
private static final Matcher<Tree> MATCHER = Matchers.packageStartsWith("test.foo");
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return MATCHER.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH;
}
}
/** Checker that checks if an argument is 'Boolean.TRUE'. */
@BugPattern(summary = "BooleanConstantTrueChecker", severity = ERROR)
public static class BooleanConstantTrueChecker extends BugChecker
implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (Matchers.methodInvocation(
MethodMatchers.anyMethod(),
ChildMultiMatcher.MatchType.AT_LEAST_ONE,
Matchers.booleanConstant(true))
.matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
}
}
| 19,995
| 34.266314
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/CompilerBasedAbstractTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.scanner.Scanner;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.tools.javac.main.Main.Result;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
/**
* @author alexeagle@google.com (Alex Eagle)
*/
public class CompilerBasedAbstractTest {
private static class FileToCompile {
final String name;
final String[] lines;
FileToCompile(String name, String... lines) {
this.name = name;
this.lines = lines;
}
}
final List<FileToCompile> filesToCompile = new ArrayList<>();
@After
public void clearSourceFiles() {
filesToCompile.clear();
}
protected void writeFile(String fileName, String... lines) {
filesToCompile.add(new FileToCompile(fileName, lines));
}
private void assertCompiles(ScannerSupplier scannerSupplier) {
CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(scannerSupplier, getClass()).expectResult(Result.OK);
for (FileToCompile fileToCompile : filesToCompile) {
compilationHelper = compilationHelper.addSourceLines(fileToCompile.name, fileToCompile.lines);
}
compilationHelper.doTest();
}
protected void assertCompiles(Scanner scanner) {
assertCompiles(ScannerSupplier.fromScanner(scanner));
}
}
| 2,011
| 29.484848
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/UnusedReturnValueMatcherTest.java
|
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link UnusedReturnValueMatcher}. */
@RunWith(JUnit4.class)
public final class UnusedReturnValueMatcherTest {
/** Checker using {@link UnusedReturnValueMatcher}. */
@BugPattern(severity = WARNING, summary = "bad")
public static class Checker extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher, MemberReferenceTreeMatcher {
protected boolean allowInExceptionTesting() {
return true;
}
private Description match(ExpressionTree tree, VisitorState state) {
if (!UnusedReturnValueMatcher.isReturnValueUnused(tree, state)) {
return Description.NO_MATCH;
}
UnusedReturnValueMatcher matcher = UnusedReturnValueMatcher.get(allowInExceptionTesting());
return matcher.isAllowed(tree, state)
? buildDescription(tree).setMessage("allowed").build()
: describeMatch(tree);
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return match(tree, state);
}
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
return match(tree, state);
}
@Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
return match(tree, state);
}
}
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(Checker.class, getClass());
@Test
public void positive() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"public class Test {",
" static interface Foo {",
" String bar();",
" }",
"",
" static String staticMethod() {",
" return \"static\";",
" }",
" String instanceMethod() {",
" return \"instance\";",
" }",
"",
" static void run(Runnable r) {}",
"",
" void stuff(Foo foo) {",
" // BUG: Diagnostic contains: bad",
" foo.bar();",
" // BUG: Diagnostic contains: bad",
" run(foo::bar);",
" // BUG: Diagnostic contains: bad",
" run(() -> foo.bar());",
" // BUG: Diagnostic contains: bad",
" staticMethod();",
" // BUG: Diagnostic contains: bad",
" Test.staticMethod();",
" // BUG: Diagnostic contains: bad",
" instanceMethod();",
" // BUG: Diagnostic contains: bad",
" this.instanceMethod();",
" // BUG: Diagnostic contains: bad",
" run(Test::staticMethod);",
" // BUG: Diagnostic contains: bad",
" run(() -> Test.staticMethod());",
" // BUG: Diagnostic contains: bad",
" run(this::instanceMethod);",
" // BUG: Diagnostic contains: bad",
" run(() -> instanceMethod());",
" // BUG: Diagnostic contains: bad",
" run(() -> this.instanceMethod());",
" }",
"}")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"import java.util.function.Supplier;",
"public class Test {",
" interface Foo {",
" String bar();",
" void voidMethod();",
" }",
"",
" static String staticMethod() {",
" return \"static\";",
" }",
" String instanceMethod() {",
" return \"instance\";",
" }",
"",
" static void accept(String s) {}",
" static void run(Supplier<String> s) {}",
"",
" String stuff(Foo foo) {",
" String s = foo.bar();",
" s = staticMethod();",
" s = instanceMethod();",
" s = Test.staticMethod();",
" s = this.instanceMethod();",
" accept(foo.bar());",
" accept(staticMethod());",
" accept(instanceMethod());",
" accept(Test.staticMethod());",
" accept(this.instanceMethod());",
" run(foo::bar);",
" run(Test::staticMethod);",
" run(this::instanceMethod);",
" run(() -> foo.bar());",
" run(() -> staticMethod());",
" run(() -> instanceMethod());",
" run(() -> Test.staticMethod());",
" run(() -> this.instanceMethod());",
" Supplier<String> supplier = foo::bar;",
" supplier = Test::staticMethod;",
" supplier = this::instanceMethod;",
" supplier = () -> foo.bar();",
" supplier = () -> staticMethod();",
" supplier = () -> instanceMethod();",
" supplier = () -> Test.staticMethod();",
" supplier = () -> this.instanceMethod();",
" foo.voidMethod();",
" return foo.bar();",
" }",
"}")
.doTest();
}
@Test
public void allowed() {
compilationHelper
.addSourceLines(
"test/Test.java",
"package test;",
"import static org.junit.Assert.fail;",
"import static org.mockito.Mockito.mock;",
"import static org.mockito.Mockito.verify;",
"import java.util.function.Consumer;",
"import java.util.stream.Stream;",
"import org.junit.rules.ExpectedException;",
"public class Test {",
" interface Foo<T> {",
" T bar();",
" }",
"",
" private final ExpectedException expected = ExpectedException.none();",
"",
" static void run(Runnable r) {}",
" static <T> void doSomething(T foo, Consumer<? super T> c) {}",
"",
" interface SubFoo<T> extends Foo<T> {}",
" interface VoidFoo extends Foo<Void> {}",
" interface VoidSubFoo extends SubFoo<Void> {}",
"",
" void javaLangVoid(",
" Foo<Void> foo, SubFoo<Void> subFoo, VoidFoo voidFoo, VoidSubFoo voidSubFoo) {",
" // BUG: Diagnostic contains: allowed",
" foo.bar();",
" // BUG: Diagnostic contains: allowed",
" run(foo::bar);",
" // BUG: Diagnostic contains: allowed",
" run(() -> foo.bar());",
"",
" // BUG: Diagnostic contains: allowed",
" subFoo.bar();",
" // BUG: Diagnostic contains: allowed",
" run(subFoo::bar);",
" // BUG: Diagnostic contains: allowed",
" run(() -> subFoo.bar());",
"",
" // BUG: Diagnostic contains: allowed",
" voidFoo.bar();",
" // BUG: Diagnostic contains: allowed",
" run(voidFoo::bar);",
" // BUG: Diagnostic contains: allowed",
" run(() -> voidFoo.bar());",
"",
" // BUG: Diagnostic contains: allowed",
" voidSubFoo.bar();",
" // BUG: Diagnostic contains: allowed",
" run(voidSubFoo::bar);",
" // BUG: Diagnostic contains: allowed",
" run(() -> voidSubFoo.bar());",
"",
" // BUG: Diagnostic contains: allowed",
" doSomething(voidFoo, VoidFoo::bar);",
" // BUG: Diagnostic contains: allowed",
" doSomething(voidSubFoo, VoidSubFoo::bar);",
" }",
"",
" void exceptionTestingFail(Foo<String> foo) {",
" try {",
" // BUG: Diagnostic contains: allowed",
" foo.bar();",
" fail();",
" } catch (RuntimeException expected) {",
" }",
"",
" expected.expect(RuntimeException.class);",
" // BUG: Diagnostic contains: allowed",
" foo.bar();",
" }",
"",
" void mockito() {",
" Foo<?> foo = mock(Foo.class);",
" // BUG: Diagnostic contains: allowed",
" verify(foo).bar();",
" }",
"",
" static <T> T genericMethod(T input) {",
" return input;",
" }",
"",
" void b219073237(Stream<Void> stream) {",
// TODO(cgdecker): This should be allowed
" // BUG: Diagnostic contains: bad",
" stream.peek(Test::genericMethod).forEach(v -> {});",
" }",
"}")
.doTest();
}
/** {@link Checker} with {@code allowInExceptionTesting = false}. */
@BugPattern(severity = WARNING, summary = "bad")
public static class NotAllowedInExceptionTesting extends Checker {
@Override
protected boolean allowInExceptionTesting() {
return false;
}
}
@Test
public void allowedInExceptionTestingFalse() {
CompilationTestHelper notAllowedInExceptionTesting =
CompilationTestHelper.newInstance(NotAllowedInExceptionTesting.class, getClass());
notAllowedInExceptionTesting
.addSourceLines(
"test/Test.java",
"package test;",
"import static org.junit.Assert.fail;",
"import org.junit.rules.ExpectedException;",
"public class Test {",
" interface Foo<T> {",
" T bar();",
" }",
"",
" private final ExpectedException expected = ExpectedException.none();",
"",
" void exceptionTesting(Foo<String> foo) {",
" try {",
" // BUG: Diagnostic contains: bad",
" foo.bar();",
" fail();",
" } catch (RuntimeException expected) {",
" }",
"",
" expected.expect(RuntimeException.class);",
" // BUG: Diagnostic contains: bad",
" foo.bar();",
" }",
"}")
.doTest();
}
}
| 11,948
| 36.224299
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/CompileTimeConstantExpressionMatcherTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.annotations.CompileTimeConstant;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.sun.source.tree.VariableTree;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import javax.lang.model.element.ElementKind;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link CompileTimeConstantExpressionMatcher}Test */
@RunWith(JUnit4.class)
public class CompileTimeConstantExpressionMatcherTest {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(
CompileTimeConstantExpressionMatcherTester.class, getClass());
@Test
public void matchesLiteralsAndStaticFinals() {
testHelper
.addSourceLines(
"Test.java",
"public class Test {",
" private final String final_string = \"bap\";",
" private final int final_int = 29;",
" private static final int static_final_int = 29;",
" public void m() { ",
" // BUG: Diagnostic contains: true",
" String s1 = \"boop\";",
" // BUG: Diagnostic contains: true",
" String s2 = \"boop\" + final_string;",
" // BUG: Diagnostic contains: true",
" int int2 = 42;",
" // BUG: Diagnostic contains: true",
" Integer int3 = 42 * final_int;",
" // BUG: Diagnostic contains: true",
" Integer int4 = 12 - static_final_int;",
" // BUG: Diagnostic contains: true",
" boolean bool4 = false;",
" }",
"}")
.doTest();
}
@Test
public void nullLiteral() {
testHelper
.addSourceLines(
"Test.java",
"public class Test {",
" private static final String static_final_string = null;",
" public void m() { ",
" // BUG: Diagnostic contains: true",
" String s1 = null;",
" // BUG: Diagnostic contains: false",
" String s2 = static_final_string;",
" // BUG: Diagnostic contains: true",
" String s3 = (String) null;",
" }",
"}")
.doTest();
}
@Test
public void doesNotMatchNonLiterals() {
testHelper
.addSourceLines(
"Test.java",
"package test;",
"public class Test {",
" private final int nonfinal_int;",
" public Test(int i) { ",
" nonfinal_int = i;",
" }",
" public void m(String s) { ",
" // BUG: Diagnostic contains: false",
" String s1 = s;",
" // BUG: Diagnostic contains: false",
" int int2 = s.length();",
" // BUG: Diagnostic contains: false",
" Integer int3 = nonfinal_int;",
" // BUG: Diagnostic contains: false",
" Integer int4 = 14 * nonfinal_int;",
" // BUG: Diagnostic contains: true",
" boolean bool4 = false;",
" }",
"}")
.doTest();
}
@Test
public void finalCompileTimeConstantMethodParameters() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class Test {",
" public void m1(final @CompileTimeConstant String s) {",
" // BUG: Diagnostic contains: true",
" String s1 = s;",
" }",
" public void m2(@CompileTimeConstant String s) {",
" s = null;",
" // BUG: Diagnostic contains: false",
" String s2 = s;",
" }",
" public void m3(final String s) {",
" // BUG: Diagnostic contains: false",
" String s3 = s;",
" }",
" public void m4(@CompileTimeConstant String s) {",
" // BUG: Diagnostic contains: true",
" String s4 = s;",
" }",
"}")
.doTest();
}
@Test
public void finalCompileTimeConstantConstructorParameters() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"public class Test {",
" public Test(final @CompileTimeConstant String s) {",
" // BUG: Diagnostic contains: true",
" String s1 = s;",
" }",
" public Test(@CompileTimeConstant String s, int foo) {",
" s = null;",
" // BUG: Diagnostic contains: false",
" String s2 = s;",
" }",
" public Test(final String s, boolean foo) {",
" // BUG: Diagnostic contains: false",
" String s3 = s;",
" }",
" public Test(@CompileTimeConstant String s, long foo) {",
" // BUG: Diagnostic contains: true",
" String s4 = s;",
" }",
"}")
.doTest();
}
// TODO(xtof): We'd like to eventually support other cases, but I first need
// to determine with confidence that the checker can ensure all initializations
// and assignments to such variables are compile-time-constant.
// For now, the annotation's target is restricted to ElementType.PARAMETER.
@Test
public void compileTimeConstantAnnotationOnlyAllowedOnParameterOrField() {
assertThat(CompileTimeConstant.class.getAnnotation(Target.class).value())
.isEqualTo(new ElementType[] {ElementType.PARAMETER, ElementType.FIELD});
}
@Test
public void conditionalExpression() {
testHelper
.addSourceLines(
"Test.java",
"abstract class Test {",
" abstract boolean g();",
" public void m(boolean flag) {",
" // BUG: Diagnostic contains: false",
" boolean bool1 = flag ? true : g();",
" // BUG: Diagnostic contains: false",
" boolean bool2 = flag ? g() : false;",
" // BUG: Diagnostic contains: true",
" boolean bool3 = flag ? true : false;",
" }",
"}")
.doTest();
}
@Test
public void parentheses() {
testHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"abstract class Test {",
" public void m(@CompileTimeConstant String ctc) {",
" // BUG: Diagnostic contains: true",
" String a = (ctc);",
" }",
"}")
.doTest();
}
@Test
public void concatenatedStrings() {
testHelper
.addSourceLines(
"Test.java",
"package test;",
"import com.google.errorprone.annotations.CompileTimeConstant;",
"abstract class Test {",
" public void m(@CompileTimeConstant String ctc, String nonCtc) {",
" // BUG: Diagnostic contains: true",
" String a = \"foo\" + ctc;",
" // BUG: Diagnostic contains: true",
" String b = ctc + \"foo\";",
" // BUG: Diagnostic contains: false",
" String c = nonCtc + \"foo\";",
" // BUG: Diagnostic contains: false",
" String d = nonCtc + ctc;",
" // BUG: Diagnostic contains: true",
" String e = \"foo\" + (ctc == null ? \"\" : \"\");",
" // BUG: Diagnostic contains: true",
" String f = \"foo\" + 1;",
" // BUG: Diagnostic contains: true",
" String g = \"foo\" + 3.14;",
" }",
"}")
.doTest();
}
/** A test-only bugpattern for testing {@link CompileTimeConstantExpressionMatcher}. */
@BugPattern(severity = WARNING, summary = "")
public static final class CompileTimeConstantExpressionMatcherTester extends BugChecker
implements VariableTreeMatcher {
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (!getSymbol(tree).getKind().equals(ElementKind.LOCAL_VARIABLE)) {
return Description.NO_MATCH;
}
return buildDescription(tree)
.setMessage(
CompileTimeConstantExpressionMatcher.instance().matches(tree.getInitializer(), state)
? "true"
: "false")
.build();
}
}
}
| 9,715
| 35.942966
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/EnclosingTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.matchers.Matchers.enclosingBlock;
import static com.google.errorprone.matchers.Matchers.enclosingNode;
import static com.google.errorprone.matchers.Matchers.parentNode;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link Matchers#enclosingNode}, {@link Matchers#parentNode}, {@link
* Matchers#enclosingBlock}, {@link Enclosing.BlockOrCase}, and at least some of the code paths also
* used by {@link Matchers#enclosingClass} and {@link Matchers#enclosingMethod}. The tests focus on
* verifying that the {@link TreePath} is set correctly.
*
* @author cpovirk@google.com (Chris Povirk)
*/
@RunWith(JUnit4.class)
public class EnclosingTest extends CompilerBasedAbstractTest {
private abstract static class IsInterestingLoopSubNode<T extends Tree> implements Matcher<T> {
@Override
public boolean matches(T t, VisitorState state) {
if (state.getPath().getParentPath() == null) {
return false;
}
Tree parent = state.getPath().getParentPath().getLeaf();
return (parent instanceof ForLoopTree && (interestingPartOfLoop((ForLoopTree) parent) == t));
}
abstract Object interestingPartOfLoop(ForLoopTree loop);
}
private static final Matcher<Tree> IS_LOOP_CONDITION =
new IsInterestingLoopSubNode<Tree>() {
@Override
Object interestingPartOfLoop(ForLoopTree loop) {
return loop.getCondition();
}
};
private static final Matcher<BlockTree> IS_LOOP_STATEMENT =
new IsInterestingLoopSubNode<BlockTree>() {
@Override
Object interestingPartOfLoop(ForLoopTree loop) {
return loop.getStatement();
}
};
private static final Matcher<Tree> ENCLOSED_IN_LOOP_CONDITION = enclosingNode(IS_LOOP_CONDITION);
private static final Matcher<Tree> CHILD_OF_LOOP_CONDITION = parentNode(IS_LOOP_CONDITION);
private static final Matcher<Tree> USED_UNDER_LOOP_STATEMENT = enclosingBlock(IS_LOOP_STATEMENT);
private static final Matcher<Tree> USED_UNDER_LOOP_STATEMENT_ACCORDING_TO_BLOCK_OR_CASE =
new Enclosing.BlockOrCase<>(IS_LOOP_STATEMENT, Matchers.<CaseTree>nothing());
final List<ScannerTest> tests = new ArrayList<>();
@After
public void tearDown() {
for (ScannerTest test : tests) {
test.assertDone();
}
}
/** Tests that a node is not enclosed by itself. */
@Test
public void usedDirectlyInLoopCondition() {
writeFile(
"A.java",
"public class A {",
" A() {",
" boolean foo = true;",
" for (int i = 0; foo; i++) {}",
" }",
"}");
assertCompiles(fooIsUsedUnderLoopCondition(false));
assertCompiles(fooIsChildOfLoopCondition(false));
assertCompiles(fooIsUsedUnderLoopStatement(false));
assertCompiles(fooIsUsedUnderLoopStatementAccordingToBlockOrCase(false));
}
/** Tests that a node is enclosed by its parent. */
@Test
public void usedAsChildTreeOfLoopCondition() {
writeFile(
"A.java",
"public class A {",
" A() {",
" boolean foo = true;",
" for (int i = 0; !foo; i++) {}",
" }",
"}");
assertCompiles(fooIsUsedUnderLoopCondition(true));
assertCompiles(fooIsChildOfLoopCondition(true));
assertCompiles(fooIsUsedUnderLoopStatement(false));
assertCompiles(fooIsUsedUnderLoopStatementAccordingToBlockOrCase(false));
}
/** Tests that a node is enclosed by a node many levels up the tree. */
@Test
public void usedInSubTreeOfLoopCondition() {
writeFile(
"A.java",
"public class A {",
" A() {",
" boolean foo = true;",
" for (int i = 0; !!!!!!!!!foo; i++) {}",
" }",
"}");
assertCompiles(fooIsUsedUnderLoopCondition(true));
assertCompiles(fooIsChildOfLoopCondition(false));
assertCompiles(fooIsUsedUnderLoopStatement(false));
assertCompiles(fooIsUsedUnderLoopStatementAccordingToBlockOrCase(false));
}
/** Tests enclosing blocks. */
@Test
public void usedInStatement() {
writeFile(
"A.java",
"public class A {",
" A() {",
" boolean foo = true;",
" for (int i = 0; i < 100; i++) {",
" foo = !foo;",
" }",
" }",
"}");
assertCompiles(fooIsUsedUnderLoopCondition(false));
assertCompiles(fooIsChildOfLoopCondition(false));
assertCompiles(fooIsUsedUnderLoopStatement(true));
assertCompiles(fooIsUsedUnderLoopStatementAccordingToBlockOrCase(true));
}
/** Make sure the scanners are doing what we expect. */
@Test
public void usedElsewhereInLoop() {
writeFile(
"A.java",
"public class A {",
" A() {",
" boolean foo = true;",
" for (int i = foo ? 0 : 1; i < 100; foo = !foo) {}",
" }",
"}");
assertCompiles(fooIsUsedUnderLoopCondition(false));
assertCompiles(fooIsChildOfLoopCondition(false));
assertCompiles(fooIsUsedUnderLoopStatement(false));
assertCompiles(fooIsUsedUnderLoopStatementAccordingToBlockOrCase(false));
}
private abstract class ScannerTest extends Scanner {
abstract void assertDone();
}
private Scanner fooIsUsedUnderLoopCondition(boolean shouldMatch) {
return fooMatches(shouldMatch, ENCLOSED_IN_LOOP_CONDITION);
}
private Scanner fooIsChildOfLoopCondition(boolean shouldMatch) {
return fooMatches(shouldMatch, CHILD_OF_LOOP_CONDITION);
}
private Scanner fooIsUsedUnderLoopStatement(boolean shouldMatch) {
return fooMatches(shouldMatch, USED_UNDER_LOOP_STATEMENT);
}
private Scanner fooIsUsedUnderLoopStatementAccordingToBlockOrCase(boolean shouldMatch) {
return fooMatches(shouldMatch, USED_UNDER_LOOP_STATEMENT_ACCORDING_TO_BLOCK_OR_CASE);
}
private Scanner fooMatches(boolean shouldMatch, Matcher<Tree> matcher) {
ScannerTest test =
new ScannerTest() {
boolean matched = false;
@Override
public Void visitIdentifier(IdentifierTree tree, VisitorState state) {
// Normally handled by ErrorProneMatcher:
// TODO(cpovirk): Find a way for this to be available by default to Matcher tests.
state = state.withPath(getCurrentPath());
matched |= tree.getName().contentEquals("foo") && matcher.matches(tree, state);
return null;
}
@Override
void assertDone() {
assertThat(matched).isEqualTo(shouldMatch);
}
};
tests.add(test);
return test;
}
}
| 7,714
| 33.752252
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/JUnitMatchersTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.sun.source.tree.ClassTree;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author epmjohnston@google.com (Emily Johnston)
*/
@RunWith(JUnit4.class)
public final class JUnitMatchersTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JUnitVersionMatcher.class, getClass());
@Test
public void runWithAnnotationOnClass_shouldBeJUnit4() {
compilationHelper
.addSourceLines(
"RunWithAnnotationOnClass.java",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"@RunWith(JUnit4.class)",
"// BUG: Diagnostic contains: Version:JUnit4",
"public class RunWithAnnotationOnClass {}")
.doTest();
}
@Test
public void annotationOnMethod_shouldBeJUnit4() {
compilationHelper
.addSourceLines(
"TestAnnotationOnMethod.java",
"import org.junit.Test;",
"// BUG: Diagnostic contains: Version:JUnit4",
"public class TestAnnotationOnMethod {",
" @Test",
" public void someTest() {}",
"}")
.doTest();
}
@Test
public void beforeAfterAnnotations_notRecognized() {
compilationHelper
.addSourceLines(
"BeforeAnnotationOnMethod.java",
"import org.junit.Before;",
"public class BeforeAnnotationOnMethod {",
" @Before",
" public void someTest() {}",
"}")
.addSourceLines(
"BeforeClassAnnotationOnMethod.java",
"import org.junit.BeforeClass;",
"public class BeforeClassAnnotationOnMethod {",
" @BeforeClass",
" public void someTest() {}",
"}")
.addSourceLines(
"AfterAnnotationOnMethod.java",
"import org.junit.After;",
"public class AfterAnnotationOnMethod {",
" @After",
" public void someTest() {}",
"}")
.addSourceLines(
"AfterClassAnnotationOnMethod.java",
"import org.junit.AfterClass;",
"public class AfterClassAnnotationOnMethod {",
" @AfterClass",
" public void someTest() {}",
"}")
.doTest();
}
@Test
public void ignoreAnnotation_notRecognized() {
compilationHelper
.addSourceLines(
"TestIgnoreAnnotation.java",
"import org.junit.Ignore;",
"public class TestIgnoreAnnotation {",
" @Ignore",
" public void someTest() {}",
"}")
.doTest();
}
@Test
public void ignoreClassAnnotation_notRecognized() {
compilationHelper
.addSourceLines(
"TestIgnoreAnnotation.java",
"import org.junit.Ignore;",
// Uncomment this line if we decide to recognize @Ignored classes as JUnit4
// "// BUG: Diagnostic contains: Version:JUnit4",
"@Ignore public class TestIgnoreAnnotation {}")
.doTest();
}
@Test
public void ruleAnnotation_notRecognized() {
compilationHelper
.addSourceLines(
"MyRule.java",
"import org.junit.rules.TestRule;",
"import org.junit.runners.model.Statement;",
"import org.junit.runner.Description;",
"public class MyRule implements TestRule {",
" public Statement apply(Statement s, Description d) { return null; }",
"}")
.addSourceLines(
"TestRuleAnnotation.java",
"import org.junit.Rule;",
"public class TestRuleAnnotation {",
" @Rule public final MyRule r = new MyRule();",
"}")
.doTest();
}
@Test
public void caseDescendant_shouldBeJUnit3() {
compilationHelper
.addSourceLines(
"TestCaseDescendant.java",
"import junit.framework.TestCase;",
"// BUG: Diagnostic contains: Version:JUnit3",
"public class TestCaseDescendant extends TestCase {}")
.doTest();
}
@Test
public void ambiguous_noRecognizedVersion() {
compilationHelper
.addSourceLines(
"AmbiguousRunWith.java",
"import junit.framework.TestCase;",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"import org.junit.Test;",
"@RunWith(JUnit4.class)",
"// BUG: Diagnostic contains: Version:Both",
"public class AmbiguousRunWith extends TestCase {",
" public void someTest() {}",
"}")
.addSourceLines(
"AmbiguousTest.java",
"import junit.framework.TestCase;",
"import org.junit.runner.RunWith;",
"import org.junit.runners.JUnit4;",
"import org.junit.Test;",
"// BUG: Diagnostic contains: Version:Both",
"public class AmbiguousTest extends TestCase {",
" @Test",
" public void someTest() {}",
"}")
.doTest();
}
/** Helper class to surface which version of JUnit a class looks like to Error Prone. */
@BugPattern(
summary = "Matches on JUnit test classes, emits description with its JUnit version.",
severity = SeverityLevel.WARNING)
public static class JUnitVersionMatcher extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
// As currently implemented, isJUnit3TestClass, isJUnit4TestClass, and isAmbiguousJUnitVersion
// matches should be disjoint. This may change in the future, in which case the assertion
// here should be changed to allow for multiple matches.
List<String> versions = new ArrayList<>();
if (JUnitMatchers.isJUnit3TestClass.matches(tree, state)) {
versions.add("JUnit3");
}
if (JUnitMatchers.isJUnit4TestClass.matches(tree, state)) {
versions.add("JUnit4");
}
if (JUnitMatchers.isAmbiguousJUnitVersion.matches(tree, state)) {
versions.add("Both");
}
if (versions.isEmpty()) {
return Description.NO_MATCH;
}
assertThat(versions).hasSize(1);
return this.buildDescription(tree).setMessage("Version:" + versions.get(0)).build();
}
}
}
| 7,520
| 33.658986
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/MethodReturnsNonNullNextTokenTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author deminguyen@google.com (Demi Nguyen)
*/
@RunWith(JUnit4.class)
public class MethodReturnsNonNullNextTokenTest extends CompilerBasedAbstractTest {
@Test
public void shouldMatch() {
writeFile(
"A.java",
"import java.util.StringTokenizer;",
"public class A {",
" public void testNextToken() {",
" StringTokenizer st = new StringTokenizer(\"test string\");",
" st.nextToken();",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ true, Matchers.methodReturnsNonNull()));
}
@Test
public void shouldNotMatchOtherMethod() {
writeFile(
"A.java",
"import java.util.StringTokenizer;",
"public class A {",
" public void testOtherMethod() {",
" StringTokenizer st = new StringTokenizer(\"test string\");",
" st.hasMoreTokens();",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ false, Matchers.methodReturnsNonNull()));
}
@Test
public void shouldNotMatchOverriddenMethod() {
writeFile(
"A.java",
"import java.util.StringTokenizer;",
"public class A extends StringTokenizer {",
" public A(String str, String delim, boolean returnDelims) {",
" super(str, delim, returnDelims);",
" }",
" @Override",
" public String nextToken() {",
" return \"overridden method\";",
" }",
" public void testOverriddenNextToken() {",
" nextToken();",
" }",
"}");
assertCompiles(
methodInvocationMatches(/* shouldMatch= */ false, Matchers.methodReturnsNonNull()));
}
private Scanner methodInvocationMatches(boolean shouldMatch, Matcher<ExpressionTree> toMatch) {
return new Scanner() {
@Override
public Void visitMethodInvocation(MethodInvocationTree node, VisitorState visitorState) {
ExpressionTree methodSelect = node.getMethodSelect();
if (!methodSelect.toString().equals("super")) {
assertWithMessage(methodSelect.toString())
.that(!shouldMatch ^ toMatch.matches(node, visitorState))
.isTrue();
}
return super.visitMethodInvocation(node, visitorState);
}
};
}
}
| 3,318
| 31.861386
| 97
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/CompoundAssignmentTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertThrows;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree.Kind;
import java.util.EnumSet;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author adgar@google.com (Mike Edgar)
*/
@RunWith(JUnit4.class)
public class CompoundAssignmentTest extends CompilerBasedAbstractTest {
@Test
public void cannotConstructWithInvalidKind() {
Set<Kind> operators = EnumSet.noneOf(Kind.class);
operators.add(Kind.PLUS_ASSIGNMENT);
operators.add(Kind.IF);
assertThrows(
IllegalArgumentException.class,
() ->
assertCompiles(
compoundAssignmentMatches(
/* shouldMatch= */ true,
new CompoundAssignment(
operators,
Matchers.<ExpressionTree>anything(),
Matchers.<ExpressionTree>anything()))));
}
@Test
public void cannotConstructWithBinaryOperator() {
Set<Kind> operators = EnumSet.noneOf(Kind.class);
operators.add(Kind.PLUS);
operators.add(Kind.PLUS_ASSIGNMENT);
assertThrows(
IllegalArgumentException.class,
() ->
assertCompiles(
compoundAssignmentMatches(
/* shouldMatch= */ true,
new CompoundAssignment(
operators,
Matchers.<ExpressionTree>anything(),
Matchers.<ExpressionTree>anything()))));
}
@Test
public void shouldMatch() {
writeFile(
"A.java",
"public class A {",
" public void getHash(int a, long b) {",
" long c = a;",
" c += b;",
" }",
"}");
Set<Kind> operators = EnumSet.noneOf(Kind.class);
operators.add(Kind.PLUS_ASSIGNMENT);
operators.add(Kind.LEFT_SHIFT_ASSIGNMENT);
assertCompiles(
compoundAssignmentMatches(
/* shouldMatch= */ true,
new CompoundAssignment(
operators,
Matchers.<ExpressionTree>anything(),
Matchers.<ExpressionTree>anything())));
}
@Test
public void shouldNotMatchWhenOperatorDiffers() {
writeFile(
"A.java",
"public class A {",
" public void getHash(int a, long b) {",
" long c = a;",
" c -= b;",
" }",
"}");
Set<Kind> operators = EnumSet.noneOf(Kind.class);
operators.add(Kind.PLUS_ASSIGNMENT);
assertCompiles(
compoundAssignmentMatches(
/* shouldMatch= */ false,
new CompoundAssignment(
operators,
Matchers.<ExpressionTree>anything(),
Matchers.<ExpressionTree>anything())));
}
@Test
public void shouldNotMatchWhenLeftOperandMatcherFails() {
writeFile(
"A.java",
"public class A {",
" public void getHash(int a, long b) {",
" long c = a;",
" c += b;",
" }",
"}");
Set<Kind> operators = EnumSet.noneOf(Kind.class);
operators.add(Kind.PLUS_ASSIGNMENT);
assertCompiles(
compoundAssignmentMatches(
/* shouldMatch= */ false,
new CompoundAssignment(
operators,
Matchers.<ExpressionTree>isArrayType(),
Matchers.<ExpressionTree>anything())));
}
@Test
public void shouldNotMatchWhenRightOperandMatcherFails() {
writeFile(
"A.java",
"public class A {",
" public void getHash(int a, long b) {",
" long c = a;",
" c += b;",
" }",
"}");
Set<Kind> operators = EnumSet.noneOf(Kind.class);
operators.add(Kind.PLUS_ASSIGNMENT);
assertCompiles(
compoundAssignmentMatches(
/* shouldMatch= */ false,
new CompoundAssignment(
operators,
Matchers.<ExpressionTree>anything(),
Matchers.<ExpressionTree>isArrayType())));
}
private Scanner compoundAssignmentMatches(boolean shouldMatch, CompoundAssignment toMatch) {
return new Scanner() {
@Override
public Void visitCompoundAssignment(CompoundAssignmentTree node, VisitorState visitorState) {
assertWithMessage(node.toString())
.that(!shouldMatch ^ toMatch.matches(node, visitorState))
.isTrue();
return super.visitCompoundAssignment(node, visitorState);
}
};
}
}
| 5,392
| 30.723529
| 99
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/AnnotationHasArgumentWithValueTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.errorprone.matchers.Matchers.stringLiteral;
import com.google.errorprone.VisitorState;
import com.google.errorprone.scanner.Scanner;
import com.sun.source.tree.AnnotationTree;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author alexeagle@google.com (Alex Eagle)
*/
@RunWith(JUnit4.class)
public class AnnotationHasArgumentWithValueTest extends CompilerBasedAbstractTest {
@Before
public void setUp() {
writeFile("Thing.java", "public @interface Thing {", " String stuff();", "}");
}
@Test
public void matches() {
writeFile("A.java", "@Thing(stuff=\"y\")", "public class A {}");
assertCompiles(
annotationMatches(
/* shouldMatch= */ true,
new AnnotationHasArgumentWithValue("stuff", stringLiteral("y"))));
}
@Test
public void matchesExtraParentheses() {
writeFile("Thing2.java", "public @interface Thing2 {", " String value();", "}");
writeFile("A.java", "@Thing2((\"y\"))", "public class A {}");
assertCompiles(
annotationMatches(
/* shouldMatch= */ true,
new AnnotationHasArgumentWithValue("value", stringLiteral("y"))));
}
@Test
public void notMatches() {
writeFile("A.java", "@Thing(stuff=\"n\")", "public class A{}");
assertCompiles(
annotationMatches(
/* shouldMatch= */ false,
new AnnotationHasArgumentWithValue("stuff", stringLiteral("y"))));
assertCompiles(
annotationMatches(
/* shouldMatch= */ false,
new AnnotationHasArgumentWithValue("other", stringLiteral("n"))));
}
@Test
public void arrayValuedElement() {
writeFile("A.java", "@SuppressWarnings({\"unchecked\",\"fallthrough\"})", "public class A{}");
assertCompiles(
annotationMatches(
/* shouldMatch= */ true,
new AnnotationHasArgumentWithValue("value", stringLiteral("unchecked"))));
}
private Scanner annotationMatches(boolean shouldMatch, AnnotationHasArgumentWithValue toMatch) {
return new Scanner() {
@Override
public Void visitAnnotation(AnnotationTree node, VisitorState visitorState) {
assertWithMessage(node.toString())
.that(!shouldMatch ^ toMatch.matches(node, visitorState))
.isTrue();
return super.visitAnnotation(node, visitorState);
}
};
}
}
| 3,153
| 32.913978
| 98
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/matchers/method/MethodInvocationMatcherTest.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers.method;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.anyMethod;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests a basic combination of a few ordinary method matchers. */
@RunWith(JUnit4.class)
public class MethodInvocationMatcherTest {
@Test
public void invocationMatchers() {
CompilationTestHelper.newInstance(MethodInvocationChecker.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" public String toString() {",
" System.out.println(\"Stringifying\");",
" // BUG: Diagnostic contains: ",
" String s = \"5\".toString();",
" // BUG: Diagnostic contains: ",
" int result = Integer.valueOf(5).compareTo(6);",
" // BUG: Diagnostic contains: ",
" return String.valueOf(5);",
" }",
"}")
.doTest();
}
/** A {@link BugChecker} for test. */
@BugPattern(
summary = "Checker that flags the given method invocation if the matcher matches",
severity = ERROR)
public static class MethodInvocationChecker extends BugChecker
implements MethodInvocationTreeMatcher {
private final Matcher<ExpressionTree> matcher;
public MethodInvocationChecker() {
ImmutableList<MethodMatchers.MethodMatcher> matchers =
ImmutableList.of(
instanceMethod().anyClass().named("toString").withNoParameters(),
anyMethod().anyClass().named("valueOf").withParameters("int"),
staticMethod().anyClass().named("valueOf").withParameters("long"),
instanceMethod().onDescendantOf("java.lang.Number"));
this.matcher = Matchers.anyOf(matchers);
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return matcher.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH;
}
}
}
| 3,409
| 38.195402
| 93
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.fixes;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.common.base.Verify;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.LiteralTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.bugpatterns.RemoveUnusedImports;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.doctree.LinkTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.DocTreePath;
import com.sun.source.util.DocTreePathScanner;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.DCTree;
import com.sun.tools.javac.tree.JCTree;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.net.URI;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
import javax.lang.model.element.Modifier;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cushon@google.com (Liam Miller-Cushon)
*/
@RunWith(JUnit4.class)
public class SuggestedFixesTest {
/** Edit modifiers type. */
@Retention(RUNTIME)
public @interface EditModifiers {
String[] value() default {};
EditKind kind() default EditKind.ADD;
/** Kind of edit. */
enum EditKind {
ADD,
REMOVE
}
}
/** Test checker that adds or removes modifiers. */
@BugPattern(name = "EditModifiers", summary = "Edits modifiers", severity = ERROR)
public static class EditModifiersChecker extends BugChecker
implements VariableTreeMatcher, MethodTreeMatcher {
static final ImmutableMap<String, Modifier> MODIFIERS_BY_NAME = createModifiersByName();
private static ImmutableMap<String, Modifier> createModifiersByName() {
ImmutableMap.Builder<String, Modifier> builder = ImmutableMap.builder();
for (Modifier mod : Modifier.values()) {
builder.put(mod.toString(), mod);
}
return builder.buildOrThrow();
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
return editModifiers(tree, state);
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
return editModifiers(tree, state);
}
private Description editModifiers(Tree tree, VisitorState state) {
EditModifiers editModifiers =
ASTHelpers.getAnnotation(
ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class), EditModifiers.class);
SuggestedFix.Builder fix = SuggestedFix.builder();
Modifier[] mods =
Arrays.stream(editModifiers.value())
.map(v -> Verify.verifyNotNull(MODIFIERS_BY_NAME.get(v), v))
.toArray(Modifier[]::new);
switch (editModifiers.kind()) {
case ADD:
fix.merge(SuggestedFixes.addModifiers(tree, state, mods).orElse(null));
break;
case REMOVE:
fix.merge(SuggestedFixes.removeModifiers(tree, state, mods).orElse(null));
break;
default:
throw new AssertionError(editModifiers.kind());
}
return describeMatch(tree, fix.build());
}
}
@Test
public void addAtBeginningOfLine() {
BugCheckerRefactoringTestHelper.newInstance(EditModifiersChecker.class, getClass())
.addInputLines(
"in/Test.java",
"import javax.annotation.Nullable;",
String.format("import %s;", EditModifiers.class.getCanonicalName()),
"@EditModifiers(value=\"final\", kind=EditModifiers.EditKind.ADD)",
"class Test {",
" @Nullable",
" int foo() {",
" return 10;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import javax.annotation.Nullable;",
String.format("import %s;", EditModifiers.class.getCanonicalName()),
"@EditModifiers(value=\"final\", kind=EditModifiers.EditKind.ADD)",
"class Test {",
" @Nullable",
" final int foo() {",
" return 10;",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void addModifiers() {
CompilationTestHelper.newInstance(EditModifiersChecker.class, getClass())
.addSourceLines(
"Test.java",
String.format("import %s;", EditModifiers.class.getCanonicalName()),
"import javax.annotation.Nullable;",
"@EditModifiers(value=\"final\", kind=EditModifiers.EditKind.ADD)",
"class Test {",
" // BUG: Diagnostic contains: final Object one",
" Object one;",
" // BUG: Diagnostic contains: @Nullable final Object two",
" @Nullable Object two;",
" // BUG: Diagnostic contains: @Nullable public final Object three",
" @Nullable public Object three;",
" // BUG: Diagnostic contains: public final Object four",
" public Object four;",
" // BUG: Diagnostic contains: public final @Nullable Object five",
" public @Nullable Object five;",
"}")
.doTest();
}
@Test
public void addModifiersComment() {
CompilationTestHelper.newInstance(EditModifiersChecker.class, getClass())
.addSourceLines(
"Test.java",
String.format("import %s;", EditModifiers.class.getCanonicalName()),
"import javax.annotation.Nullable;",
"@EditModifiers(value=\"final\", kind=EditModifiers.EditKind.ADD)",
"class Test {",
" // BUG: Diagnostic contains:"
+ " private @Deprecated /*comment*/ final volatile Object one;",
" private @Deprecated /*comment*/ volatile Object one;",
" // BUG: Diagnostic contains:"
+ " private @Deprecated /*comment*/ static final Object two = null;",
" private @Deprecated /*comment*/ static Object two = null;",
"}")
.doTest();
}
@Test
public void addModifiersFirst() {
CompilationTestHelper.newInstance(EditModifiersChecker.class, getClass())
.addSourceLines(
"Test.java",
String.format("import %s;", EditModifiers.class.getCanonicalName()),
"import javax.annotation.Nullable;",
"@EditModifiers(value=\"public\", kind=EditModifiers.EditKind.ADD)",
"class Test {",
" // BUG: Diagnostic contains: public static final transient Object one",
" static final transient Object one = null;",
"}")
.doTest();
}
@Test
public void removeModifiers() {
CompilationTestHelper.newInstance(EditModifiersChecker.class, getClass())
.addSourceLines(
"Test.java",
String.format("import %s;", EditModifiers.class.getCanonicalName()),
"import javax.annotation.Nullable;",
"@EditModifiers(value=\"final\", kind=EditModifiers.EditKind.REMOVE)",
"class Test {",
" // BUG: Diagnostic contains: Object one",
" final Object one = null;",
" // BUG: Diagnostic contains: @Nullable Object two",
" @Nullable final Object two = null;",
" // BUG: Diagnostic contains: @Nullable public Object three",
" @Nullable public final Object three = null;",
" // BUG: Diagnostic contains: public Object four",
" public final Object four = null;",
"}")
.doTest();
}
@Test
public void removeMultipleModifiers() {
CompilationTestHelper.newInstance(EditModifiersChecker.class, getClass())
.addSourceLines(
"Test.java",
String.format("import %s;", EditModifiers.class.getCanonicalName()),
"import javax.annotation.Nullable;",
"@EditModifiers(value={\"final\", \"static\"}, kind=EditModifiers.EditKind.REMOVE)",
"class Test {",
" // BUG: Diagnostic contains: private Object one = null;",
" private static final Object one = null;",
"}")
.doTest();
}
/** Test checker that casts returned expression. */
@BugPattern(severity = ERROR, summary = "Adds casts to returned expressions")
public static class CastReturn extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
if (tree.getExpression() == null) {
return Description.NO_MATCH;
}
Type type =
ASTHelpers.getSymbol(ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class))
.getReturnType();
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
String qualifiedTargetType = SuggestedFixes.qualifyType(state, fixBuilder, type.tsym);
fixBuilder.prefixWith(tree.getExpression(), String.format("(%s) ", qualifiedTargetType));
return describeMatch(tree, fixBuilder.build());
}
}
/** Test checker that casts returned expression. */
@BugPattern(name = "CastReturn", severity = ERROR, summary = "Adds casts to returned expressions")
public static class CastReturnFullType extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
if (tree.getExpression() == null) {
return Description.NO_MATCH;
}
Type type =
ASTHelpers.getSymbol(ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class))
.getReturnType();
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
String qualifiedTargetType = SuggestedFixes.qualifyType(state, fixBuilder, type);
fixBuilder.prefixWith(tree.getExpression(), String.format("(%s) ", qualifiedTargetType));
return describeMatch(tree, fixBuilder.build());
}
}
@Test
public void qualifiedName_object() {
CompilationTestHelper.newInstance(CastReturn.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" Object f() {",
" // BUG: Diagnostic contains: return (Object) null;",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void qualifiedName_imported() {
CompilationTestHelper.newInstance(CastReturn.class, getClass())
.addSourceLines(
"Test.java",
"import java.util.Map.Entry;",
"class Test {",
" java.util.Map.Entry<String, Integer> f() {",
" // BUG: Diagnostic contains: return (Entry) null;",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void qualifiedName_notImported() {
CompilationTestHelper.newInstance(CastReturn.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" java.util.Map.Entry<String, Integer> f() {",
" // BUG: Diagnostic contains: return (Map.Entry) null;",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void qualifiedName_typeVariable() {
CompilationTestHelper.newInstance(CastReturn.class, getClass())
.addSourceLines(
"Test.java",
"class Test<T> {",
" T f() {",
" // BUG: Diagnostic contains: return (T) null;",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void fullQualifiedName_object() {
CompilationTestHelper.newInstance(CastReturnFullType.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" Object f() {",
" // BUG: Diagnostic contains: return (Object) null;",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void fullQualifiedName_imported() {
CompilationTestHelper.newInstance(CastReturnFullType.class, getClass())
.addSourceLines(
"Test.java",
"import java.util.Map.Entry;",
"class Test {",
" java.util.Map.Entry<String, Integer> f() {",
" // BUG: Diagnostic contains: return (Entry<String,Integer>) null;",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void fullQualifiedName_notImported() {
CompilationTestHelper.newInstance(CastReturnFullType.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" java.util.Map.Entry<String, Integer> f() {",
" // BUG: Diagnostic contains: return (Map.Entry<String,Integer>) null;",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void fullQualifiedName_typeVariable() {
CompilationTestHelper.newInstance(CastReturnFullType.class, getClass())
.addSourceLines(
"Test.java",
"class Test<T> {",
" T f() {",
" // BUG: Diagnostic contains: return (T) null;",
" return null;",
" }",
"}")
.doTest();
}
/** A test check that adds an annotation to all return types. */
@BugPattern(summary = "Add an annotation", severity = ERROR)
public static class AddAnnotation extends BugChecker implements BugChecker.MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
Type type = state.getTypeFromString("some.pkg.SomeAnnotation");
SuggestedFix.Builder builder = SuggestedFix.builder();
String qualifiedName = SuggestedFixes.qualifyType(state, builder, type);
return describeMatch(
tree.getReturnType(),
builder.prefixWith(tree.getReturnType(), "@" + qualifiedName + " ").build());
}
private static BugCheckerRefactoringTestHelper testHelper(
Class<? extends SuggestedFixesTest> clazz) {
return BugCheckerRefactoringTestHelper.newInstance(AddAnnotation.class, clazz)
.addInputLines(
"in/some/pkg/SomeAnnotation.java",
"package some.pkg;",
"public @interface SomeAnnotation {}")
.expectUnchanged();
}
}
@Test
public void qualifyType_alreadyImported() {
AddAnnotation.testHelper(getClass())
.addInputLines(
"in/AddAnnotation.java",
"import some.pkg.SomeAnnotation;",
"class AddAnnotation {",
" @SomeAnnotation Void nullable = null;",
" Void foo() { return null; }",
"}")
.addOutputLines(
"out/AddAnnotation.java",
"import some.pkg.SomeAnnotation;",
"class AddAnnotation {",
" @SomeAnnotation Void nullable = null;",
" @SomeAnnotation Void foo() { return null; }",
"}")
.doTest();
}
@Test
public void qualifyType_importType() {
AddAnnotation.testHelper(getClass())
.addInputLines(
"in/AddAnnotation.java", "class AddAnnotation {", " Void foo() { return null; }", "}")
.addOutputLines(
"out/AddAnnotation.java",
"import some.pkg.SomeAnnotation;",
"class AddAnnotation {",
" @SomeAnnotation Void foo() { return null; }",
"}")
.doTest();
}
@Test
public void qualifyType_someOtherNullable() {
AddAnnotation.testHelper(getClass())
.addInputLines("in/SomeAnnotation.java", "@interface SomeAnnotation {}")
.expectUnchanged()
.addInputLines(
"in/AddAnnotation.java",
"class AddAnnotation {",
" @SomeAnnotation Void foo() { return null; }",
"}")
.addOutputLines(
"out/AddAnnotation.java",
"class AddAnnotation {",
" @SomeAnnotation @some.pkg.SomeAnnotation Void foo() { return null; }",
"}")
.doTest();
}
@Test
public void qualifyType_nestedNullable() {
AddAnnotation.testHelper(getClass())
.addInputLines(
"in/AddAnnotation.java",
"class AddAnnotation {",
" Void foo() { return null; }",
" @interface SomeAnnotation {}",
"}")
.addOutputLines(
"out/AddAnnotation.java",
"class AddAnnotation {",
" @some.pkg.SomeAnnotation Void foo() { return null; }",
" @interface SomeAnnotation {}",
"}")
.doTest();
}
@Test
public void qualifyType_deeplyNestedNullable() {
AddAnnotation.testHelper(getClass())
.addInputLines(
"in/AddAnnotation.java",
"class AddAnnotation {",
" Void foo() { return null; }",
" static class Nested {",
" Void bar() { return null; }",
" @interface SomeAnnotation {}",
" }",
"}")
.addOutputLines(
"out/AddAnnotation.java",
"import some.pkg.SomeAnnotation;",
"class AddAnnotation {",
" @SomeAnnotation Void foo() { return null; }",
" static class Nested {",
" @some.pkg.SomeAnnotation Void bar() { return null; }",
" @interface SomeAnnotation {}",
" }",
"}")
.doTest();
}
@Test
public void qualifyType_someOtherNullableSomeOtherPackage() {
AddAnnotation.testHelper(getClass())
.addInputLines(
"in/SomeAnnotation.java", "package foo.bar;", "public @interface SomeAnnotation {}")
.expectUnchanged()
.addInputLines(
"in/AddAnnotation.java",
"import foo.bar.SomeAnnotation;",
"class AddAnnotation {",
" @SomeAnnotation Void foo() { return null; }",
"}")
.addOutputLines(
"out/AddAnnotation.java",
"import foo.bar.SomeAnnotation;",
"class AddAnnotation {",
" @SomeAnnotation @some.pkg.SomeAnnotation Void foo() { return null; }",
"}")
.doTest();
}
@Test
public void qualifyType_typeVariable() {
AddAnnotation.testHelper(getClass())
.addInputLines(
"in/AddAnnotation.java",
"class AddAnnotation {",
" <SomeAnnotation> Void foo() { return null; }",
"}")
.addOutputLines(
"out/AddAnnotation.java",
"class AddAnnotation {",
" <SomeAnnotation> @some.pkg.SomeAnnotation Void foo() { return null; }",
"}")
.doTest();
}
/** A test check that replaces all methods' return types with a given type. */
@BugPattern(summary = "Change the method return type", severity = ERROR)
public static class ReplaceReturnType extends BugChecker implements BugChecker.MethodTreeMatcher {
private final String newReturnType;
public ReplaceReturnType(String newReturnType) {
this.newReturnType = newReturnType;
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
Type type = state.getTypeFromString(newReturnType);
SuggestedFix.Builder builder = SuggestedFix.builder();
String qualifiedName = SuggestedFixes.qualifyType(state, builder, type);
return describeMatch(
tree.getReturnType(), builder.replace(tree.getReturnType(), qualifiedName).build());
}
}
@Test
public void qualifyType_nestedType() {
qualifyNestedType(new ReplaceReturnType("pkg.Outer.Inner"));
}
@Test
public void qualifyType_deeplyNestedType() {
qualifyDeeplyNestedType(new ReplaceReturnType("pkg.Outer.Inner.Innermost"));
}
/** A test check that replaces all methods' return types with a given type. */
@BugPattern(summary = "Change the method return type", severity = ERROR)
public static class ReplaceReturnTypeString extends BugChecker
implements BugChecker.MethodTreeMatcher {
private final String newReturnType;
public ReplaceReturnTypeString(String newReturnType) {
this.newReturnType = newReturnType;
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
SuggestedFix.Builder builder = SuggestedFix.builder();
String qualifiedName = SuggestedFixes.qualifyType(state, builder, newReturnType);
return describeMatch(
tree.getReturnType(), builder.replace(tree.getReturnType(), qualifiedName).build());
}
}
@Test
public void qualifyTypeString_nestedType() {
qualifyNestedType(new ReplaceReturnTypeString("pkg.Outer.Inner"));
}
@Test
public void qualifyTypeString_deeplyNestedType() {
qualifyDeeplyNestedType(new ReplaceReturnTypeString("pkg.Outer.Inner.Innermost"));
}
@Test
public void qualifiedName_canImportInnerClass() {
BugCheckerRefactoringTestHelper.newInstance(new ReplaceReturnTypeString("foo.A.B"), getClass())
.addInputLines(
"foo/A.java", //
"package foo;",
"public class A {",
" public static class B {}",
"}")
.expectUnchanged()
.addInputLines(
"bar/A.java", //
"package bar;",
"public class A extends foo.A {}")
.expectUnchanged()
.addInputLines(
"bar/Test.java", //
"package bar;",
"public interface Test {",
" A.B foo();",
"}")
.addOutputLines(
"bar/Test.java", //
"package bar;",
"import foo.A.B;",
"public interface Test {",
" B foo();",
"}")
.doTest();
}
@Test
public void qualifiedName_outerAndInnerClassClash_fullyQualifies() {
BugCheckerRefactoringTestHelper.newInstance(new ReplaceReturnTypeString("foo.A.B"), getClass())
.addInputLines(
"foo/A.java", //
"package foo;",
"public class A {",
" public static class B {}",
"}")
.expectUnchanged()
.addInputLines(
"bar/A.java", //
"package bar;",
"public class A extends foo.A {}")
.expectUnchanged()
.addInputLines(
"bar/B.java", //
"package bar;",
"public class B {}")
.expectUnchanged()
.addInputLines(
"bar/Test.java", //
"package bar;",
"public interface Test {",
" A.B foo();",
"}")
.addOutputLines(
"bar/Test.java", //
"package bar;",
"public interface Test {",
" foo.A.B foo();",
"}")
.doTest();
}
@Test
public void qualifiedName_noPackageName_noImportNeeded() {
BugCheckerRefactoringTestHelper.newInstance(new ReplaceReturnTypeString("A.B"), getClass())
.addInputLines(
"A.java", //
"public interface A {",
" public static class B {}",
" B foo();",
" B bar();",
"}")
.expectUnchanged()
.addInputLines(
"Test.java", //
"public interface Test {",
" A.B foo();",
"}")
.expectUnchanged()
.doTest();
}
private void qualifyDeeplyNestedType(BugChecker bugChecker) {
BugCheckerRefactoringTestHelper.newInstance(bugChecker, getClass())
.addInputLines(
"in/pkg/Outer.java",
"package pkg;",
"public class Outer {",
" public class Inner {",
" public class Innermost {}",
" }",
"}")
.expectUnchanged()
.addInputLines(
"in/ReplaceReturnType.java",
"class ReplaceReturnType {",
" Void foo() { return null; }",
"}")
.addOutputLines(
"out/ReplaceReturnType.java",
"import pkg.Outer;",
"class ReplaceReturnType {",
" Outer.Inner.Innermost foo() { return null; }",
"}")
.doTest();
}
private void qualifyNestedType(BugChecker bugChecker) {
BugCheckerRefactoringTestHelper.newInstance(bugChecker, getClass())
.addInputLines(
"in/pkg/Outer.java",
"package pkg;",
"public class Outer {",
" public class Inner {}",
"}")
.expectUnchanged()
.addInputLines(
"in/ReplaceReturnType.java",
"class ReplaceReturnType {",
" Void foo() { return null; }",
"}")
.addOutputLines(
"out/ReplaceReturnType.java",
"import pkg.Outer;",
"class ReplaceReturnType {",
" Outer.Inner foo() { return null; }",
"}")
.doTest();
}
/** A test check that replaces all checkNotNulls with verifyNotNull. */
@BugPattern(summary = "Replaces checkNotNull with verifyNotNull.", severity = ERROR)
public static class ReplaceMethodInvocations extends BugChecker
implements BugChecker.MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> CHECK_NOT_NULL =
staticMethod().onClass("com.google.common.base.Preconditions").named("checkNotNull");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!CHECK_NOT_NULL.matches(tree, state)) {
return NO_MATCH;
}
SuggestedFix.Builder builder = SuggestedFix.builder();
String qualifiedName =
SuggestedFixes.qualifyStaticImport(
"com.google.common.base.Verify.verifyNotNull", builder, state);
return describeMatch(
tree,
builder
.replace(
tree,
String.format(
"%s(%s)", qualifiedName, state.getSourceForNode(tree.getArguments().get(0))))
.build());
}
}
@Test
public void qualifyStaticImport_addsStaticImportAndUsesUnqualifiedName() {
BugCheckerRefactoringTestHelper.newInstance(ReplaceMethodInvocations.class, getClass())
.addInputLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkNotNull;",
"class Test {",
" void test() {",
" checkNotNull(1);",
" }",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkNotNull;",
"import static com.google.common.base.Verify.verifyNotNull;",
"class Test {",
" void test() {",
" verifyNotNull(1);",
" }",
"}")
.doTest();
}
@Test
public void qualifyStaticImport_whenAlreadyImported_usesUnqualifiedName() {
BugCheckerRefactoringTestHelper.newInstance(ReplaceMethodInvocations.class, getClass())
.addInputLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkNotNull;",
"import static com.google.common.base.Verify.verifyNotNull;",
"class Test {",
" void test() {",
" verifyNotNull(2);",
" checkNotNull(1);",
" }",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkNotNull;",
"import static com.google.common.base.Verify.verifyNotNull;",
"class Test {",
" void test() {",
" verifyNotNull(2);",
" verifyNotNull(1);",
" }",
"}")
.doTest();
}
@Test
public void qualifyStaticImport_whenIdentifierNamesClash_usesQualifiedName() {
BugCheckerRefactoringTestHelper.newInstance(ReplaceMethodInvocations.class, getClass())
.addInputLines(
"pkg/Lib.java",
"package pkg;",
"public class Lib {",
" public static void verifyNotNull(int a) {}",
" }")
.expectUnchanged()
.addInputLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkNotNull;",
"import static pkg.Lib.verifyNotNull;",
"class Test {",
" void test() {",
" verifyNotNull(2);",
" checkNotNull(1);",
" }",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkNotNull;",
"import static pkg.Lib.verifyNotNull;",
"import com.google.common.base.Verify;",
"class Test {",
" void test() {",
" verifyNotNull(2);",
" Verify.verifyNotNull(1);",
" }",
"}")
.doTest();
}
@Test
public void qualifyStaticImport_whenMethodNamesClash_usesQualifiedName() {
BugCheckerRefactoringTestHelper.newInstance(ReplaceMethodInvocations.class, getClass())
.addInputLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkNotNull;",
"class Test {",
" void test() {",
" checkNotNull(1);",
" }",
" void verifyNotNull(int a) {}",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.base.Preconditions.checkNotNull;",
"import com.google.common.base.Verify;",
"class Test {",
" void test() {",
" Verify.verifyNotNull(1);",
" }",
" void verifyNotNull(int a) {}",
"}")
.doTest();
}
/** A test check that qualifies javadoc link. */
@BugPattern(summary = "all javadoc links should be qualified", severity = ERROR)
public static class JavadocQualifier extends BugChecker implements BugChecker.ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
DCTree.DCDocComment comment =
((JCTree.JCCompilationUnit) state.getPath().getCompilationUnit())
.docComments.getCommentTree((JCTree) tree);
if (comment == null) {
return Description.NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
new DocTreePathScanner<Void, Void>() {
@Override
public Void visitLink(LinkTree node, Void unused) {
SuggestedFixes.qualifyDocReference(
fix, new DocTreePath(getCurrentPath(), node.getReference()), state);
return null;
}
}.scan(new DocTreePath(state.getPath(), comment), null);
if (fix.isEmpty()) {
return Description.NO_MATCH;
}
return describeMatch(tree, fix.build());
}
}
@Test
public void qualifyJavadocTest() {
BugCheckerRefactoringTestHelper.newInstance(JavadocQualifier.class, getClass())
.addInputLines(
"in/Test.java", //
"import java.util.List;",
"import java.util.Map;",
"/** foo {@link List} bar {@link Map#containsKey(Object)} baz {@link #foo} */",
"class Test {",
" void foo() {}",
"}")
.addOutputLines(
"out/Test.java", //
"import java.util.List;",
"import java.util.Map;",
"/** foo {@link java.util.List} bar {@link java.util.Map#containsKey(Object)} baz"
+ " {@link Test#foo} */",
"class Test {",
" void foo() {}",
"}")
.doTest(TEXT_MATCH);
}
/** A {@link BugChecker} for testing. */
@BugPattern(summary = "", severity = ERROR)
public static final class SuppressMe extends BugChecker
implements LiteralTreeMatcher, VariableTreeMatcher {
@Override
public Description matchLiteral(LiteralTree tree, VisitorState state) {
if (tree.getValue().equals(42)) {
Fix potentialFix = SuggestedFixes.addSuppressWarnings(state, "SuppressMe");
if (potentialFix == null) {
return describeMatch(tree);
}
return describeMatch(tree, potentialFix);
}
return Description.NO_MATCH;
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
// If it's a lambda param, then flag.
LambdaExpressionTree enclosingMethod =
ASTHelpers.findEnclosingNode(state.getPath(), LambdaExpressionTree.class);
if (enclosingMethod != null && enclosingMethod.getParameters().contains(tree)) {
return describeMatch(tree, SuggestedFixes.addSuppressWarnings(state, "AParameter"));
}
return Description.NO_MATCH;
}
}
@Test
@org.junit.Ignore("There appears to be an issue parsing lambda comments")
public void suppressWarningsFix() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(SuppressMe.class, getClass());
refactorTestHelper
.addInputLines(
"in/Test.java",
"public class Test {",
" static final int BEST_NUMBER = 42;",
" static { int i = 42; }",
" @SuppressWarnings(\"one\")",
" public void doIt() {",
" System.out.println(\"\" + 42);",
" new Runnable() {",
" {System.out.println(\"\" + 42);}",
" @Override public void run() {}",
" };",
" }",
" public void bar() {",
" java.util.function.Predicate<String> p = x -> x.isEmpty();",
" java.util.function.Predicate<Integer> isEven = ",
" (Integer x) -> x % 2 == 0;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" @SuppressWarnings(\"SuppressMe\") static final int BEST_NUMBER = 42;",
" static { @SuppressWarnings(\"SuppressMe\") int i = 42; }",
" @SuppressWarnings({\"one\", \"SuppressMe\"})",
" public void doIt() {",
" System.out.println(\"\" + 42);",
" new Runnable() {",
" {System.out.println(\"\" + 42);}",
" @Override public void run() {}",
" };",
" }",
" public void bar() {",
" @SuppressWarnings(\"AParameter\")",
" java.util.function.Predicate<String> p = x -> x.isEmpty();",
" java.util.function.Predicate<Integer> isEven = ",
" (@SuppressWarnings(\"AParameter\") Integer x) -> x % 2 == 0;",
" }",
"}")
.doTest();
}
/** A {@link BugChecker} for testing. */
@BugPattern(summary = "", severity = ERROR)
public static final class SuppressMeWithComment extends BugChecker implements LiteralTreeMatcher {
private final String lineComment;
SuppressMeWithComment(String lineComment) {
this.lineComment = lineComment;
}
@Override
public Description matchLiteral(LiteralTree tree, VisitorState state) {
Fix potentialFix = SuggestedFixes.addSuppressWarnings(state, "SuppressMe", lineComment);
return describeMatch(tree, potentialFix);
}
}
@Test
public void suppressWarningsWithCommentFix() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(
new SuppressMeWithComment("b/XXXX: fix me!"), getClass());
refactorTestHelper
.addInputLines(
"in/Test.java",
"public class Test {",
" int BEST_NUMBER = 42;",
" @SuppressWarnings(\"x\") int BEST = 42;",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" // b/XXXX: fix me!",
" @SuppressWarnings(\"SuppressMe\") int BEST_NUMBER = 42;",
" // b/XXXX: fix me!",
" @SuppressWarnings({\"x\", \"SuppressMe\"}) int BEST = 42;",
"}")
.doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}
@Test
public void suppressWarningsWithCommentFix_existingComment() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(
new SuppressMeWithComment("b/XXXX: fix me!"), getClass());
refactorTestHelper
.addInputLines(
"in/Test.java",
"public class Test {",
" // This comment was here already.",
" int BEST_NUMBER = 42;",
"",
" // As was this one.",
" @SuppressWarnings(\"x\") int BEST = 42;",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" // This comment was here already.",
" // b/XXXX: fix me!",
" @SuppressWarnings(\"SuppressMe\") int BEST_NUMBER = 42;",
"",
" // As was this one.",
" // b/XXXX: fix me!",
" @SuppressWarnings({\"x\", \"SuppressMe\"}) int BEST = 42;",
"}")
.doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}
@Test
public void suppressWarningsWithCommentFix_commentHasToBeLineWrapped() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(
new SuppressMeWithComment(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, "
+ "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."),
getClass());
refactorTestHelper
.addInputLines("in/Test.java", "public class Test {", " int BEST = 42;", "}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" // Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor "
+ "incididunt ut",
" // labore et dolore magna aliqua.",
" @SuppressWarnings(\"SuppressMe\") int BEST = 42;",
"}")
.doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
}
/** A {@link BugChecker} for testing. */
@BugPattern(summary = "", severity = ERROR)
public static final class RemoveSuppressFromMe extends BugChecker implements LiteralTreeMatcher {
@Override
public Description matchLiteral(LiteralTree tree, VisitorState state) {
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
SuggestedFixes.removeSuppressWarnings(fixBuilder, state, "RemoveMe");
return describeMatch(tree, fixBuilder.build());
}
}
@Test
public void removeSuppressWarnings_singleWarning_removesEntireAnnotation() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(RemoveSuppressFromMe.class, getClass());
refactorTestHelper
.addInputLines(
"in/Test.java",
"public class Test {",
" @SuppressWarnings(\"RemoveMe\") int BEST = 42;",
"}")
.addOutputLines("out/Test.java", "public class Test {", " int BEST = 42;", "}")
.doTest(TestMode.AST_MATCH);
}
@Test
public void removeSuppressWarnings_twoWarning_removesWarningAndNewArray() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(RemoveSuppressFromMe.class, getClass());
refactorTestHelper
.addInputLines(
"in/Test.java",
"public class Test {",
" @SuppressWarnings({\"RemoveMe\", \"KeepMe\"}) int BEST = 42;",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" @SuppressWarnings(\"KeepMe\") int BEST = 42;",
"}")
.doTest(TestMode.AST_MATCH);
}
@Test
public void removeSuppressWarnings_threeWarning_removesOnlyOneAndKeepsArray() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(RemoveSuppressFromMe.class, getClass());
refactorTestHelper
.addInputLines(
"in/Test.java",
"public class Test {",
" @SuppressWarnings({\"RemoveMe\", \"KeepMe1\", \"KeepMe2\"}) int BEST = 42;",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" @SuppressWarnings({\"KeepMe1\", \"KeepMe2\"}) int BEST = 42;",
"}")
.doTest(TestMode.AST_MATCH);
}
@Test
public void removeSuppressWarnings_oneWarningInArray_removesWholeAnnotation() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(RemoveSuppressFromMe.class, getClass());
refactorTestHelper
.addInputLines(
"in/Test.java",
"public class Test {",
" @SuppressWarnings({\"RemoveMe\"}) int BEST = 42;",
"}")
.addOutputLines("out/Test.java", "public class Test {", " int BEST = 42;", "}")
.doTest(TestMode.AST_MATCH);
}
@Test
public void removeSuppressWarnings_withValueInit_retainsValue() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(RemoveSuppressFromMe.class, getClass());
refactorTestHelper
.addInputLines(
"in/Test.java",
"public class Test {",
" @SuppressWarnings(value={\"RemoveMe\", \"KeepMe\"}) int BEST = 42;",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" @SuppressWarnings(value=\"KeepMe\") int BEST = 42;",
"}")
.doTest(TestMode.AST_MATCH);
}
/** A {@link BugChecker} for testing. */
@BugPattern(name = "UpdateDoNotCallArgument", summary = "", severity = ERROR)
public static final class UpdateDoNotCallArgumentChecker extends BugChecker
implements AnnotationTreeMatcher {
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
SuggestedFix.Builder fixBuilder =
SuggestedFixes.updateAnnotationArgumentValues(
tree, state, "value", ImmutableList.of("\"Danger\""));
return describeMatch(tree, fixBuilder.build());
}
}
@Test
public void updateAnnotationArgumentValues_noArguments() {
BugCheckerRefactoringTestHelper refactorTestHelper =
BugCheckerRefactoringTestHelper.newInstance(
UpdateDoNotCallArgumentChecker.class, getClass());
refactorTestHelper
.addInputLines(
"in/Test.java",
"import com.google.errorprone.annotations.DoNotCall;",
"public class Test {",
" @DoNotCall void m() {}",
"}")
.addOutputLines(
"out/Test.java",
"import com.google.errorprone.annotations.DoNotCall;",
"public class Test {",
" @DoNotCall(\"Danger\") void m() {}",
"}")
.doTest(TestMode.AST_MATCH);
}
/** A test bugchecker that deletes any field whose removal doesn't break the compilation. */
@BugPattern(summary = "", severity = ERROR)
public static class CompilesWithFixChecker extends BugChecker implements VariableTreeMatcher {
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
Fix fix = SuggestedFix.delete(tree);
return SuggestedFixes.compilesWithFix(fix, state)
? describeMatch(tree, fix)
: Description.NO_MATCH;
}
}
@Test
public void compilesWithFixTest() {
BugCheckerRefactoringTestHelper.newInstance(CompilesWithFixChecker.class, getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" void f() {",
" int x = 0;",
" int y = 1;",
" System.err.println(y);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() {",
" int y = 1;",
" System.err.println(y);",
" }",
"}")
.doTest();
}
@Test
public void compilesWithFix_releaseFlag() {
BugCheckerRefactoringTestHelper.newInstance(CompilesWithFixChecker.class, getClass())
.setArgs("--release", "9")
.addInputLines(
"in/Test.java",
"class Test {",
" void f() {",
" int x = 0;",
" int y = 1;",
" System.err.println(y);",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void f() {",
" int y = 1;",
" System.err.println(y);",
" }",
"}")
.doTest();
}
/** A test bugchecker that deletes an exception from throws. */
@BugPattern(name = "RemovesExceptionChecker", summary = "", severity = ERROR)
public static class RemovesExceptionsChecker extends BugChecker implements MethodTreeMatcher {
private final int index;
RemovesExceptionsChecker(int index) {
this.index = index;
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (tree.getThrows().isEmpty() || tree.getThrows().size() <= index) {
return NO_MATCH;
}
ExpressionTree expressionTreeToRemove = tree.getThrows().get(index);
return describeMatch(
expressionTreeToRemove,
SuggestedFixes.deleteExceptions(tree, state, ImmutableList.of(expressionTreeToRemove)));
}
}
@Test
public void deleteExceptionsRemoveFirstCheckerTest() {
BugCheckerRefactoringTestHelper.newInstance(new RemovesExceptionsChecker(0), getClass())
.addInputLines(
"in/Test.java",
"import java.io.IOException;",
"class Test {",
" void e() {",
" }",
" void f() throws Exception {",
" }",
" void g() throws RuntimeException, Exception {",
" }",
" void h() throws RuntimeException, Exception, IOException {",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.io.IOException;",
"class Test {",
" void e() {",
" }",
" void f() {",
" }",
" void g() throws Exception {",
" }",
" void h() throws Exception, IOException {",
" }",
"}")
.doTest();
}
@Test
public void deleteExceptionsRemoveSecondCheckerTest() {
BugCheckerRefactoringTestHelper.newInstance(new RemovesExceptionsChecker(1), getClass())
.addInputLines(
"in/Test.java",
"import java.io.IOException;",
"class Test {",
" void e() {",
" }",
" void f() throws Exception {",
" }",
" void g() throws RuntimeException, Exception {",
" }",
" void h() throws RuntimeException, Exception, IOException {",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import java.io.IOException;",
"class Test {",
" void e() {",
" }",
" void f() throws Exception {",
" }",
" void g() throws RuntimeException {",
" }",
" void h() throws RuntimeException, IOException {",
" }",
"}")
.doTest();
}
@Test
public void unusedImportInPackageInfo() {
CompilationTestHelper.newInstance(RemoveUnusedImports.class, getClass())
.addSourceLines(
"in/com/example/package-info.java",
"package com.example;",
"// BUG: Diagnostic contains: Did you mean to remove this line?",
"import java.util.Map;")
.doTest();
}
/** Test checker that renames variables. */
@BugPattern(summary = "", severity = ERROR)
public static class RenamesVariableChecker extends BugChecker implements VariableTreeMatcher {
private final String toReplace;
private final String replacement;
private final Class<?> typeClass;
RenamesVariableChecker(String toReplace, String replacement, Class<?> typeClass) {
this.toReplace = toReplace;
this.replacement = replacement;
this.typeClass = typeClass;
}
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (!tree.getName().contentEquals(toReplace) || !isSameType(typeClass).matches(tree, state)) {
return Description.NO_MATCH;
}
return describeMatch(tree, SuggestedFixes.renameVariable(tree, replacement, state));
}
}
@Test
public void renameVariable_renamesLocalVariable_withNestedScope() {
BugCheckerRefactoringTestHelper.newInstance(
new RenamesVariableChecker("replace", "renamed", Integer.class), getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" void m() {",
" Integer replace = 0;",
" Integer b = replace;",
" if (true) {",
" Integer c = replace;",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void m() {",
" Integer renamed = 0;",
" Integer b = renamed;",
" if (true) {",
" Integer c = renamed;",
" }",
" }",
"}")
.doTest();
}
@Test
public void renameVariable_ignoresMatchingNames_whenNotInScopeOfReplacement() {
BugCheckerRefactoringTestHelper.newInstance(
new RenamesVariableChecker("replace", "renamed", Integer.class), getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" void m() {",
" if (true) {",
" Integer replace = 0;",
" Integer c = replace;",
" }",
" Object replace = null;",
" Object c = replace;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void m() {",
" if (true) {",
" Integer renamed = 0;",
" Integer c = renamed;",
" }",
" Object replace = null;",
" Object c = replace;",
" }",
"}")
.doTest();
}
@Test
public void renameVariable_renamesMethodParameter() {
BugCheckerRefactoringTestHelper.newInstance(
new RenamesVariableChecker("replace", "renamed", Integer.class), getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" void m(Integer replace) {",
" Integer b = replace;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void m(Integer renamed) {",
" Integer b = renamed;",
" }",
"}")
.doTest();
}
@Test
public void renameVariable_renamesTryWithResourcesParameter() {
BugCheckerRefactoringTestHelper.newInstance(
new RenamesVariableChecker("replace", "renamed", AutoCloseable.class), getClass())
.addInputLines(
"in/Test.java",
"abstract class Test {",
" abstract AutoCloseable open();",
" void m() {",
" try (AutoCloseable replace = open()) {",
" Object o = replace;",
" } catch (Exception e) {",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"abstract class Test {",
" abstract AutoCloseable open();",
" void m() {",
" try (AutoCloseable renamed = open()) {",
" Object o = renamed;",
" } catch (Exception e) {",
" }",
" }",
"}")
.doTest();
}
@Test
public void renameVariable_renamesLambdaParameter_explicitlyTyped() {
BugCheckerRefactoringTestHelper.newInstance(
new RenamesVariableChecker("replace", "renamed", Integer.class), getClass())
.addInputLines(
"in/Test.java",
"import java.util.function.Function;",
"class Test {",
" Function<Integer, Integer> f = (Integer replace) -> replace;",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.function.Function;",
"class Test {",
" Function<Integer, Integer> f = (Integer renamed) -> renamed;",
"}")
.doTest();
}
@Test
public void renameVariable_renamesLambdaParameter_notExplicitlyTyped() {
BugCheckerRefactoringTestHelper.newInstance(
new RenamesVariableChecker("replace", "renamed", Integer.class), getClass())
.addInputLines(
"in/Test.java",
"import java.util.function.Function;",
"class Test {",
" Function<Integer, Integer> f = (replace) -> replace;",
"}")
.addOutputLines(
"out/Test.java",
"import java.util.function.Function;",
"class Test {",
" Function<Integer, Integer> f = (renamed) -> renamed;",
"}")
.doTest();
}
@Test
public void renameVariable_renamesCatchParameter() {
BugCheckerRefactoringTestHelper.newInstance(
new RenamesVariableChecker("replace", "renamed", Throwable.class), getClass())
.addInputLines(
"in/Test.java",
"class Test {",
" void m() {",
" try {",
" } catch (Throwable replace) {",
" replace.toString();",
" }",
" }",
"}")
.addOutputLines(
"out/Test.java",
"class Test {",
" void m() {",
" try {",
" } catch (Throwable renamed) {",
" renamed.toString();",
" }",
" }",
"}")
.doTest();
}
/** Test checker that removes and adds modifiers in the same fix. */
@BugPattern(summary = "", severity = ERROR)
public static class RemoveAddModifier extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return describeMatch(
tree,
SuggestedFix.builder()
.merge(SuggestedFixes.removeModifiers(tree, state, Modifier.PUBLIC).orElse(null))
.merge(SuggestedFixes.addModifiers(tree, state, Modifier.ABSTRACT).orElse(null))
.build());
}
}
@Test
public void removeAddModifier_rangesCompatible() {
BugCheckerRefactoringTestHelper.newInstance(RemoveAddModifier.class, getClass())
.addInputLines("in/Test.java", "public class Test {}")
.addOutputLines("out/Test.java", "abstract class Test {}")
.doTest();
}
/** A bugchecker for testing suggested fixes. */
@BugPattern(summary = "A bugchecker for testing suggested fixes.", severity = ERROR)
public static class PrefixAddImportCheck extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return describeMatch(
tree,
SuggestedFix.builder()
.prefixWith(tree, "@Deprecated\n")
.addImport("java.util.List")
.build());
}
}
@Test
public void prefixAddImport() throws IOException {
BugCheckerRefactoringTestHelper.newInstance(PrefixAddImportCheck.class, getClass())
.addInputLines(
"in/Test.java", //
"package p;",
"class Test {}")
.addOutputLines(
"out/Test.java", //
"package p;",
"import java.util.List;",
"@Deprecated",
"class Test {}")
.doTest();
}
@Test
public void sourceURITest() throws Exception {
assertThat(SuggestedFixes.sourceURI(URI.create("file:/com/google/Foo.java")))
.isEqualTo(URI.create("file:/com/google/Foo.java"));
assertThat(SuggestedFixes.sourceURI(URI.create("jar:file:sources.jar!/com/google/Foo.java")))
.isEqualTo(URI.create("file:/com/google/Foo.java"));
}
/** A {@link BugChecker} for testing. */
@BugPattern(summary = "RenameMethodChecker", severity = ERROR)
public static class RenameMethodChecker extends BugChecker
implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return describeMatch(tree, SuggestedFixes.renameMethodInvocation(tree, "singleton", state));
}
}
@Test
public void renameMethodInvocation() {
BugCheckerRefactoringTestHelper.newInstance(RenameMethodChecker.class, getClass())
.addInputLines(
"Test.java",
"import java.util.Collections;",
"class Test {",
" int singletonList = 1;",
" Object foo = Collections.<Integer /* foo */>singletonList(singletonList);",
" Object bar = Collections.<Integer>/* foo */singletonList(singletonList);",
" Object baz = Collections.<Integer> singletonList (singletonList);",
" class emptyList {}",
" Object quux = Collections.<emptyList>singletonList(null);",
"}")
.addOutputLines(
"Test.java",
"import java.util.Collections;",
"class Test {",
" int singletonList = 1;",
" Object foo = Collections.<Integer /* foo */>singleton(singletonList);",
" Object bar = Collections.<Integer>/* foo */singleton(singletonList);",
" Object baz = Collections.<Integer> singleton (singletonList);",
" class emptyList {}",
" Object quux = Collections.<emptyList>singleton(null);",
"}")
.doTest(TEXT_MATCH);
}
/**
* Test checker that raises a diagnostic with the result of {@link SuggestedFixes#qualifyType} on
* new instances.
*/
@BugPattern(summary = "QualifyTypeLocalClassChecker", severity = ERROR)
public static class QualifyTypeLocalClassChecker extends BugChecker
implements NewClassTreeMatcher {
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
SuggestedFix.Builder builder = SuggestedFix.builder();
return buildDescription(tree)
.setMessage(SuggestedFixes.qualifyType(state, builder, ASTHelpers.getType(tree).tsym))
.build();
}
}
@Test
public void qualifyTypeLocal_localClass() {
CompilationTestHelper.newInstance(QualifyTypeLocalClassChecker.class, getClass())
.addSourceLines(
"Test.java",
"import java.util.function.Supplier;",
"class Test {",
" static {",
" class InStaticInitializer {}",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] InStaticInitializer",
" new InStaticInitializer();",
" }",
"",
" {",
" class InInstanceInitializer {}",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] InInstanceInitializer",
" new InInstanceInitializer();",
" }",
"",
" Test() { // in constructor",
" class InConstructor {}",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] InConstructor",
" new InConstructor();",
" }",
"",
" static Object staticMethod() {",
" class InStaticMethod {}",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] InStaticMethod",
" return new InStaticMethod();",
" }",
"",
" Object instanceMethod() {",
" class InInstanceMethod {}",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] InInstanceMethod",
" return new InInstanceMethod();",
" }",
"",
" void lambda() {",
" Supplier<Object> consumer = () -> {",
" class InLambda {}",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] InLambda",
" return new InLambda();",
" };",
" }",
"}")
.doTest();
}
@Test
public void qualifyTypeLocal_anonymousClass() {
CompilationTestHelper.newInstance(QualifyTypeLocalClassChecker.class, getClass())
.addSourceLines(
"Test.java",
"import java.util.function.Supplier;",
"class Test {",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] Object",
" static Object staticField = new Object() {};",
"",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] Object",
" Object instanceField = new Object() {};",
"",
" static {",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] Object",
" new Object() {};",
" }",
"",
" {",
" class InInstanceInitializer {}",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] Object",
" new Object() {};",
" }",
"",
" Test() { // in constructor",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] Object",
" new Object() {};",
" }",
"",
" static Object staticMethod() {",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] Object",
" return new Object() {};",
" }",
"",
" Object instanceMethod() {",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] Object",
" return new Object() {};",
" }",
"",
" void lambda() {",
" Supplier<Object> consumer = () -> {",
" // BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] Object",
" return new Object() {};",
" };",
" }",
"}")
.doTest();
}
/** Test checker that adds @SuppressWarnings when compilation succeeds in the current unit. */
@BugPattern(summary = "", severity = ERROR)
public static final class AddSuppressWarningsIfCompilationSucceedsOnlyInSameCompilationUnit
extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return addSuppressWarningsIfCompilationSucceeds(
tree, state, true, fix -> describeMatch(tree, fix));
}
}
@Test
public void compilesWithFix_onlyInSameCompilationUnit() {
String[] unrelatedFile = {
"class ClassContainingRawType {",
// This unsuppressed raw type would prevent compilation.
" java.util.List list;",
"}",
};
// This compilation will succeed because we only consider the compilation errors in the first
// class.
CompilationTestHelper.newInstance(
AddSuppressWarningsIfCompilationSucceedsOnlyInSameCompilationUnit.class, getClass())
.addSourceLines(
"OnlyInSameCompilationUnit.java", //
"// BUG: Diagnostic contains: foobar",
"class OnlyInSameCompilationUnit {",
"}")
.addSourceLines("ClassContainingRawType.java", unrelatedFile)
.doTest();
// But a warning in the first class makes the compilation fail, so no suppression is added.
CompilationTestHelper.newInstance(
AddSuppressWarningsIfCompilationSucceedsOnlyInSameCompilationUnit.class, getClass())
.addSourceLines(
"OnlyInSameCompilationUnit.java", //
"class OnlyInSameCompilationUnit {",
// This unsuppressed raw type prevents compilation.
" java.util.List list;",
"}")
.addSourceLines("ClassContainingRawType.java", unrelatedFile)
.doTest();
}
/** Test checker that adds @SuppressWarnings when compilation succeeds in all units. */
@BugPattern(summary = "", severity = ERROR)
public static final class AddSuppressWarningsIfCompilationSucceedsInAllCompilationUnits
extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
return addSuppressWarningsIfCompilationSucceeds(
tree, state, false, fix -> describeMatch(tree, fix));
}
}
@Test
public void compilesWithFix_inAllCompilationUnits() {
// This compilation will succeed because we consider all compilation errors.
CompilationTestHelper.newInstance(
AddSuppressWarningsIfCompilationSucceedsInAllCompilationUnits.class, getClass())
.addSourceLines(
"InAllCompilationUnits.java", //
"class InAllCompilationUnits {",
"}")
.addSourceLines(
"ClassContainingRawType.java", //
"class ClassContainingRawType {",
// This unsuppressed raw type prevents re-compilation, so the other class is unchanged.
" java.util.List list;",
"}")
.doTest();
}
private static Description addSuppressWarningsIfCompilationSucceeds(
ClassTree tree,
VisitorState state,
boolean onlyInSameCompilationUnit,
Function<? super Fix, Description> toDescriptionFn) {
return Optional.of(SuggestedFix.prefixWith(tree, "@SuppressWarnings(\"foobar\") "))
.filter(
fix ->
SuggestedFixes.compilesWithFix(
fix,
state,
ImmutableList.of("-Xlint:unchecked,rawtypes", "-Werror"),
onlyInSameCompilationUnit))
.map(toDescriptionFn)
.orElse(NO_MATCH);
}
/** Test checker that casts return expressions to int. */
@BugPattern(
name = "AddSuppressWarningsIfCompilationSucceedsInAllCompilationUnits",
summary = "",
severity = ERROR)
public static final class CastTreeToIntChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(
tree,
SuggestedFix.replace(
tree.getExpression(), SuggestedFixes.castTree(tree.getExpression(), "int", state)));
}
}
@Test
public void castTree() {
BugCheckerRefactoringTestHelper.newInstance(CastTreeToIntChecker.class, getClass())
.addInputLines(
"Test.java",
"class Test {",
" public int one() { return 1; }",
" public int negateOne() { return ~1; }",
" public int castOne() { return (short) 1; }",
" public int onePlusOne() { return 1 + 1; }",
" public int simpleAssignment() { int a = 0; return a = 1; }",
" public int compoundAssignment() { int a = 0; return a += 1; }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" public int one() { return (int) 1; }",
" public int negateOne() { return (int) ~1; }",
" public int castOne() { return (int) (short) 1; }",
" public int onePlusOne() { return (int) (1 + 1); }",
" public int simpleAssignment() { int a = 0; return (int) (a = 1); }",
" public int compoundAssignment() { int a = 0; return (int) (a += 1); }",
"}")
.doTest();
}
@Test
public void addDuplicateImport() {
String firstImport = "java.time.Duration";
String secondImport = "java.time.Instant";
SuggestedFix fix =
SuggestedFix.builder()
.addImport(firstImport)
.addImport(secondImport)
.addImport(firstImport)
.build();
assertThat(fix.getImportsToAdd())
.containsExactly("import " + firstImport, "import " + secondImport)
.inOrder();
}
@Test
public void addDuplicateStaticImport() {
String firstImport = "java.util.concurrent.TimeUnit.MILLISECONDS";
String secondImport = "java.util.concurrent.TimeUnit.SECONDS";
SuggestedFix fix =
SuggestedFix.builder()
.addStaticImport(firstImport)
.addStaticImport(secondImport)
.addStaticImport(firstImport)
.build();
assertThat(fix.getImportsToAdd())
.containsExactly("import static " + firstImport, "import static " + secondImport)
.inOrder();
}
@Test
public void removeElement() {
BugCheckerRefactoringTestHelper.newInstance(RemoveAnnotationElement.class, getClass())
.addInputLines(
"Anno.java", //
"@interface Anno {",
" int a() default 0;",
" int b() default 0;",
"}")
.expectUnchanged()
.addInputLines(
"Test.java",
"class Test {",
" @Anno(a = 1) class A {}",
" @Anno(a = 1, b = 2) class B {}",
" @Anno(b = 1, a = 2) class C {}",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" @Anno() class A {}",
" @Anno(b = 2) class B {}",
" @Anno(b = 1) class C {}",
"}")
.doTest();
}
/** Bugpattern for testing. */
@BugPattern(name = "RemoveAnnotationElement", summary = "", severity = ERROR)
public static final class RemoveAnnotationElement extends BugChecker
implements AnnotationTreeMatcher {
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
return tree.getArguments().stream()
.filter(
t ->
((IdentifierTree) ((AssignmentTree) t).getVariable())
.getName()
.contentEquals("a"))
.findFirst()
.map(t -> describeMatch(t, SuggestedFixes.removeElement(t, tree.getArguments(), state)))
.orElse(NO_MATCH);
}
}
}
| 73,572
| 35.440317
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessInferenceTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.fixes.SuggestedFix.replace;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.dataflow.nullnesspropagation.inference.InferredNullability;
import com.google.errorprone.dataflow.nullnesspropagation.inference.NullnessQualifierInference;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreePath;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author bennostein@google.com (Benno Stein)
*/
@RunWith(JUnit4.class)
public class NullnessInferenceTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NullnessInferenceChecker.class, getClass());
/**
* This method triggers the {@code BugPattern} used to test nullness annotation inference
*
* @param t Method call whose type arguments' inferred nullness will be inspected
* @return {@code t} for use in expressions
*/
public static <T> T inspectInferredGenerics(T t) {
return t;
}
/**
* This method triggers the {@code BugPattern} used to test nullness annotation inference
*
* @param t Expression whose inferred nullness will be inspected
* @return {@code t} for use in expressions
*/
public static <T> T inspectInferredExpression(T t) {
return t;
}
@Test
public void identity() {
compilationHelper
.addSourceLines(
"IdentityTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredGenerics;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class IdentityTest {",
" @Nullable Object nullableObj;",
" @NonNull Object nonnullObj;",
" <T> T id(T t) { return t; }",
" void id_tests() {",
" // BUG: Diagnostic contains: {T=Nullable}",
" inspectInferredGenerics(id(nullableObj));",
" // BUG: Diagnostic contains: {T=Non-null}",
" inspectInferredGenerics(id(nonnullObj));",
" }",
" void literal_tests() {",
" // BUG: Diagnostic contains: {T=Null}",
" inspectInferredGenerics(id(null));",
" // BUG: Diagnostic contains: {T=Non-null}",
" inspectInferredGenerics(id(this));",
" // BUG: Diagnostic contains: {T=Non-null}",
" inspectInferredGenerics(id(5));",
" // BUG: Diagnostic contains: {T=Non-null}",
" inspectInferredGenerics(id(\"hello\"));",
" // BUG: Diagnostic contains: {T=Non-null}",
" inspectInferredGenerics(id(new Object()));",
" // BUG: Diagnostic contains: {T=Non-null}",
" inspectInferredGenerics(id(new Object[0]));",
" }",
"}")
.doTest();
}
@Test
public void annotatedGenericMethod() {
compilationHelper
.addSourceLines(
"AnnotatedGenericMethodTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredGenerics;",
"import org.checkerframework.checker.nullness.compatqual.NullableDecl;",
"import org.checkerframework.checker.nullness.compatqual.NonNullDecl;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class AnnotatedGenericMethodTest {",
" <T> @NonNull T makeNonNull(@Nullable T t) { return t; }",
" <T> @NonNullDecl T makeNonNullDecl(@NullableDecl T t) { return t; }",
" void test_type_anno(Object o) {",
" // BUG: Diagnostic contains: Optional[Nullable]",
" makeNonNull(inspectInferredExpression(o));",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(makeNonNull(o));",
" }",
" void test_decl_anno(Object o) {",
" // BUG: Diagnostic contains: Optional[Nullable]",
" makeNonNullDecl(inspectInferredExpression(o));",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(makeNonNullDecl(o));",
" }",
" void test_generics(Object o) {",
" // BUG: Diagnostic contains: {}",
" inspectInferredGenerics(makeNonNull(o));",
" // BUG: Diagnostic contains: {}",
" inspectInferredGenerics(makeNonNullDecl(o));",
" }",
"}")
.doTest();
}
@Test
public void boundedGenericMethod() {
compilationHelper
.addSourceLines(
"AnnotatedGenericMethodTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredGenerics;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class AnnotatedGenericMethodTest {",
" <T extends @NonNull Object> T requireNonNull(T t) { return t; }",
" <T extends @NonNull Object> T makeNonNull(@Nullable T t) { return t; }",
" void test_bound_only(Object o) {",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(requireNonNull(o));",
" // BUG: Diagnostic contains: {T=Non-null}",
" inspectInferredGenerics(requireNonNull(o));",
" }",
" void test_bound_and_param_anno(Object o) {",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(makeNonNull(o));",
" // BUG: Diagnostic contains: {T=Non-null}",
" inspectInferredGenerics(makeNonNull(o));",
" }",
"}")
.doTest();
}
// Regression test for b/113123074
@Test
public void unparameterizedMethodInvocation() {
compilationHelper
.addSourceLines(
"IdentityTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class IdentityTest {",
" @NonNull Object returnNonnull(@Nullable Integer i) { return \"hello\"; }",
" @Nullable Object returnNullable(@Nullable Integer i) { return \"hello\"; }",
" Object returnUnannotated(@Nullable Integer i) { return \"hello\"; }",
" void invoke_test() {",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(returnNonnull(null));",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(returnNullable(null));",
" // BUG: Diagnostic contains: Optional.empty",
" inspectInferredExpression(returnUnannotated(\"\".hashCode()));",
" }",
"}")
.doTest();
}
@Test
public void lists() {
compilationHelper
.addSourceLines(
"ListsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredGenerics;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class ListsTest {",
" @Nullable Object nullableObj;",
" @NonNull Object nonnullObj;",
" void lists_tests(Object o1, Object o2) {",
// Infer from target type (if possible)
" // BUG: Diagnostic contains: {}",
" inspectInferredGenerics(List.cons(o1, List.cons(o2, List.nil())));",
" // BUG: Diagnostic contains: {Z=Non-null}",
" List<@NonNull Object> l = "
+ "inspectInferredGenerics(List.cons(o1, List.cons(o2, List.nil())));",
// Infer from argument types (if possible)
" // BUG: Diagnostic contains: {Z=Non-null}",
" inspectInferredGenerics(List.cons(nonnullObj, List.<@NonNull Object>nil()));",
" // BUG: Diagnostic contains: {Z=Non-null}",
" inspectInferredGenerics(List.cons(nonnullObj, List.<Object>nil()));",
" // BUG: Diagnostic contains: {Z=Nullable}",
" inspectInferredGenerics("
+ "List.cons(nullableObj, List.cons(nonnullObj, List.nil())));",
// Propagate inference about receiver to result of calls
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression("
+ "List.cons(nonnullObj, List.<@NonNull Object>nil()).head());",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(List.cons(nonnullObj, List.<Object>nil()).head());",
" }",
"}",
" abstract class List<T> {",
" abstract T head();",
" static <X> List<X> nil() {return null;}",
" static <Z> List<Z> cons(Z z, List<Z> zs ) {return null;}",
" }")
.doTest();
}
@Test
public void returnCase() {
compilationHelper
.addSourceLines(
"ReturnTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredGenerics;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class ReturnTest {",
" List<@NonNull Object> return_tests(Object o1, Object o2) {",
" // BUG: Diagnostic contains: {}",
" inspectInferredGenerics(List.cons(o1, List.cons(o2, List.nil())));",
" // BUG: Diagnostic contains: {Z=Non-null}",
" return inspectInferredGenerics(List.cons(o1, List.cons(o2, List.nil())));",
" }",
"}",
"abstract class List<T> {",
" abstract T head();",
" static <X> List<X> nil() {return null;}",
" static <Z> List<Z> cons(Z z, List<Z> zs ) {return null;}",
"}")
.doTest();
}
@Test
public void assignments() {
compilationHelper
.addSourceLines(
"AssignmentsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredGenerics;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"public class AssignmentsTest {",
" void assignments_tests(@Nullable Object nullable, Object unknown) {",
" // BUG: Diagnostic contains: {}",
" inspectInferredGenerics(List.cons(unknown, List.nil()));",
" // BUG: Diagnostic contains: {Z=Non-null}",
" List<@NonNull Object> a ="
+ " inspectInferredGenerics(List.cons(unknown, List.nil()));",
" // BUG: Diagnostic contains: Optional[Non-null]",
" @NonNull Object b ="
+ " inspectInferredExpression(List.cons(unknown, List.nil()).head());",
" }",
"}",
"abstract class List<T> {",
" abstract T head();",
" static <X> List<X> nil() {return null;}",
" static <Z> List<Z> cons(Z z, List<Z> zs ) {return null;}",
"}")
.doTest();
}
@Test
public void varArgs() {
compilationHelper
.addSourceLines(
"VarArgsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredGenerics;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"public class VarArgsTest {",
" void foo(@NonNull Object... objects) {}",
" void bar(@Nullable Object... objects) {}",
" void varargs_tests(Object o) {",
" // BUG: Diagnostic contains: Optional.empty",
" inspectInferredExpression(o);",
" // BUG: Diagnostic contains: Optional[Non-null]",
" foo(inspectInferredExpression(o));",
" // BUG: Diagnostic contains: Optional[Non-null]",
" foo(o, o, o, inspectInferredExpression(o));",
" // BUG: Diagnostic contains: Optional[Nullable]",
" bar(inspectInferredExpression(o));",
" // BUG: Diagnostic contains: Optional[Nullable]",
" bar(o, o, o, inspectInferredExpression(o));",
" }",
"}")
.doTest();
}
@Test
public void annotatedAtGenericTypeUse() {
compilationHelper
.addSourceLines(
"AnnotatedAtGenericTypeUseTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.compatqual.NullableDecl;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class AnnotatedAtGenericTypeUseTest {",
" void test(MyInnerClass<@Nullable Object> nullable, "
+ "MyInnerClass<@NonNull Object> nonnull) {",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nullable.get());",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(nullable.getNonNull());",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(nonnull.get());",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nonnull.getNullable());",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nonnull.getNullableDecl());",
" }",
" void testNested_nullable(MyWrapper<MyInnerClass<@Nullable Object>> nullable) {",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nullable.get().get());",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(nullable.get().getNonNull());",
" }",
" void testNested_nonnull(MyWrapper<MyInnerClass<@NonNull Object>> nonnull) {",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(nonnull.get().get());",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nonnull.get().getNullable());",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nonnull.get().getNullableDecl());",
" }",
" interface MyInnerClass<T> {",
" T get();",
" @NonNull T getNonNull();",
" @Nullable T getNullable();",
" @NullableDecl T getNullableDecl();",
" }",
" interface MyWrapper<T> {",
" T get();",
" }",
"}")
.doTest();
}
@Test
public void annotatedAtGenericTypeDef() {
compilationHelper
.addSourceLines(
"AnnotatedAtGenericTypeDefTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.compatqual.NullableDecl;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class AnnotatedAtGenericTypeDefTest {",
" void test(NullableTypeInner<?> nullable) {",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nullable.get());",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(nullable.getNonNull());",
" }",
" void test(NonNullTypeInner<?> nonnull) {",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(nonnull.get());",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nonnull.getNullable());",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nonnull.getNullableDecl());",
" }",
" void test(TypeAndBoundInner<?> type_and_bound) {",
" // BUG: Diagnostic contains: Optional[Nullable]", // use upper bound (b/121398981)
" inspectInferredExpression(type_and_bound.get());",
" }",
" interface NullableTypeInner<@Nullable T> {",
" T get();",
" @NonNull T getNonNull();",
" }",
" interface NonNullTypeInner<@NonNull T> {",
" T get();",
" @Nullable T getNullable();",
" @NullableDecl T getNullableDecl();",
" }",
" interface TypeAndBoundInner<@NonNull T extends @Nullable Object> { T get(); }",
"}")
.doTest();
}
@Test
public void boundedAtGenericTypeUse() {
compilationHelper
.addSourceLines(
"BoundedAtGenericTypeUseTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class BoundedAtGenericTypeUseTest {",
" void test(MyInnerClass<? extends @Nullable Object> nullable,"
+ "MyInnerClass<? extends @NonNull Object> nonnull) {",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nullable.get());",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(nonnull.get());",
" }",
" interface MyInnerClass<T> {",
" T get();",
" }",
"}")
.doTest();
}
@Test
public void boundedAtGenericTypeDef() {
compilationHelper
.addSourceLines(
"BoundedAtGenericTypeDefTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class BoundedAtGenericTypeDefTest {",
" void test(NullableElementCollection<?> nullable) {",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(nullable.get());",
" }",
" void test(NonNullElementCollection<?> nonnull) {",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(nonnull.get());",
" }",
" interface NullableElementCollection<T extends @Nullable Object> {",
" T get();",
" }",
" interface NonNullElementCollection<T extends @NonNull Object> {",
" T get();",
" }",
"}")
.doTest();
}
@Test
public void defaultAnnotation() {
compilationHelper
.addSourceLines(
"DefaultAnnotationTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class DefaultAnnotationTest<T> {",
" public void testGenericMethod() {",
" Object o = new Object();",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(defaulted());",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(boundDefaulted());",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(bounded());",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(explicit(o));",
" }",
" @DefaultNotNull void testParameters(T undefaulted, String defaulted,",
" @Nullable Integer explicit) {",
" // BUG: Diagnostic contains: Optional.empty", // because T is declared elsewhere
" inspectInferredExpression(undefaulted);",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(defaulted);",
" // BUG: Diagnostic contains: Optional[Nullable]",
" inspectInferredExpression(explicit);",
" }",
" @DefaultNotNull static Object defaulted() { return null; }",
" @DefaultNotNull static <T> T boundDefaulted() { return null; }",
" @DefaultNotNull static <T extends @Nullable Object> T bounded() { return null; }",
" @DefaultNotNull static <T> @Nullable T explicit(T t) { return t; }",
" public @interface DefaultNotNull {}",
"}")
.doTest();
}
@Test
public void intersectionBounds() {
compilationHelper
.addSourceLines(
"IntersectionBoundsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class IntersectionBoundsTest {",
" void test(MyBoundedClass<?> bounded) {",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(bounded.get());",
" }",
" interface MyBoundedClass<T extends @NonNull Number & @Nullable Iterable> {",
" T get();",
" }",
"}")
.doTest();
}
@Test
public void annotatedMethodTypeParams() {
compilationHelper
.addSourceLines(
"AnnotatedMethodTypeParamsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessInferenceTest.inspectInferredExpression;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class AnnotatedMethodTypeParamsTest {",
" public void test() {",
" Object o = new Object();",
" // BUG: Diagnostic contains: Optional[Non-null]",
" inspectInferredExpression(AnnotatedMethodTypeParamsTest.<@NonNull Object>id(o));",
" }",
" static <T> T id(T t) { return t; }",
"}")
.doTest();
}
/** BugPattern to test inference of nullness qualifiers */
@BugPattern(
summary = "Test checker for NullnessInferenceTest",
explanation =
"Outputs an error for each call to inspectInferredExpression and inspectInferredGenerics,"
+ " displaying inferred or explicitly-specified Nullness information.",
severity = ERROR)
public static final class NullnessInferenceChecker extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> GENERICS_CALL_MATCHER =
staticMethod()
.onClass(NullnessInferenceTest.class.getName())
.named("inspectInferredGenerics");
private static final Matcher<ExpressionTree> EXPRESSION_CALL_MATCHER =
staticMethod()
.onClass(NullnessInferenceTest.class.getName())
.named("inspectInferredExpression");
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocation, VisitorState state) {
if (GENERICS_CALL_MATCHER.matches(methodInvocation, state)) {
TreePath root = state.getPath();
InferredNullability inferenceRes =
NullnessQualifierInference.getInferredNullability(
ASTHelpers.findEnclosingNode(root, MethodTree.class));
assertThat(methodInvocation.getArguments().get(0).getKind())
.isEqualTo(Kind.METHOD_INVOCATION);
MethodInvocationTree callsiteToInspect =
(MethodInvocationTree) methodInvocation.getArguments().get(0);
return describeMatch(
callsiteToInspect,
replace(
methodInvocation, inferenceRes.getNullnessGenerics(callsiteToInspect).toString()));
} else if (EXPRESSION_CALL_MATCHER.matches(methodInvocation, state)) {
TreePath root = state.getPath();
InferredNullability inferenceRes =
NullnessQualifierInference.getInferredNullability(
ASTHelpers.findEnclosingNode(root, MethodTree.class));
ExpressionTree exprToInspect = methodInvocation.getArguments().get(0);
return describeMatch(
exprToInspect,
replace(methodInvocation, inferenceRes.getExprNullness(exprToInspect).toString()));
} else {
return NO_MATCH;
}
}
}
}
| 30,240
| 46.925515
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.dataflow.DataFlow.expressionDataflow;
import static com.google.errorprone.fixes.SuggestedFix.replace;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.common.base.Joiner;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author deminguyen@google.com (Demi Nguyen)
*/
@RunWith(JUnit4.class)
public class NullnessPropagationTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(NullnessPropagationChecker.class, getClass());
/**
* This method triggers the {@code BugPattern} used to test nullness propagation
*
* @param obj Variable whose nullness value is being checked
* @return {@code obj} for use in expressions
*/
public static Object triggerNullnessChecker(Object obj) {
return obj;
}
/*
* Methods that should never be called. These methods exist to force tests that pass a primitive
* to decide whether they are testing (a) that primitive itself is null in which case they should
* call triggerNullnessCheckerOnPrimitive or (b) that the result of autoboxing the primitive is
* null, in which case it should call triggerNullnessCheckerOnBoxed. Of course, in either case,
* the value should never be null. (The analysis isn't yet smart enough to detect this in all
* cases.)
*
* Any call to these methods will produce a special error.
*/
public static void triggerNullnessChecker(boolean b) {}
public static void triggerNullnessChecker(byte b) {}
public static void triggerNullnessChecker(char c) {}
public static void triggerNullnessChecker(double d) {}
public static void triggerNullnessChecker(float f) {}
public static void triggerNullnessChecker(int i) {}
public static void triggerNullnessChecker(long l) {}
public static void triggerNullnessChecker(short s) {}
/**
* This method also triggers the {@code BugPattern} used to test nullness propagation, but it is
* intended to be used only in the rare case of testing the result of boxing a primitive.
*/
public static void triggerNullnessCheckerOnBoxed(Object obj) {}
/*
* These methods also trigger the {@code BugPattern} used to test nullness propagation, but they
* are careful not to autobox their inputs.
*/
public static void triggerNullnessCheckerOnPrimitive(boolean b) {}
public static void triggerNullnessCheckerOnPrimitive(byte b) {}
public static void triggerNullnessCheckerOnPrimitive(char c) {}
public static void triggerNullnessCheckerOnPrimitive(double d) {}
public static void triggerNullnessCheckerOnPrimitive(float f) {}
public static void triggerNullnessCheckerOnPrimitive(int i) {}
public static void triggerNullnessCheckerOnPrimitive(long l) {}
public static void triggerNullnessCheckerOnPrimitive(short s) {}
/** For {@link #testConstantsDefinedInOtherCompilationUnits}. */
public static final String COMPILE_TIME_CONSTANT = "not null";
/** For {@link #testConstantsDefinedInOtherCompilationUnits} as constant outside compilation. */
@SuppressWarnings("GoodTime") // false positive
public static final Integer NOT_COMPILE_TIME_CONSTANT = 421;
@Test
public void transferFunctions1() {
compilationHelper.addSourceFile("NullnessPropagationTransferCases1.java").doTest();
}
@Test
public void transferFunctions2() {
compilationHelper.addSourceFile("NullnessPropagationTransferCases2.java").doTest();
}
@Test
public void transferFunctions3() {
compilationHelper.addSourceFile("NullnessPropagationTransferCases3.java").doTest();
}
@Test
public void transferFunctions4() {
compilationHelper.addSourceFile("NullnessPropagationTransferCases4.java").doTest();
}
@Test
public void transferFunctions5() {
compilationHelper.addSourceFile("NullnessPropagationTransferCases5.java").doTest();
}
@Test
public void transferFunctions6() {
compilationHelper.addSourceFile("NullnessPropagationTransferCases6.java").doTest();
}
@Test
public void transferFunctions7() {
compilationHelper.addSourceFile("NullnessPropagationTransferCases7.java").doTest();
}
@Test
public void transferFunctions8() {
compilationHelper.addSourceFile("NullnessPropagationTransferCases8.java").doTest();
}
@Test
public void nonNullThis() {
compilationHelper
.addSourceLines(
"ThisNonNullTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class ThisNonNullTest {",
" public void instanceMethod() {",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(this);",
" }",
"}")
.doTest();
}
@Test
public void equals() {
compilationHelper
.addSourceLines(
"ThisEqualsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class ThisEqualsTest {",
" @Override",
" public boolean equals(Object obj) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(obj);",
" return this == obj;",
" }",
" private void testEquals(Object arg) {",
" ThisEqualsTest thisEqualsTest = new ThisEqualsTest();",
" if (thisEqualsTest.equals(arg)) {",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(arg);",
" }",
" }",
"}")
.doTest();
}
@Test
public void instanceofNonNull() {
compilationHelper
.addSourceLines(
"InstanceofTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class InstanceofTest {",
" public static void m(Object o) {",
" if (o instanceof InstanceofTest) {",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o);",
" } else {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o);",
" }",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o);",
" }",
"}")
.doTest();
}
@Test
public void protoGetters() {
compilationHelper
.addSourceLines(
"InstanceofTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;",
"public class InstanceofTest {",
" public static void m(TestProtoMessage o) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o.getMessage());",
" }",
"}")
.doTest();
}
@Test
public void arrayAccess() {
compilationHelper
.addSourceLines(
"ArrayAccessTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class ArrayAccessTest {",
" public static void read(Integer[] a) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(a);",
" Integer result = a[0];",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(a);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(result);",
" }",
" public static void read(int[][] matrix) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(matrix);",
" int result = matrix[0][0];",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(matrix);",
" }",
" public static void write(int[] vector) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(vector);",
" vector[7] = 42;",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(vector);",
" }",
"}")
.doTest();
}
@Test
public void fieldAccess() {
compilationHelper
.addSourceLines(
"FieldAccessTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class FieldAccessTest {",
" public static void dereference(Coinductive o) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o.f);",
" o.f = (Coinductive) new Object();",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o.f);",
" }",
" abstract class Coinductive {",
" Coinductive f;",
" }",
"}")
.doTest();
}
@Test
public void fieldReceivers() {
compilationHelper
.addSourceLines(
"FieldReceiversTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class FieldReceiversTest {",
" Object f;",
" public FieldReceiversTest getSelf() { return this; }",
" public void test_different_receivers(FieldReceiversTest other) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(other);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(this);",
" other.f = new Object();",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(other.f);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(this.f);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(f);",
" this.f = null;",
" // BUG: Diagnostic contains: (Null)",
" triggerNullnessChecker(this.f);",
" // BUG: Diagnostic contains: (Null)",
" triggerNullnessChecker(f);",
" }",
"}")
.doTest();
}
@Test
public void fieldPathSensitivity() {
compilationHelper
.addSourceLines(
"FieldPathSensitivityTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class FieldPathSensitivityTest {",
" public static void path_sensitivity(Coinductive o) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o.f);",
" if (o.f == null) {",
" // BUG: Diagnostic contains: (Null)",
" triggerNullnessChecker(o.f);",
" } else {",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o.f);",
" }",
" }",
" abstract class Coinductive {",
" Coinductive f;",
" }",
"}")
.doTest();
}
@Test
public void accessPaths() {
compilationHelper
.addSourceLines(
"AccessPathsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class AccessPathsTest {",
" public static void access_paths(Coinductive o) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o.f.f.f.f.f);",
" o.f.f.f.f.f = (Coinductive) new Object();",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o.f.f.f.f.f);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o.f.f.f.f);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o.f.f.f);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o.f.f);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o.f);",
" }",
" abstract class Coinductive {",
" Coinductive f;",
" }",
"}")
.doTest();
}
@Test
public void untrackableFields() {
compilationHelper
.addSourceLines(
"UntrackableFieldsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class UntrackableFieldsTest {",
" public static void untrackable_fields(CoinductiveWithMethod o) {",
" o.f.f = (CoinductiveWithMethod) new Object();",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o.f.f);",
" o.foo().f = (CoinductiveWithMethod) new Object();",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o.foo().f);",
" }",
" abstract class CoinductiveWithMethod {",
" CoinductiveWithMethod f;",
" abstract CoinductiveWithMethod foo();",
" }",
"}")
.doTest();
}
@Test
public void annotatedAtGenericTypeUse() {
compilationHelper
.addSourceLines(
"AnnotatedAtGenericTypeUseTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class AnnotatedAtGenericTypeUseTest {",
" void test(MyInnerClass<@Nullable Object> nullable,"
+ "MyInnerClass<@NonNull Object> nonnull) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nullable.get());",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(nonnull.get());",
" }",
" interface MyInnerClass<T> {",
" T get();",
" }",
"}")
.doTest();
}
@Test
public void annotatedAtGenericTypeDef() {
compilationHelper
.addSourceLines(
"AnnotatedAtGenericTypeDefTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import org.checkerframework.checker.nullness.compatqual.NullableDecl;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class AnnotatedAtGenericTypeDefTest {",
" void test(NullableTypeInner<?> nullable,"
+ "NonNullTypeInner<?> nonnull,"
+ "TypeAndBoundInner<?> type_and_bound) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nullable.get());",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(nullable.getNonNull());",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(nonnull.get());",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nonnull.getNullable());",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nonnull.getNullableDecl());",
" // BUG: Diagnostic contains: (Nullable)", // use upper bound (b/121398981)
" triggerNullnessChecker(type_and_bound.get());",
" }",
" interface NullableTypeInner<@Nullable T> {",
" T get();",
" @NonNull T getNonNull();",
" }",
" interface NonNullTypeInner<@NonNull T> {",
" T get();",
" @Nullable T getNullable();",
" @NullableDecl T getNullableDecl();",
" }",
" interface TypeAndBoundInner<@NonNull T extends @Nullable Object> { T get(); }",
"}")
.doTest();
}
@Test
public void boundedAtGenericTypeUse() {
compilationHelper
.addSourceLines(
"BoundedAtGenericTypeUseTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class BoundedAtGenericTypeUseTest {",
" void test(MyInnerClass<? extends @Nullable Object> nullable,"
+ "MyInnerClass<? extends @NonNull Object> nonnull) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nullable.get());",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(nullable.getNonNull());",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(nonnull.get());",
" }",
" interface MyInnerClass<T> {",
" T get();",
" @NonNull T getNonNull();",
" }",
"}")
.doTest();
}
@Test
public void boundedAtGenericTypeDef() {
compilationHelper
.addSourceLines(
"BoundedAtGenericTypeDefTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class BoundedAtGenericTypeDefTest {",
" void test(NullableElementCollection<?> nullable, "
+ "NonNullElementCollection<?> nonnull) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nullable.get());",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(nonnull.get());",
" }",
" interface NullableElementCollection<T extends @Nullable Object> {",
" T get();",
" }",
" interface NonNullElementCollection<T extends @NonNull Object> {",
" T get();",
" }",
"}")
.doTest();
}
@Test
public void annotatedMethodTypeParams() {
compilationHelper
.addSourceLines(
"AnnotatedMethodTypeParamsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class AnnotatedMethodTypeParamsTest {",
" public void test() {",
" Object o = new Object();",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(AnnotatedMethodTypeParamsTest.<@NonNull Object>id(o));",
" }",
" static <T> T id(T t) { return t; }",
"}")
.doTest();
}
@Test
public void fieldAnnotations() {
compilationHelper
.addSourceLines(
"FieldAnnotationsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import org.checkerframework.checker.nullness.compatqual.NullableDecl;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class FieldAnnotationsTest {",
" void test(NullableTypeInner<?> nullable,"
+ "NonNullTypeInner<?> nonnull,"
+ "TypeAndBoundInner<?> type_and_bound) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nullable.foo);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(nonnull.foo);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nonnull.fooNullable);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nonnull.fooNullableDecl);",
" // BUG: Diagnostic contains: (Nullable)", // use upper bound (b/121398981)
" triggerNullnessChecker(type_and_bound.foo);",
" }",
" class NullableTypeInner<@Nullable T> { T foo; }",
" class NonNullTypeInner<@NonNull T> {",
" T foo;",
" @Nullable T fooNullable;",
" @NullableDecl T fooNullableDecl;",
" }",
" class TypeAndBoundInner<@NonNull T extends @Nullable Object> { T foo; }",
"}")
.doTest();
}
@Test
public void checkerWorksInsideLambdaBody() {
compilationHelper
.addSourceLines(
"LambdaBodyTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class LambdaBodyTest {",
" public void startNothing() {",
" new Thread(()",
" // BUG: Diagnostic contains: (Null)",
" -> triggerNullnessChecker(null))",
" .start();",
" }",
"}")
.doTest();
}
@Test
public void checkerWorksInsideInitializer() {
compilationHelper
.addSourceLines(
"InitializerBlockTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class InitializerBlockTest {",
" // BUG: Diagnostic contains: (Null)",
" Object o1 = triggerNullnessChecker(null);", // instance field initializer
" // BUG: Diagnostic contains: (Null)",
" static Object o2 = triggerNullnessChecker(null);", // static field initializer
" {", // instance initializer block
" // BUG: Diagnostic contains: (Null)",
" triggerNullnessChecker(null);",
" }",
" static {", // static initializer block
" // BUG: Diagnostic contains: (Null)",
" triggerNullnessChecker(null);",
" // The following is a regression test for b/80179088",
" int i = 0; i = i++;",
" }",
"}")
.doTest();
}
/**
* Tests nullness propagation for references to constants defined in other compilation units. Enum
* constants and compile-time constants are still known to be non-null; other constants are
* assumed nullable. It doesn't matter whether the referenced compilation unit is part of the same
* compilation or not. Note we often do better when constants are defined in the same compilation
* unit. Circular initialization dependencies between compilation units are also not recognized
* while we do recognize them inside a compilation unit.
*/
@Test
public void constantsDefinedInOtherCompilationUnits() {
compilationHelper
.addSourceLines(
"AnotherEnum.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"public enum AnotherEnum {",
" INSTANCE;",
" public static final String COMPILE_TIME_CONSTANT = \"not null\";",
" public static final AnotherEnum NOT_COMPILE_TIME_CONSTANT = INSTANCE;",
" public static final String CIRCULAR = ConstantsFromOtherCompilationUnits.CIRCULAR;",
"}")
.addSourceLines(
"ConstantsFromOtherCompilationUnits.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class ConstantsFromOtherCompilationUnits {",
" public static final String CIRCULAR = AnotherEnum.CIRCULAR;",
" public void referenceInsideCompilation() {",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(AnotherEnum.INSTANCE);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(AnotherEnum.COMPILE_TIME_CONSTANT);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(AnotherEnum.NOT_COMPILE_TIME_CONSTANT);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(CIRCULAR);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(AnotherEnum.CIRCULAR);",
" }",
"",
" public void referenceOutsideCompilation() {",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(NullnessPropagationTest.COMPILE_TIME_CONSTANT);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(NullnessPropagationTest.NOT_COMPILE_TIME_CONSTANT);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(System.out);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(java.math.RoundingMode.UNNECESSARY);",
" }",
"}")
.doTest();
}
// Regression test for b/110756716, verifying that the l-val of an assignment in expr position in
// an equality comparison is refined
@Test
public void whileLoopPartialCorrectness() {
compilationHelper
.addSourceLines(
"PartialCorrectnessTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"public class PartialCorrectnessTest {",
" public void test(java.util.function.Supplier<Object> supplier) {",
" Object result;",
" while((result = supplier.get()) == null) { }",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(result);",
" }",
"}")
.doTest();
}
@Test
public void casts() {
compilationHelper
.addSourceLines(
"CastsTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class CastsTest {",
" public void test(@Nullable Object o) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker((@NonNull Object) o);",
" }",
"}")
.doTest();
}
@Test
public void autoValue() {
compilationHelper
.addSourceLines(
"AutoValueTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import com.google.auto.value.AutoValue;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"public class AutoValueTest {",
" public void test(Value v) {",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(v.accessor().field);",
" if (v.accessor().field != null) {",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(v.accessor().field);",
" }",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(v.nullableAccessor());",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(v.accessor());",
" }",
" @AutoValue",
" static abstract class Value {",
" Value field;",
" abstract Value accessor();",
" @Nullable abstract Value nullableAccessor();",
" }",
"}")
.doTest();
}
@Test
public void genericTypeInference() {
compilationHelper
.addSourceLines(
"GenericTypeInferenceTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"public class GenericTypeInferenceTest {",
" public void test(@NonNull Object o) {",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(o);",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(id(o));",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(idButMaybeNullify(o));",
" }",
" <T> T id(T t) {return t;}",
" <T> @Nullable T idButMaybeNullify(T t) {",
" return java.lang.Math.random() > 0.5 ? t : null;",
" }",
"}")
.doTest();
}
@Test
public void annotatedFormal() {
compilationHelper
.addSourceLines(
"AnnotatedFormalTest.java",
"package com.google.errorprone.dataflow.nullnesspropagation;",
"import static com.google.errorprone.dataflow.nullnesspropagation."
+ "NullnessPropagationTest.triggerNullnessChecker;",
"import org.checkerframework.checker.nullness.qual.NonNull;",
"import org.checkerframework.checker.nullness.qual.Nullable;",
"public class AnnotatedFormalTest {",
" public void test(@NonNull Object nonnull, @Nullable Object nullable, Object o) {",
" // BUG: Diagnostic contains: (Non-null)",
" triggerNullnessChecker(nonnull);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(nullable);",
" // BUG: Diagnostic contains: (Nullable)",
" triggerNullnessChecker(o);",
" }",
"}")
.doTest();
}
/** BugPattern to test dataflow analysis using nullness propagation */
@BugPattern(
summary = "Test checker for NullnessPropagationTest",
explanation =
"Outputs an error for each call to triggerNullnessChecker, describing its "
+ "argument as nullable or non-null",
severity = ERROR)
public static final class NullnessPropagationChecker extends BugChecker
implements MethodInvocationTreeMatcher {
private final NullnessPropagationTransfer nullnessPropagation =
new NullnessPropagationTransfer();
private static final String AMBIGUOUS_CALL_MESSAGE =
"AMBIGUOUS CALL: use "
+ "triggerNullnessCheckerOnPrimitive if you want to test the primitive for nullness";
private static final Matcher<ExpressionTree> TRIGGER_CALL_MATCHER =
anyOf(
staticMethod()
.onClass(NullnessPropagationTest.class.getName())
.named("triggerNullnessCheckerOnPrimitive"),
staticMethod()
.onClass(NullnessPropagationTest.class.getName())
.named("triggerNullnessCheckerOnBoxed"),
staticMethod()
.onClass(NullnessPropagationTest.class.getName())
.named("triggerNullnessChecker")
.withParameters("java.lang.Object"));
private static final Matcher<ExpressionTree> AMBIGUOUS_CALL_FALLBACK_MATCHER =
staticMethod()
.onClass(NullnessPropagationTest.class.getName())
.named("triggerNullnessChecker");
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocation, VisitorState state) {
if (!TRIGGER_CALL_MATCHER.matches(methodInvocation, state)) {
if (AMBIGUOUS_CALL_FALLBACK_MATCHER.matches(methodInvocation, state)) {
return buildDescription(methodInvocation).setMessage(AMBIGUOUS_CALL_MESSAGE).build();
}
return NO_MATCH;
}
TreePath root = state.getPath();
List<Object> values = new ArrayList<>();
for (Tree arg : methodInvocation.getArguments()) {
TreePath argPath = new TreePath(root, arg);
nullnessPropagation.setContext(state.context).setCompilationUnit(root.getCompilationUnit());
values.add(expressionDataflow(argPath, state.context, nullnessPropagation));
nullnessPropagation.setContext(null).setCompilationUnit(null);
}
String fixString = "(" + Joiner.on(", ").join(values) + ")";
return describeMatch(methodInvocation, replace(methodInvocation, fixString));
}
}
}
| 38,107
| 41.721973
| 100
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/testdata/NullnessPropagationTransferCases1.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation.testdata;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessCheckerOnPrimitive;
/**
* Dataflow analysis cases for testing transfer functions in nullness propagation, primarily around
* conditionals.
*/
public class NullnessPropagationTransferCases1 {
public void conditionalNot(String foo) {
if (!(foo == null)) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(foo);
return;
}
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(foo);
}
public void conditionalOr1(String foo, String bar) {
if (foo == null || bar == null) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(bar);
return;
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(foo);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(bar);
}
public void conditionalOr2(String foo, String bar) {
if (foo != null || bar != null) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
}
public void conditionalOr3(String foo) {
if (foo != null || foo != null) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(foo);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
}
public void conditionalOr4(String foo) {
// BUG: Diagnostic contains: (Non-null)
if (foo == null || triggerNullnessChecker(foo) == null) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
}
// BUG: Diagnostic contains: (Null)
if (foo != null || triggerNullnessChecker(foo) != null) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
}
public void conditionalAnd1(String foo, String bar) {
if (foo != null && bar != null) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(foo);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
}
public void conditionalAnd2(String foo) {
if (foo == null && foo != null) {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(foo);
return;
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
}
public void conditionalAnd3(String foo) {
// BUG: Diagnostic contains: (Null)
if (foo == null && triggerNullnessChecker(foo) == null) {
// Something
}
// BUG: Diagnostic contains: (Non-null)
if (foo != null && triggerNullnessChecker(foo) != null) {
// Something
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(foo);
}
public void ternary1(String nullable) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(nullable == null ? "" : nullable);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(nullable != null ? null : nullable);
}
public void ternary2(boolean test, String nullable) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(test ? "yes" : "no");
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(test ? nullable : "");
}
public void valueOfComparisonItself() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 == 1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 != 1);
boolean b;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(b = (1 == 1));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(b = (1 != 1));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(!b);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(b || b);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(b && b);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(b = !b);
}
public void leastUpperBoundOfNonNullAndUnknown(String param, boolean b) {
if (b) {
param = "foo";
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(param);
}
public void stringConcatenation(String a, String b) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(a + b);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(null + b);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(a + 5);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(null + (String) null);
}
}
| 5,613
| 30.016575
| 123
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/testdata/NullnessPropagationTransferCases4.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation.testdata;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
/** Tests for ==. */
public class NullnessPropagationTransferCases4 {
public void equalBothNull() {
String str1 = null;
if (str1 == null) {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
if (null == str1) {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
String str2 = null;
if (str1 == str2) {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
public void equalBothNonNull() {
String str1 = "foo";
if (str1 == "bar") {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
if ("bar" == str1) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
String str2 = "bar";
if (str1 == str2) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
public void equalOneNullOtherNonNull() {
String str1 = "foo";
if (str1 == null) {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
if (null == str1) {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
String str2 = null;
if (str1 == str2) {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
if (str2 == str1) {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
public void equalOneNullableOtherNull(String nullableParam) {
String str1 = nullableParam;
if (str1 == null) {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
if (null == str1) {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
String str2 = null;
if (str1 == str2) {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
if (str2 == str1) {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
public void equalOneNullableOtherNonNull(String nullableParam) {
String str1 = nullableParam;
if (str1 == "foo") {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
if ("foo" == str1) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
String str2 = "foo";
if (str1 == str2) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
if (str2 == str1) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
// TODO(eaftan): tests for bottom?
}
| 8,406
| 29.682482
| 112
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/testdata/NullnessPropagationTransferCases7.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation.testdata;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessCheckerOnBoxed;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessCheckerOnPrimitive;
import static com.google.errorprone.dataflow.nullnesspropagation.testdata.NullnessPropagationTransferCases7.HasStaticFields.staticIntField;
import static com.google.errorprone.dataflow.nullnesspropagation.testdata.NullnessPropagationTransferCases7.HasStaticFields.staticStringField;
/** Tests for field accesses and assignments. */
public class NullnessPropagationTransferCases7 {
private static class MyClass {
int field;
}
private static class MyContainerClass {
MyClass field;
}
enum MyEnum {
ENUM_INSTANCE;
}
static class HasStaticFields {
static String staticStringField;
static int staticIntField;
}
private int i;
private String str;
private Object obj;
private Integer boxedIntReturningMethod() {
return null;
}
public void field() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(i);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed(i);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(obj);
}
public void fieldQualifiedByThis() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(this.i);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed(this.i);
}
public void fieldQualifiedByOtherVar() {
NullnessPropagationTransferCases7 self = this;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(self.i);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed(self.i);
}
public void fieldAccessIsDereference(MyClass nullableParam) {
MyClass mc = nullableParam;
int i = mc.field;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(mc);
}
public void staticFieldAccessIsNotDereferenceNullableReturn(HasStaticFields nullableParam) {
String s = nullableParam.staticStringField;
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(nullableParam);
}
public void staticFieldAccessIsNotDereferenceNonNullReturn(MyEnum nullableParam) {
MyEnum x = nullableParam.ENUM_INSTANCE;
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(nullableParam);
}
public void fieldAssignmentIsDereference(MyClass nullableParam) {
MyClass mc = nullableParam;
mc.field = 0;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(mc);
}
public void chainedFieldAssignmentIsDereference(MyClass nullableParam) {
MyClass mc = nullableParam;
MyContainerClass container = new MyContainerClass();
container.field.field = 0;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(container);
}
public void staticFieldAssignmentIsNotDereferenceNullableReturn(HasStaticFields nullableParam) {
nullableParam.staticStringField = "foo";
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(nullableParam);
}
public void staticFieldAssignmentIsNotDereferenceNonNullReturn(HasStaticFields nullableParam) {
nullableParam.staticIntField = 0;
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(nullableParam);
}
public void staticFieldAccessIsNotDereferenceButPreservesExistingInformation() {
HasStaticFields container = new HasStaticFields();
String s = container.staticStringField;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(container);
}
public void trackFieldValues() {
MyContainerClass container = new MyContainerClass();
container.field = new MyClass();
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(container.field);
container.field.field = 10;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(container.field);
}
public void assignmentToFieldExpressionValue() {
MyContainerClass container = new MyContainerClass();
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(container.field = new MyClass());
}
public void assignmentToPrimitiveFieldExpressionValue() {
MyClass mc = new MyClass();
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(mc.field = 10);
}
public void assignmentToStaticImportedFieldExpressionValue() {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(staticStringField = null);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(staticStringField = "foo");
}
public void assignmentToStaticImportedPrimitiveFieldExpressionValue() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(staticIntField = boxedIntReturningMethod());
}
public void nullableAssignmentToPrimitiveFieldExpressionValue() {
MyClass mc = new MyClass();
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(mc.field = boxedIntReturningMethod());
}
}
| 5,992
| 33.051136
| 142
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/testdata/NullnessPropagationTransferCases5.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation.testdata;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
/** Tests for !=. */
public class NullnessPropagationTransferCases5 {
public void notEqualBothNull() {
String str1 = null;
if (str1 != null) {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
if (null != str1) {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
String str2 = null;
if (str1 != str2) {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
public void notEqualBothNonNull() {
String str1 = "foo";
if (str1 != "bar") {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
if ("bar" != str1) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
String str2 = "bar";
if (str1 != str2) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
public void notEqualOneNullOtherNonNull() {
String str1 = "foo";
if (str1 != null) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
if (null != str1) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
String str2 = null;
if (str1 != str2) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
if (str2 != str1) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Bottom)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
public void notEqualOneNullableOtherNull(String nullableParam) {
String str1 = nullableParam;
if (str1 != null) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
if (null != str1) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
String str2 = null;
if (str1 != str2) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
if (str2 != str1) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
public void notEqualOneNullableOtherNonNull(String nullableParam) {
String str1 = nullableParam;
if (str1 != "foo") {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
if ("foo" != str1) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
String str2 = "foo";
if (str1 != str2) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
if (str2 != str1) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
}
// TODO(eaftan): tests for bottom?
}
| 8,421
| 29.737226
| 112
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/testdata/NullnessPropagationTransferCases2.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation.testdata;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Verify.verifyNotNull;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessCheckerOnPrimitive;
import static com.google.errorprone.dataflow.nullnesspropagation.testdata.NullnessPropagationTransferCases2.MyEnum.ENUM_INSTANCE;
import static java.lang.String.format;
import static java.lang.String.valueOf;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import java.math.BigInteger;
import java.util.Objects;
/**
* Dataflow analysis cases for testing transfer functions in nullness propagation around constants
* and built-in knowledge.
*/
@SuppressWarnings("deprecation") // test cases include deprecated JUnit methods
public class NullnessPropagationTransferCases2 {
private static class MyClass {
static String staticReturnNullable() {
return null;
}
}
static final int CONSTANT_INT = 1;
static final Integer CONSTANT_BOXED_INTEGER = 1;
static final Integer CONSTANT_DERIVED_INTEGER = (Integer) (CONSTANT_INT);
static final Boolean CONSTANT_DERIVED_BOOLEAN = CONSTANT_INT == 1;
static final String CONSTANT_STRING = "foo";
static final String CONSTANT_NULL_STRING = null;
static final String CONSTANT_DERIVED_STRING = CONSTANT_DERIVED_BOOLEAN ? CONSTANT_STRING : "";
static final MyClass CONSTANT_OTHER_CLASS = new MyClass();
static final Integer[] CONSTANT_OBJECT_ARRAY = new Integer[7];
static final Integer[] CONSTANT_ARRAY_INITIALIZER = {Integer.valueOf(5)};
static final Object CONSTANT_NO_INITIALIZER;
static {
CONSTANT_NO_INITIALIZER = new Object();
}
public void constants() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(CONSTANT_INT);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(CONSTANT_BOXED_INTEGER);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(CONSTANT_DERIVED_INTEGER);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(CONSTANT_DERIVED_BOOLEAN);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(CONSTANT_STRING);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(CONSTANT_NULL_STRING);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(CONSTANT_DERIVED_STRING);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(CONSTANT_OTHER_CLASS);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(CONSTANT_OBJECT_ARRAY);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(CONSTANT_OBJECT_ARRAY[0]);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(CONSTANT_ARRAY_INITIALIZER);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(CONSTANT_NO_INITIALIZER);
}
public static final MyBigInteger CIRCULAR = MyBigInteger.CIRCLE;
public void circularInitialization() {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(MyBigInteger.CIRCLE);
}
static class MyBigInteger extends BigInteger {
// Shadows BigInteger.ONE.
public static final MyBigInteger ONE = null;
// Creates circular initializer dependency.
public static final MyBigInteger CIRCLE = NullnessPropagationTransferCases2.CIRCULAR;
MyBigInteger(String val) {
super(val);
}
// Has the same signature as a BigInteger method. In other words, our method hides that one.
public static BigInteger valueOf(long val) {
return null;
}
}
public void builtInConstants() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(BigInteger.ZERO);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(MyBigInteger.ZERO);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(BigInteger.ONE);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(MyBigInteger.ONE);
}
enum MyEnum {
ENUM_INSTANCE;
static MyEnum valueOf(char c) {
return null;
}
public static final MyEnum NOT_COMPILE_TIME_CONSTANT = ENUM_INSTANCE;
public static final MyEnum UNKNOWN_VALUE_CONSTANT = instance();
public static MyEnum instance() {
return ENUM_INSTANCE;
}
}
public void enumConstants() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(MyEnum.ENUM_INSTANCE);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(ENUM_INSTANCE);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(MyEnum.NOT_COMPILE_TIME_CONSTANT);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(MyEnum.UNKNOWN_VALUE_CONSTANT);
}
public void explicitValueOf() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(String.valueOf(3));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(valueOf(3));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(Integer.valueOf(null));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(BigInteger.valueOf(3));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(Enum.valueOf(MyEnum.class, "INSTANCE"));
// We'd prefer this to be Non-null. See the TODO on CLASSES_WITH_NON_NULLABLE_VALUE_OF_METHODS.
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(MyEnum.valueOf("INSTANCE"));
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(MyBigInteger.valueOf(3));
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(MyEnum.valueOf('a'));
}
public void methodInvocationIsDereference(String nullableParam) {
String str = nullableParam;
str.toString();
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str);
}
public void booleanMethodInvocationIsDereference(String nullableParam) {
String str = nullableParam;
str.isEmpty();
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str);
}
public void staticMethodInvocationIsNotDereferenceNullableReturn(MyClass nullableParam) {
nullableParam.staticReturnNullable();
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(nullableParam);
}
public void staticMethodInvocationIsNotDereferenceNonNullReturn(String nullableParam) {
nullableParam.valueOf(true);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(nullableParam);
}
public void staticMethodInvocationIsNotDereferenceButPreservesExistingInformation() {
String s = "foo";
s.format("%s", "foo");
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
}
public void staticMethodInvocationIsNotDereferenceButDefersToOtherNewInformation(String s) {
s = s.valueOf(true);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
}
public void classgetNamesMethods() {
Class<?> klass = this.getClass();
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(klass.getName());
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(klass.getSimpleName());
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(klass.getCanonicalName());
}
public void stringStaticMethodsReturnNonNull() {
String s = null;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(String.format("%s", "foo"));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(format("%s", "foo"));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s.format("%s", "foo"));
}
public void stringInstanceMethodsReturnNonNull() {
String s = null;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s.substring(0));
}
public void requireNonNullReturnsNonNull(String s) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(Objects.requireNonNull(s));
}
public void requireNonNullUpdatesVariableNullness(String s) {
Objects.requireNonNull(s);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
}
public void checkNotNullReturnsNonNull(String s) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(checkNotNull(s));
}
public void checkNotNullUpdatesVariableNullness(String s) {
checkNotNull(s);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
}
public void verifyNotNullReturnsNonNull(String s) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(verifyNotNull(s));
}
public void verifyNotNullUpdatesVariableNullness(String s) {
verifyNotNull(s);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
}
public void junit3AssertNotNullOneArgUpdatesVariableNullness(Object o) {
junit.framework.Assert.assertNotNull(o);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(o);
}
public void junit3AssertNotNullTwoArgUpdatesVariableNullness(String message, Object o) {
junit.framework.Assert.assertNotNull(message, o);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(o);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(message);
}
public void junit4AssertNotNullOneArgUpdatesVariableNullness(Object o) {
org.junit.Assert.assertNotNull(o);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(o);
}
public void junit4AssertNotNullTwoArgUpdatesVariableNullness(String message, Object o) {
org.junit.Assert.assertNotNull(message, o);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(o);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(message);
}
public void stringsIsNullOrEmptyIsNullCheck(String s) {
if (Strings.isNullOrEmpty(s)) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(s);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
}
}
public void objectsIsNullIsNullCheck(String s) {
if (Objects.isNull(s)) {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(s);
} else {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
}
}
public void objectsNonNullIsNullCheck(String s) {
if (Objects.nonNull(s)) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
} else {
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(s);
}
}
public void optionalMethodsReturnNonNullUnlessAnnotated() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(Optional.absent());
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(Optional.of(""));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(Optional.fromNullable(null));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(Optional.of("Test"));
Optional<String> myOptional = Optional.absent();
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(myOptional.get());
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(myOptional.or(""));
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(myOptional.asSet());
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(myOptional.orNull());
}
}
| 12,202
| 34.268786
| 129
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/testdata/NullnessPropagationTransferCases8.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation.testdata;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
/** Tests for {@code try} blocks. */
public class NullnessPropagationTransferCases8 {
public void caughtException() {
try {
System.out.println();
} catch (Throwable t) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(t);
t = something();
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(t);
}
}
void tryWithResources() throws Exception {
try (OutputStream out = something()) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(out);
}
try (OutputStream out = new ByteArrayOutputStream()) {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(out);
}
}
<T> T something() {
return null;
}
}
| 1,606
| 29.320755
| 112
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/testdata/NullnessPropagationTransferCases6.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation.testdata;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessCheckerOnPrimitive;
import static com.google.errorprone.dataflow.nullnesspropagation.testdata.NullnessPropagationTransferCases6.MyEnum.ENUM_INSTANCE;
/**
* Tests for:
*
* <ul>
* <li>bitwise operations
* <li>numerical operations and comparisons
* <li>plain {@code visitNode}
* <li>name shadowing
* </ul>
*/
public class NullnessPropagationTransferCases6 {
enum MyEnum {
ENUM_INSTANCE;
}
public void bitwiseOperations() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 | 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 & 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 ^ 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(~1);
}
public void bitwiseOperationsAreDereferences(Integer i) {
/*
* This next part has nothing to do with bitwise operations per se. The reason that it works is
* that we recognize the implicit intValue() call as a dereference.
*/
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(i);
int unused = ~i;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(i);
}
public void numercialOperations() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 + 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 - 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 * 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 / 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 % 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1.0 / 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1.0 % 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 << 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 >> 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 >>> 2);
int i = 1;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(+i);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(-i);
}
public void numericalOperationsAreDereferences(Integer i) {
// See bitwiseOperationsAreDereferences for some background.
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(i);
int unused = i + i;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(i);
}
public void numercialComparisons() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 < 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 > 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 <= 2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(1 >= 2);
}
public void numericalComparisonsAreDereferences(Integer a, Integer b) {
// See bitwiseOperationsAreDereferences for some background.
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(a);
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(b);
int unused = a + b;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(a);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(b);
}
public void vanillaVisitNode() {
String[] a = new String[1];
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(a[0]);
}
public void sameNameImmediatelyShadowed() {
final String s = "foo";
class Bar {
void method(String s) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(s);
}
}
}
public void sameNameLaterShadowed() {
final String s = "foo";
class Bar {
void method() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
String s = HasStaticFields.staticStringField;
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(s);
}
}
}
public void sameNameShadowedThenUnshadowed() {
final String s = HasStaticFields.staticStringField;
class Bar {
void method() {
{
String s = "foo";
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(s);
}
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(s);
}
}
}
public void nonCompileTimeConstantCapturedVariable() {
final Object nonnull = ENUM_INSTANCE;
class Bar {
void method() {
/*
* We'd prefer for this to be non-null, but we don't run the analysis over the enclosing
* class's enclosing method, so our captured-variable handling is limited to compile-time
* constants, which include only primitives and strings:
* http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28
*/
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(nonnull);
}
}
}
static class HasStaticFields {
static String staticStringField;
}
}
| 6,244
| 30.700508
| 129
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/testdata/NullnessPropagationTransferCases3.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.dataflow.nullnesspropagation.testdata;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessCheckerOnBoxed;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessCheckerOnPrimitive;
import com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest;
/**
* Dataflow analysis cases for testing transfer functions in nullness propagation around various
* kinds of expressions, method parameter and call handling, and loops.
*/
public class NullnessPropagationTransferCases3 {
public void casts() {
Object o = null;
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker((String) o);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed((int) o);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive((int) o);
o = "str";
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker((String) o);
}
public void literals() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive((byte) 1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive((short) 1000);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(33L);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(0.444f);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(0.5555d);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(true);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive('z');
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker("a string literal");
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(String.class);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(null);
}
public void autoboxed() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed((byte) 1);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed((short) 1000);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed(2);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed(33L);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed(0.444f);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed(0.5555d);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed(true);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnBoxed('z');
}
public void autounbox() {
Integer i = null;
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(i);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(i);
// Unboxing is a method call, so i must be non-null...
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(i);
}
public void parameter(String str, int i) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str);
// A call to plain triggerNullnessChecker() would implicitly call Integer.valueOf(i).
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(i);
}
public void assignment(String nullableParam) {
String str = nullableParam;
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(str);
str = "a string";
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str);
String otherStr = str;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str);
str = null;
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str);
otherStr = str;
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str);
}
public void assignmentExpressionValue() {
String str = "foo";
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str = null);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str = "bar");
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str);
str = null;
String str2 = null;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str = str2 = "bar");
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str2);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str = str2 = null);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str);
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(str2);
}
public void localVariable() {
short s;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(s = 1000); // narrowing conversion
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(s);
int i = 2;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(i);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(i = s); // widening conversion
String str = "a string literal";
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(str);
Object obj = null;
// BUG: Diagnostic contains: (Null)
triggerNullnessChecker(obj);
++i;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(i);
}
public void boxedPrimitives() {
Short s = 1000;
// BUG: Diagnostic contains: (Non-null)
NullnessPropagationTest.triggerNullnessChecker(s);
Integer i = 2;
// BUG: Diagnostic contains: (Non-null)
NullnessPropagationTest.triggerNullnessChecker(i);
}
public void nullableAssignmentToPrimitiveVariableExpressionValue() {
int i;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(i = boxedIntReturningMethod());
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(boxedIntReturningMethod());
}
public void methodInvocation() {
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(intReturningMethod());
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(stringReturningMethod());
}
private Integer boxedIntReturningMethod() {
return null;
}
private int intReturningMethod() {
return 0;
}
private String stringReturningMethod() {
return null;
}
public void objectCreation(Object nullableParam) {
Object obj = nullableParam;
obj = new Object();
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(obj);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessChecker(new Object[0]);
}
public void inc() {
int i = 0;
short s = 0;
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(i++);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(s++);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(++i);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(++s);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(i += 5);
// BUG: Diagnostic contains: (Non-null)
triggerNullnessCheckerOnPrimitive(s += 5);
}
public void loop1() {
Object o = null;
while (true) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(o);
o.hashCode();
}
}
public void loop2() {
Object o = null;
Object comingValue = null;
while (true) {
// BUG: Diagnostic contains: (Nullable)
triggerNullnessChecker(o);
o = comingValue;
comingValue = new Object();
}
}
}
| 8,757
| 30.963504
| 123
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/suppress/SuppressWarningsTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.suppress;
import static com.google.errorprone.FileObjects.forResources;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.ErrorProneTestCompiler;
import com.google.errorprone.bugpatterns.DeadException;
import com.google.errorprone.bugpatterns.EmptyIfStatement;
import com.google.errorprone.bugpatterns.SelfAssignment;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.tools.javac.main.Main.Result;
import javax.tools.JavaFileObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for standard {@code @SuppressWarnings} suppression method.
*
* @author alexeagle@google.com (Alex Eagle)
*/
@RunWith(JUnit4.class)
public class SuppressWarningsTest {
private ErrorProneTestCompiler compiler;
@Before
public void setUp() {
ScannerSupplier scannerSupplier =
ScannerSupplier.fromBugCheckerClasses(
DeadException.class, EmptyIfStatement.class, SelfAssignment.class);
compiler = new ErrorProneTestCompiler.Builder().report(scannerSupplier).build();
}
@Test
public void negativeCase() {
ImmutableList<JavaFileObject> sources =
forResources(getClass(), "SuppressWarningsNegativeCases.java");
assertThat(compiler.compile(sources), is(Result.OK));
}
}
| 2,052
| 33.216667
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/suppress/SuppressLintTest.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.suppress;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.FileObjects.forResources;
import static com.google.errorprone.FileObjects.forSourceLines;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.ErrorProneTestCompiler;
import com.google.errorprone.bugpatterns.DeadException;
import com.google.errorprone.bugpatterns.EmptyIfStatement;
import com.google.errorprone.bugpatterns.SelfAssignment;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.tools.javac.main.Main.Result;
import java.util.ArrayList;
import java.util.List;
import javax.tools.JavaFileObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@code @SuppressLint} suppression method. */
@RunWith(JUnit4.class)
public class SuppressLintTest {
private ErrorProneTestCompiler compiler;
@Before
public void setUp() {
ScannerSupplier scannerSupplier =
ScannerSupplier.fromBugCheckerClasses(
DeadException.class, EmptyIfStatement.class, SelfAssignment.class);
compiler = new ErrorProneTestCompiler.Builder().report(scannerSupplier).build();
}
@Test
public void negativeCase() {
ImmutableList<JavaFileObject> sources =
forResources(getClass(), "SuppressLintNegativeCases.java");
JavaFileObject stub =
forSourceLines(
"SuppressLint.java",
"package android.annotation;",
"public @interface SuppressLint {",
" public String[] value() default {};",
"}");
List<JavaFileObject> thingsToCompile = new ArrayList<>(sources);
thingsToCompile.add(stub);
assertThat(compiler.compile(thingsToCompile)).isEqualTo(Result.OK);
}
}
| 2,426
| 35.223881
| 84
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/suppress/CustomSuppressionTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.suppress;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ReturnTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit4.class)
public class CustomSuppressionTest {
/** Custom suppression annotation for both checkers in this test. */
public @interface SuppressBothCheckers {}
@BugPattern(
summary = "Test checker that uses a custom suppression annotation",
explanation = "Test checker that uses a custom suppression annotation",
suppressionAnnotations = SuppressBothCheckers.class,
severity = ERROR)
public static class MyChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
/** Custom suppression annotation for the second checker in this test. */
public @interface SuppressMyChecker2 {}
@BugPattern(
summary = "Test checker that accepts both custom suppression annotations",
explanation = "Test checker that accepts both custom suppression annotations",
suppressionAnnotations = {SuppressBothCheckers.class, SuppressMyChecker2.class},
severity = ERROR)
public static class MyChecker2 extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@Test
public void myCheckerIsNotSuppressedWithSuppressWarnings() {
CompilationTestHelper.newInstance(MyChecker.class, getClass())
.addSourceLines(
"Test.java",
"class Test {",
" @SuppressWarnings(\"MyChecker\")",
" int identity(int value) {",
" // BUG: Diagnostic contains:",
" return value;",
" }",
"}")
.doTest();
}
@Test
public void myCheckerIsSuppressedWithCustomAnnotation() {
CompilationTestHelper.newInstance(MyChecker.class, getClass())
.addSourceLines(
"Test.java",
"import com.google.errorprone.suppress.CustomSuppressionTest.SuppressBothCheckers;",
"class Test {",
" @SuppressBothCheckers",
" int identity(int value) {",
" return value;",
" }",
"}")
.doTest();
}
@Test
public void myCheckerIsSuppressedWithCustomAnnotationAtLocalVariableScope() {
CompilationTestHelper.newInstance(MyChecker.class, getClass())
.addSourceLines(
"Test.java",
"import com.google.errorprone.suppress.CustomSuppressionTest.SuppressBothCheckers;",
"class Test {",
" @SuppressBothCheckers",
" Comparable<Integer> myComparable = new Comparable<Integer>() {",
" @Override public int compareTo(Integer other) {",
" return -1;",
" }",
" };",
"}")
.doTest();
}
@Test
public void myCheckerIsNotSuppressedWithWrongCustomAnnotation() {
CompilationTestHelper.newInstance(MyChecker.class, getClass())
.addSourceLines(
"Test.java",
"import com.google.errorprone.suppress.CustomSuppressionTest.SuppressMyChecker2;",
"class Test {",
" @SuppressMyChecker2",
" int identity(int value) {",
" // BUG: Diagnostic contains:",
" return value;",
" }",
"}")
.doTest();
}
@Test
public void myChecker2IsSuppressedWithEitherCustomAnnotation() {
CompilationTestHelper.newInstance(MyChecker2.class, getClass())
.addSourceLines(
"Test.java",
"import com.google.errorprone.suppress.CustomSuppressionTest.SuppressBothCheckers;",
"import com.google.errorprone.suppress.CustomSuppressionTest.SuppressMyChecker2;",
"class Test {",
" @SuppressBothCheckers",
" int identity(int value) {",
" return value;",
" }",
" @SuppressMyChecker2",
" int square(int value) {",
" return value * value;",
" }",
"}")
.doTest();
}
}
| 5,314
| 34.198675
| 96
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/suppress/UnsuppressibleTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.suppress;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.FileObjects.forResources;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.DiagnosticTestHelper;
import com.google.errorprone.ErrorProneTestCompiler;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.source.tree.ReturnTree;
import com.sun.tools.javac.main.Main.Result;
import javax.tools.JavaFileObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Test for unsuppressible checks.
*
* @author eaftan@google.com (Eddie Aftandilan)
*/
@RunWith(JUnit4.class)
public class UnsuppressibleTest {
@BugPattern(
summary = "Test checker that is unsuppressible",
explanation = "Test checker that that is unsuppressible",
suppressionAnnotations = {},
severity = ERROR)
public static class MyChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
private ErrorProneTestCompiler compiler;
private DiagnosticTestHelper diagnosticHelper;
@Before
public void setUp() {
diagnosticHelper = new DiagnosticTestHelper();
compiler =
new ErrorProneTestCompiler.Builder()
.listenToDiagnostics(diagnosticHelper.collector)
.report(ScannerSupplier.fromBugCheckerClasses(MyChecker.class))
.build();
}
@Test
public void positiveCase() {
ImmutableList<JavaFileObject> sources =
forResources(getClass(), "UnsuppressiblePositiveCases.java");
assertThat(compiler.compile(sources), is(Result.ERROR));
assertThat(diagnosticHelper.getDiagnostics().toString(), containsString("[MyChecker]"));
}
}
| 2,889
| 33.819277
| 92
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/suppress/testdata/SuppressLintNegativeCases.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.suppress.testdata;
import android.annotation.SuppressLint;
/** Test cases to ensure SuppressLint annotation is respected. */
@SuppressLint("DeadException")
public class SuppressLintNegativeCases {
@SuppressLint({"EmptyIf", "EmptyStatement"})
public void testEmptyIf() {
int i = 0;
if (i == 10)
;
{
System.out.println("foo");
}
}
@SuppressLint({"bar", "SelfAssignment"})
public void testSelfAssignment() {
int i = 0;
i = i;
}
public void testDeadException() {
new RuntimeException("whoops");
}
}
| 1,195
| 25.577778
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/suppress/testdata/SuppressWarningsNegativeCases.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.suppress.testdata;
/**
* Test cases to ensure SuppressWarnings annotation is respected.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
@SuppressWarnings("DeadException")
public class SuppressWarningsNegativeCases {
@SuppressWarnings({"EmptyIf", "EmptyStatement"})
public void testEmptyIf() {
int i = 0;
if (i == 10)
;
{
System.out.println("foo");
}
}
@SuppressWarnings({"bar", "SelfAssignment"})
public void testSelfAssignment() {
int i = 0;
i = i;
}
public void testDeadException() {
new RuntimeException("whoops");
}
}
| 1,230
| 25.191489
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/suppress/testdata/UnsuppressiblePositiveCases.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.suppress.testdata;
/**
* Test cases to ensure that unsuppressible checks really are unsuppressible.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
public class UnsuppressiblePositiveCases {
@SuppressWarnings("MyChecker")
public void testUnsuppressible() {
return;
}
}
| 928
| 29.966667
| 77
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/testdata/CommandLineFlagTestFile.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.testdata;
public class CommandLineFlagTestFile {
public void foo() {
return;
}
}
| 729
| 29.416667
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/testdata/UsesAnnotationProcessor.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.testdata;
public class UsesAnnotationProcessor {}
| 690
| 33.55
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/testdata/FlowSub.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.testdata;
public class FlowSub extends FlowSuper {}
| 692
| 33.65
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/testdata/MultipleTopLevelClassesWithNoErrors.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.testdata;
public class MultipleTopLevelClassesWithNoErrors {
int foo;
int bar;
public MultipleTopLevelClassesWithNoErrors(int foo, int bar) {
this.foo = foo;
this.bar = bar;
}
private static class InnerFoo {}
}
final class Foo1 {
int foo;
int bar;
public Foo1(int foo, int bar) {
this.foo = foo;
this.bar = bar;
}
}
final class Foo2 {
int foo;
int bar;
public Foo2(int foo, int bar) {
this.foo = foo;
this.bar = bar;
}
}
final class Foo3 {
int foo;
int bar;
public Foo3(int foo, int bar) {
this.foo = foo;
this.bar = bar;
}
}
| 1,240
| 19.683333
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/testdata/FlowSuper.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.testdata;
import static com.google.errorprone.testdata.FlowConstants.*;
public class FlowSuper {
byte myByte = SOME_BYTE;
}
| 767
| 31
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/testdata/FlowConstants.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.testdata;
public final class FlowConstants {
public static final byte SOME_BYTE = 32;
}
| 730
| 32.227273
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/testdata/ExtendedMultipleTopLevelClassesWithNoErrors.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.testdata;
public class ExtendedMultipleTopLevelClassesWithNoErrors
extends MultipleTopLevelClassesWithNoErrors {
ExtendedMultipleTopLevelClassesWithNoErrors() {
super(0, 0);
}
}
| 830
| 32.24
| 75
|
java
|
error-prone
|
error-prone-master/core/src/test/java/com/google/errorprone/testdata/MultipleTopLevelClassesWithErrors.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.testdata;
public class MultipleTopLevelClassesWithErrors {}
final class Poo1 {
public int poo() {
int i = 10;
i = i;
return i;
}
class Poo2 {
public int poo() {
int i = 10;
i = i;
return i;
}
}
}
final class Poo3 {
public int poo() {
int i = 10;
i = i;
return i;
}
}
| 972
| 21.113636
| 75
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.