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
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ObjectArrayMapping.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.intset.OrdinalSetMapping; import java.util.HashMap; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.stream.Stream; import org.jspecify.annotations.Nullable; /** * A bit set mapping based on an immutable object array. This is not terribly efficient, but is * useful for prototyping. */ public class ObjectArrayMapping<T> implements OrdinalSetMapping<T> { private final T[] array; /** A mapping from object to Integer */ private final HashMap<T, Integer> map = HashMapFactory.make(); public ObjectArrayMapping(final T[] array) { if (array == null) { throw new IllegalArgumentException("null array"); } this.array = array; for (int i = 0; i < array.length; i++) { map.put(array[i], i); } } @Override public T getMappedObject(int n) throws NoSuchElementException { try { return array[n]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid n: " + n, e); } } @Override public int getMappedIndex(@Nullable Object o) { if (map.get(o) == null) { return -1; } return map.get(o); } @Override public boolean hasMappedIndex(Object o) { return map.get(o) != null; } @Override public Iterator<T> iterator() { return map.keySet().iterator(); } @Override public Stream<T> stream() { return map.keySet().stream(); } @Override public int add(Object o) throws UnimplementedError { Assertions.UNREACHABLE(); return 0; } @Override public int getMaximumIndex() { return array.length - 1; } @Override public int getSize() { return map.size(); } }
2,207
23.263736
95
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ObjectVisitor.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.util.collections; public interface ObjectVisitor<T> { void visit(T obj_); }
2,019
44.909091
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/Pair.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import com.ibm.wala.util.debug.Assertions; import java.io.Serializable; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; public class Pair<T, U> implements Serializable { private static final long serialVersionUID = 1861211857872739247L; public final T fst; public final U snd; protected Pair(T fst, U snd) { this.fst = fst; this.snd = snd; } private static boolean check(Object x, Object y) { return Objects.equals(x, y); } @SuppressWarnings("rawtypes") @Override public boolean equals(Object o) { return (o instanceof Pair) && check(fst, ((Pair) o).fst) && check(snd, ((Pair) o).snd); } private static int hc(Object o) { return (o == null) ? 0 : o.hashCode(); } @Override public int hashCode() { return hc(fst) * 7219 + hc(snd); } public Iterator<Object> iterator() { return new Iterator<>() { byte nextFlag = 1; @Override public boolean hasNext() { return nextFlag > 0; } @Override public Object next() { switch (nextFlag) { case 1: nextFlag++; return fst; case 2: nextFlag = 0; return snd; default: throw new NoSuchElementException(); } } @Override public void remove() { Assertions.UNREACHABLE(); } }; } @Override public String toString() { return "[" + fst + ',' + snd + ']'; } public static <T, U> Pair<T, U> make(T x, U y) { return new Pair<>(x, y); } }
2,003
21.772727
91
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ParanoidHashMap.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import com.ibm.wala.util.debug.UnimplementedError; import java.lang.reflect.Method; import java.util.LinkedHashMap; import java.util.Map; /** * a debugging aid. This implementation complains if you stick an object in here which appears to * use System.identityHashCode() */ public class ParanoidHashMap<K, V> extends LinkedHashMap<K, V> { public static final long serialVersionUID = 909018793791787198L; /** @throws NullPointerException if t is null */ public ParanoidHashMap(Map<K, V> t) throws NullPointerException { super(t.size()); putAll(t); } public ParanoidHashMap(int size) { super(size); } public ParanoidHashMap() {} /** @see java.util.Map#put(java.lang.Object, java.lang.Object) */ @Override public V put(K arg0, V arg1) { assertOverridesHashCode(arg0); return super.put(arg0, arg1); } public static void assertOverridesHashCode(Object o) throws UnimplementedError { if (o != null && o.hashCode() == System.identityHashCode(o)) { try { Method method = o.getClass().getMethod("hashCode"); if (method.getDeclaringClass() == Object.class) { assert false : o.getClass().toString(); } } catch (Exception e) { assert false : "Could not find hashCode method"; } } } /** @see java.util.Map#putAll(java.util.Map) */ @Override public void putAll(Map<? extends K, ? extends V> arg0) { if (arg0 == null) { throw new IllegalArgumentException("arg0 is null"); } for (Map.Entry<? extends K, ? extends V> E : arg0.entrySet()) { put(E.getKey(), E.getValue()); } } }
2,035
28.941176
97
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ParanoidHashSet.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import com.ibm.wala.util.debug.UnimplementedError; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; /** * a debugging aid. This implementation complains if you stick an object in here which appears to * use System.identityHashCode(), or if it detects more than BAD_HC collisions in the Set (possibly * indicated a bad hash function) */ public class ParanoidHashSet<T> extends LinkedHashSet<T> { public static final long serialVersionUID = 30919839181133333L; /** A mapping from Integer (hashcode) -&gt; Set of objects */ private final Map<Integer, Set<T>> hcFreq; /** If a hash set contains more than this number of items with the same hash code, complain. */ private final int BAD_HC = 3; /** @throws NullPointerException if s is null */ public ParanoidHashSet(Collection<T> s) throws NullPointerException { super(s.size()); hcFreq = HashMapFactory.make(s.size()); this.addAll(s); } /** */ public ParanoidHashSet() { super(); hcFreq = HashMapFactory.make(); } public ParanoidHashSet(int size) { super(size); hcFreq = HashMapFactory.make(size); } /** * @see java.util.Collection#add(java.lang.Object) * @throws UnimplementedError if there's a bad hash code problem */ @Override public boolean add(T arg0) { if (arg0 == null) { throw new IllegalArgumentException("arg0 is null"); } ParanoidHashMap.assertOverridesHashCode(arg0); boolean result = super.add(arg0); if (result) { int hc = arg0.hashCode(); Set<T> s = hcFreq.get(hc); if (s == null) { HashSet<T> h = new LinkedHashSet<>(1); h.add(arg0); hcFreq.put(hc, h); } else { if (s.size() == BAD_HC) { for (T t : s) { Object o = t; System.err.println(o + " " + o.hashCode()); } assert false : "bad hc " + arg0.getClass() + ' ' + arg0; } else { s.add(arg0); } } } return result; } }
2,489
27.62069
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ReverseIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; /** An iterator that reverses an input iterator. Not very efficient. */ public class ReverseIterator<T> implements Iterator<T> { final ArrayList<T> list = new ArrayList<>(); int nextIndex; /** * @param other the iterator to reverse * @throws IllegalArgumentException if other == null */ private ReverseIterator(Iterator<T> other) throws IllegalArgumentException { if (other == null) { throw new IllegalArgumentException("other == null"); } while (other.hasNext()) { list.add(other.next()); } nextIndex = list.size() - 1; } @Override public boolean hasNext() { return nextIndex > -1; } @Override public T next() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException(); } return list.get(nextIndex--); } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } public static <T> Iterator<T> reverse(Iterator<T> it) { return new ReverseIterator<>(it); } }
1,562
25.05
78
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/SimpleVector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** simple implementation of IVector */ public class SimpleVector<T> implements IVector<T> { private static final int MAX_SIZE = Integer.MAX_VALUE / 4; private static final double GROWTH_FACTOR = 1.5; Object[] store = new Object[1]; int maxIndex = -1; public SimpleVector() {} /** @see com.ibm.wala.util.intset.IntVector#get(int) */ @NullUnmarked @Override @SuppressWarnings("unchecked") public T get(int x) { if (x < 0) { throw new IllegalArgumentException("illegal x: " + x); } if (x < store.length) { return (T) store[x]; } else { return null; } } /** @see com.ibm.wala.util.intset.IntVector#set(int, int) */ @Override public void set(int x, @Nullable T value) { if (x < 0) { throw new IllegalArgumentException("illegal x value " + x); } if (x > MAX_SIZE) { throw new IllegalArgumentException("x is too big: " + x); } maxIndex = Math.max(maxIndex, x); if (value == null) { if (x >= store.length) { return; } else { store[x] = null; } } else { ensureCapacity(x); store[x] = value; } } /** make sure we can store to a particular index */ private void ensureCapacity(int capacity) { if (capacity >= store.length) { store = Arrays.copyOf(store, 1 + (int) (GROWTH_FACTOR * capacity)); } } @Override public void performVerboseAction() { System.err.println(("size: " + store.length)); System.err.println(("occupancy: " + computeOccupancy())); } /** @return the percentage of entries in delegateStore that are non-null */ private double computeOccupancy() { int count = 0; for (Object element : store) { if (element != null) { count++; } } return (double) count / (double) store.length; } @Override @SuppressWarnings("unchecked") public Iterator<T> iterator() { ArrayList<T> result = new ArrayList<>(); for (int i = 0; i <= maxIndex; i++) { result.add((T) store[i]); } return result.iterator(); } @Override public int getMaxIndex() { return maxIndex; } }
2,727
24.259259
77
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/SmallMap.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import com.ibm.wala.util.debug.Assertions; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** * A simple implementation of Map; intended for Maps with few elements. Optimized for space, not * time -- use with care. */ public class SmallMap<K, V> implements Map<K, V> { private static final boolean DEBUG_USAGE = false; private static final int DEBUG_MAX_SIZE = 20; // this Map contains keysAndValues.length / 2 entries. // in the following array, entries 0 ... keysAndValues.length/2 - 1 are keys. // entries keysAndValues.length/2 .. keysAndValues.length are values. @SuppressWarnings("NullAway.Init") private Object[] keysAndValues; /* */ @Override public int size() { if (keysAndValues == null) { return 0; } else { return keysAndValues.length / 2; } } /** * Use with care. * * @return the ith key */ @SuppressWarnings("unchecked") public K getKey(int i) throws IllegalStateException { if (keysAndValues == null) { throw new IllegalStateException("getKey on empty map"); } try { return (K) keysAndValues[i]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("invalid i: " + i, e); } } /** * Use with care. * * @return the ith key */ @SuppressWarnings("unchecked") public V getValue(int i) throws IllegalStateException { if (keysAndValues == null) { throw new IllegalStateException("getValue on empty map"); } try { return (V) keysAndValues[size() + i]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("illegal i: " + i, e); } } @Override public boolean isEmpty() { return (keysAndValues == null); } @Override public boolean containsKey(Object key) { for (int i = 0; i < size(); i++) { if (keysAndValues[i].equals(key)) { return true; } } return false; } @Override public boolean containsValue(Object value) { if (keysAndValues == null) { return false; } for (int i = size(); i < keysAndValues.length; i++) { Object v = keysAndValues[i]; if (v == null) { if (value == null) { return true; } } else { if (v.equals(value)) { return true; } } } return false; } @NullUnmarked @Override @SuppressWarnings("unchecked") public V get(Object key) { if (key != null) for (int i = 0; i < size(); i++) { if (keysAndValues[i] != null && keysAndValues[i].equals(key)) { return (V) keysAndValues[size() + i]; } } return null; } private void growByOne() { if (keysAndValues == null) keysAndValues = new Object[2]; else { final int oldLength = keysAndValues.length; final int oldEntryCount = oldLength / 2; final int oldLastKeySlot = oldEntryCount - 1; final int oldFirstValueSlot = oldLastKeySlot + 1; final int newLength = oldLength + 2; final int newEntryCount = newLength / 2; final int newLastKeySlot = newEntryCount - 1; final int newFirstValueSlot = newLastKeySlot + 1; keysAndValues = Arrays.copyOf(keysAndValues, newLength); System.arraycopy( keysAndValues, oldFirstValueSlot, keysAndValues, newFirstValueSlot, oldEntryCount); keysAndValues[newLastKeySlot] = null; } } @Nullable @Override @SuppressWarnings({"unchecked", "unused"}) public V put(Object key, Object value) { if (key == null) { throw new IllegalArgumentException("null key"); } for (int i = 0; i < size(); i++) { if (keysAndValues[i] != null && keysAndValues[i].equals(key)) { V result = (V) keysAndValues[size() + i]; keysAndValues[size() + i] = value; return result; } } if (DEBUG_USAGE && size() >= DEBUG_MAX_SIZE) { Assertions.UNREACHABLE("too many elements in a SmallMap"); } growByOne(); keysAndValues[size() - 1] = key; keysAndValues[keysAndValues.length - 1] = value; return null; } @Override public V remove(Object key) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends K, ? extends V> t) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @NullUnmarked @Override public void clear() { keysAndValues = null; } @Override public Set<K> keySet() { //noinspection rawtypes return new SlotIteratingSet<>() { @Override protected K getItemInSlot(int slot) { return getKey(slot); } }; } @Override public Collection<V> values() { //noinspection rawtypes return new SlotIteratingSet<>() { @Override protected V getItemInSlot(int slot) { return getValue(slot); } }; } @Override public Set<Map.Entry<K, V>> entrySet() { //noinspection rawtypes return new SlotIteratingSet<>() { @Override protected Entry<K, V> getItemInSlot(int slot) { return new AbstractMap.SimpleEntry<>(getKey(slot), getValue(slot)); } }; } /** * Minimally functional {@link Set} that iterates over array slots. * * @param <E> the type of elements maintained by this set */ private abstract class SlotIteratingSet<E> extends AbstractSet<E> { @Override public Iterator<E> iterator() { return new SlotIterator(); } @Override public int size() { return SmallMap.this.size(); } private class SlotIterator implements Iterator<E> { private int nextSlot = 0; @Override public boolean hasNext() { return nextSlot < SmallMap.this.size(); } @Override public E next() { final E result; try { result = getItemInSlot(nextSlot); } catch (IllegalStateException | IllegalArgumentException problem) { throw new NoSuchElementException(problem.getMessage()); } ++nextSlot; return result; } } protected abstract E getItemInSlot(int slot); } }
6,851
24.377778
96
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/SparseVector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.MutableSparseIntSet; import com.ibm.wala.util.intset.TunedMutableSparseIntSet; import java.io.Serializable; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** * An {@link IVector} implementation designed for low occupancy. Note that get() from this vector is * a binary search. * * <p>This should only be used for small sets ... insertion and deletion are linear in size of set. */ public class SparseVector<T> implements IVector<T>, Serializable { private static final long serialVersionUID = -6220164684358954867L; private static final int DEF_INITIAL_SIZE = 5; /** if indices[i] = x, then data[i] == get(x) */ private MutableSparseIntSet indices = MutableSparseIntSet.makeEmpty(); private Object[] data; public SparseVector() { data = new Object[DEF_INITIAL_SIZE]; indices = MutableSparseIntSet.makeEmpty(); } public SparseVector(int initialSize, float expansion) { data = new Object[DEF_INITIAL_SIZE]; indices = new TunedMutableSparseIntSet(initialSize, expansion); } /** @see com.ibm.wala.util.intset.IntVector#get(int) */ @NullUnmarked @Override @SuppressWarnings("unchecked") public T get(int x) { int index = indices.getIndex(x); if (index == -1) { return null; } else { return (T) data[index]; } } /** * TODO: this can be optimized * * @see com.ibm.wala.util.intset.IntVector#set(int, int) */ @Override public void set(int x, @Nullable T value) { int index = indices.getIndex(x); if (index == -1) { indices.add(x); index = indices.getIndex(x); ensureCapacity(indices.size() + 1); if (index < (data.length - 1)) { System.arraycopy(data, index, data, index + 1, indices.size() - index); } } data[index] = value; } private void ensureCapacity(int capacity) { if (data.length < capacity + 1) { data = Arrays.copyOf(data, 1 + (int) (capacity * indices.getExpansionFactor())); } } /** @see com.ibm.wala.util.debug.VerboseAction#performVerboseAction() */ @Override public void performVerboseAction() { System.err.println((getClass() + " stats: ")); System.err.println(("data.length " + data.length)); System.err.println(("indices.size() " + indices.size())); } /** @see com.ibm.wala.util.intset.IntSet#intIterator() */ @Override public Iterator<T> iterator() { return new Iterator<>() { int i = 0; @Override public boolean hasNext() { return i < indices.size(); } @Override @SuppressWarnings("unchecked") public T next() { if (!hasNext()) { throw new NoSuchElementException(); } return (T) data[i++]; } @Override public void remove() { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } }; } /** @return max i s.t get(i) != null */ @Override public int getMaxIndex() throws IllegalStateException { return indices.max(); } public int size() { return indices.size(); } public IntIterator iterateIndices() { return indices.intIterator(); } /** * This iteration _will_ cover all indices even when remove is called while the iterator is * active. */ public IntIterator safeIterateIndices() { return MutableSparseIntSet.make(indices).intIterator(); } public void clear() { data = new Object[DEF_INITIAL_SIZE]; indices = MutableSparseIntSet.makeEmpty(); } public void remove(int x) { int index = indices.getIndex(x); if (index == -1) { return; } else { System.arraycopy(data, index + 1, data, index, size() - index - 1); indices.remove(x); } } }
4,372
25.828221
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ToStringComparator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import java.util.Comparator; /** A comparator based on lexicographical ordering of toString() */ public class ToStringComparator<T> implements Comparator<T> { @SuppressWarnings("rawtypes") private static final ToStringComparator INSTANCE = new ToStringComparator(); private ToStringComparator() {} @Override public int compare(T o1, T o2) throws NullPointerException { // by convention, null is the least element if (o1 == null) { return o2 == null ? 0 : -1; } else if (o2 == null) { return 1; } return o1.toString().compareTo(o2.toString()); } public static <T> ToStringComparator<T> instance() { return INSTANCE; } }
1,091
27.736842
78
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/TwoLevelVector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.collections; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.math.Logs; import java.io.Serializable; import java.util.Iterator; import java.util.Vector; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** An {@link IVector} implementation which delegates to pages of int vectors. */ public class TwoLevelVector<T> implements IVector<T>, Serializable { private static final long serialVersionUID = -835376054736611070L; private static final int PAGE_SIZE = 4096; private static final int LOG_PAGE_SIZE = Logs.log2(PAGE_SIZE); /** Array of IVector: data.get(i) holds data[i*PAGE_SIZE] ... data[(i+1)*PAGESIZE - 1] */ @SuppressWarnings("JdkObsolete") // uses Vector-specific APIs private final Vector<SparseVector<T>> data = new Vector<>(0); private int maxPage = -1; /** @see com.ibm.wala.util.intset.IntVector#get(int) */ @NullUnmarked @Nullable @Override public T get(int x) { if (x < 0) { throw new IllegalArgumentException("invalid x: " + x); } int page = getPageNumber(x); if (page >= data.size()) { return null; } IVector<T> v = data.get(page); if (v == null) { return null; } int localX = x - getFirstIndexOnPage(page); return v.get(localX); } private static int getFirstIndexOnPage(int page) { return page << LOG_PAGE_SIZE; } private static int getPageNumber(int x) { return x >> LOG_PAGE_SIZE; } /* * TODO: this can be optimized * * @see com.ibm.wala.util.intset.IntVector#set(int, int) */ @Override public void set(int x, @Nullable T value) { if (x < 0) { throw new IllegalArgumentException("illegal x: " + x); } int page = getPageNumber(x); IVector<T> v = findOrCreatePage(page); int localX = toLocalIndex(x, page); v.set(localX, value); } private static int toLocalIndex(int x, int page) { return x - getFirstIndexOnPage(page); } private IVector<T> findOrCreatePage(int page) { if (page >= data.size()) { SparseVector<T> v = new SparseVector<>(); data.setSize(page + 1); data.add(page, v); maxPage = Math.max(page, maxPage); return v; } else { SparseVector<T> v = data.get(page); if (v == null) { v = new SparseVector<>(); data.set(page, v); maxPage = Math.max(page, maxPage); } return v; } } /** @see com.ibm.wala.util.debug.VerboseAction#performVerboseAction() */ @Override public void performVerboseAction() { // do nothing; } /** @see com.ibm.wala.util.intset.IntSet#intIterator() */ @Override public Iterator<T> iterator() { return new Iterator<>() { final Iterator<SparseVector<T>> outer = data.iterator(); @Nullable Iterator<T> inner; { while (outer.hasNext()) { IVector<T> v = outer.next(); if (v != null) { Iterator<T> it = v.iterator(); if (it.hasNext()) { inner = it; break; } } } } @Override public boolean hasNext() { return inner != null; } @NullUnmarked @Override public T next() { T result = inner.next(); if (!inner.hasNext()) { inner = null; while (outer.hasNext()) { IVector<T> v = outer.next(); if (v != null) { Iterator<T> it = v.iterator(); if (it.hasNext()) { inner = it; break; } } } } return result; } @Override public void remove() { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } }; } @Override public int getMaxIndex() { if (maxPage == -1) { return -1; } else { IVector<T> v = data.get(maxPage); int localMax = v.getMaxIndex(); return maxPage * PAGE_SIZE + localMax; } } }
4,421
24.560694
91
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/collections/Util.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.util.collections; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.security.Permission; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import org.jspecify.annotations.Nullable; /** Miscellaneous utility functions. */ public class Util { /** The empty {@link BitSet}. */ public static final BitSet EMPTY_BITSET = new BitSet(); /** * Get a {@link String} representation of a {@link Throwable}. * * @throws IllegalArgumentException if thrown == null */ public static String str(Throwable thrown) throws IllegalArgumentException { if (thrown == null) { throw new IllegalArgumentException("thrown == null"); } // create a memory buffer to which to dump the trace ByteArrayOutputStream traceDump = new ByteArrayOutputStream(); try (final PrintWriter w = new PrintWriter( new BufferedWriter(new OutputStreamWriter(traceDump, StandardCharsets.UTF_8)))) { thrown.printStackTrace(w); } return traceDump.toString(); } /** Return those elements of {@code c} that are assignable to {@code klass}. */ @SuppressWarnings("unchecked") public static <S, T> Set<T> filterByType(Iterable<S> c, Class<T> klass) { Set<T> result = HashSetFactory.make(); for (S s : c) if (klass.isAssignableFrom(s.getClass())) result.add((T) s); return result; } /** * Test whether <em>some</em> element of the given {@link Collection} satisfies the given {@link * Predicate}. * * @throws IllegalArgumentException if c == null */ public static <T> boolean forSome(Collection<T> c, Predicate<T> p) throws IllegalArgumentException { if (c == null) { throw new IllegalArgumentException("c == null"); } for (T t : c) { if (p.test(t)) { return true; } } return false; } /** * Test whether <em>some</em> element of the given {@link Collection} satisfies the given {@link * Predicate}. * * @return The first element satisfying the predicate; otherwise null. * @throws IllegalArgumentException if c == null */ @Nullable public static <T> T find(Collection<T> c, Predicate<T> p) throws IllegalArgumentException { if (c == null) { throw new IllegalArgumentException("c == null"); } for (T obj : c) { if (p.test(obj)) return obj; } return null; } /** * Test whether <em>all</em> elements of the given {@link Collection} satisfy the given {@link * Predicate}. * * @throws NullPointerException if c == null */ public static <T> boolean forAll(Collection<T> c, Predicate<T> p) throws NullPointerException { for (T t : c) { if (!p.test(t)) return false; } return true; } /** * Perform an action for all elements in a collection. * * @param c the collection * @param v the visitor defining the action * @throws IllegalArgumentException if c == null */ public static <T> void doForAll(Collection<T> c, ObjectVisitor<T> v) throws IllegalArgumentException { if (c == null) { throw new IllegalArgumentException("c == null"); } for (T t : c) v.visit(t); } /** * Map a list: generate a new list with each element mapped. The new list is always an {@link * ArrayList}; it would have been more precise to use {@link java.lang.reflect reflection} to * create a list of the same type as 'srcList', but reflection works really slowly in some * implementations, so it's best to avoid it. * * @throws IllegalArgumentException if srcList == null */ public static <T, U> List<U> map(List<T> srcList, Function<T, U> f) throws IllegalArgumentException { if (srcList == null) { throw new IllegalArgumentException("srcList == null"); } ArrayList<U> result = new ArrayList<>(); for (T t : srcList) { result.add(f.apply(t)); } return result; } /** * Map a set: generate a new set with each element mapped. The new set is always a {@link * HashSet}; it would have been more precise to use {@link java.lang.reflect reflection} to create * a set of the same type as 'srcSet', but reflection works really slowly in some implementations, * so it's best to avoid it. * * @throws IllegalArgumentException if srcSet == null */ public static <T, U> Set<U> mapToSet(Collection<T> srcSet, Function<T, U> f) throws IllegalArgumentException { if (srcSet == null) { throw new IllegalArgumentException("srcSet == null"); } HashSet<U> result = HashSetFactory.make(); for (T t : srcSet) { result.add(f.apply(t)); } return result; } /* * Grow an int[] -- i.e. allocate a new array of the given size, with the initial segment equal to this int[]. */ public static int[] realloc(int[] data, int newSize) throws IllegalArgumentException { if (data == null) { throw new IllegalArgumentException("data == null"); } if (data.length < newSize) { return Arrays.copyOf(data, newSize); } else return data; } /** Generate strings with fully qualified names or not */ public static final boolean FULLY_QUALIFIED_NAMES = false; /** * Write object fields to string * * @throws IllegalArgumentException if obj == null */ public static String objectFieldsToString(Object obj) throws IllegalArgumentException { if (obj == null) { throw new IllegalArgumentException("obj == null"); } // Temporarily disable the security manager SecurityManager oldsecurity = System.getSecurityManager(); System.setSecurityManager( new SecurityManager() { @Override public void checkPermission(Permission perm) {} }); Class<?> c = obj.getClass(); StringBuilder buf = new StringBuilder(FULLY_QUALIFIED_NAMES ? c.getName() : removePackageName(c.getName())); while (c != Object.class) { Field[] fields = c.getDeclaredFields(); if (fields.length > 0) buf = buf.append(" ("); for (int i = 0; i < fields.length; i++) { // Make this field accessible fields[i].setAccessible(true); try { Class<?> type = fields[i].getType(); String name = fields[i].getName(); Object value = fields[i].get(obj); // name=value : type buf = buf.append(name); buf = buf.append('='); buf = buf.append(value == null ? "null" : value.toString()); buf = buf.append(" : "); buf = buf.append( FULLY_QUALIFIED_NAMES ? type.getName() : removePackageName(type.getName())); } catch (IllegalAccessException e) { e.printStackTrace(); } buf = buf.append(i + 1 >= fields.length ? ")" : ","); } c = c.getSuperclass(); } // Reinstate the security manager System.setSecurityManager(oldsecurity); return buf.toString(); } /** Remove the package name from a fully qualified class name */ @Nullable public static String removePackageName(String fully_qualified_name_) { if (fully_qualified_name_ == null) return null; int lastdot = fully_qualified_name_.lastIndexOf('.'); if (lastdot < 0) { return ""; } else { return fully_qualified_name_.substring(lastdot + 1); } } /** * checks if two sets have a non-empty intersection * * @return {@code true} if the sets intersect; {@code false} otherwise */ public static <T> boolean intersecting(final Set<T> s1, final Set<T> s2) { return forSome(s1, s2::contains); } /** * given the name of a class C, returns the name of the top-most enclosing class of class C. For * example, given A$B$C, the method returns A * * @return String name of top-most enclosing class * @throws IllegalArgumentException if typeStr == null */ public static String topLevelTypeString(String typeStr) throws IllegalArgumentException { if (typeStr == null) { throw new IllegalArgumentException("typeStr == null"); } int dollarIndex = typeStr.indexOf('$'); String topLevelTypeStr = dollarIndex == -1 ? typeStr : typeStr.substring(0, dollarIndex); return topLevelTypeStr; } public static <T> void addIfNotNull(T val, Collection<T> vals) { if (val != null) { vals.add(val); } } /** * @return the amount of memory currently being used, in bytes. Often inaccurate, but there's no * better thing to do from within the JVM. */ public static long getUsedMemory() { gc(); long totalMemory = Runtime.getRuntime().totalMemory(); gc(); long freeMemory = Runtime.getRuntime().freeMemory(); long usedMemory = totalMemory - freeMemory; return usedMemory; } private static void gc() { try { for (int i = 0; i < 2; i++) { System.gc(); Thread.sleep(100); System.runFinalization(); Thread.sleep(100); } } catch (Exception e) { e.printStackTrace(); } } } // class Util
11,296
32.324484
112
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/config/FileOfClasses.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.config; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jspecify.annotations.Nullable; /** An object which represents a set of classes read from a text file. */ public class FileOfClasses extends SetOfClasses { /* Serial version */ private static final long serialVersionUID = -3256390509887654322L; private static final boolean DEBUG = false; @Nullable private Pattern pattern = null; @Nullable private String regex = null; private boolean needsCompile = false; public FileOfClasses(InputStream input) throws IOException { if (input == null) { throw new IllegalArgumentException("null input"); } try (final BufferedReader is = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) { StringBuilder regex = null; String line; while ((line = is.readLine()) != null) { if (line.startsWith("#")) continue; if (regex == null) { regex = new StringBuilder('(' + line + ')'); } else { regex.append("|(").append(line).append(')'); } } if (regex != null) { this.regex = regex.toString(); needsCompile = true; } } } private void compile() { pattern = Pattern.compile(regex); needsCompile = false; } @Override public boolean contains(String klassName) { if (needsCompile) { compile(); } if (pattern == null) { return false; } Matcher m = pattern.matcher(klassName); if (DEBUG) { if (m.matches()) { System.err.println(klassName + ' ' + true); } else { System.err.println(klassName + ' ' + false); } } return m.matches(); } @Override public void add(String klass) { if (klass == null) { throw new IllegalArgumentException("klass is null"); } if (regex == null) { regex = klass; } else { regex = regex + '|' + klass; } needsCompile = true; } @Nullable @Override public String toString() { return this.regex; } }
2,630
23.820755
83
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/config/SetOfClasses.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.config; import java.io.Serializable; import java.util.Set; /** * Logically, a set of {@link Class}. * * <p>TODO: why does this not extend {@link Set}? Is there a good reason anymore? */ public abstract class SetOfClasses implements Serializable { private static final long serialVersionUID = -3048222852073799533L; public abstract boolean contains(String klassName); public abstract void add(String klass); }
825
27.482759
81
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/debug/Assertions.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.debug; /** * WALA-specific assertion checking. * * <p>This may go away in favor of Java language-level assertions. */ public class Assertions { /** * An assertion which does not need to be guarded by verifyAssertions. These assertions will be * enabled in production! * * @throws UnimplementedError if b == false */ public static void productionAssertion(boolean b, String string) throws UnimplementedError { if (!b) throw new UnimplementedError(string); } /** * An assertion which does not need to be guarded by verifyAssertions. These assertions will be * enabled in production! * * @throws UnimplementedError if b == false */ public static void productionAssertion(boolean b) throws UnimplementedError { if (!b) throw new UnimplementedError(); } /** * An assertion to call when reaching a point that should not be reached. * * @throws UnimplementedError unconditionally */ public static void UNREACHABLE() { throw new UnimplementedError(); } /** * An assertion to call when reaching a point that should not be reached. * * @throws UnimplementedError unconditionally */ public static void UNREACHABLE(String string) { throw new UnimplementedError(string); } /** * An assertion to call when reaching a point that should not be reached. * * @throws UnimplementedError unconditionally */ public static void UNREACHABLE(Object o) { throw new UnimplementedError(o == null ? "" : o.toString()); } }
1,922
27.701493
97
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/debug/LoggingStopwatch.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.debug; /** * A stop watch that prints log messages. * * @author mschaefer */ public class LoggingStopwatch { private long start; /** Start the stopwatch. */ public void start() { this.start = System.nanoTime(); } /** * Mark the completion of a task, print the time it took to complete, and optionally restart the * stopwatch. * * @param msg message to print * @param reset whether to restart the stopwatch * @return the elapsed time in milliseconds */ public long mark(String msg, boolean reset) { long end = System.nanoTime(); long elapsed = (end - start) / 1000000; System.out.println(msg + ": " + elapsed + "ms"); if (reset) start(); return elapsed; } /** * Convenience method that invokes {@link #mark(String, boolean)} with {@code true} as its second * argument. */ public long mark(String msg) { return mark(msg, true); } }
1,310
25.22
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/debug/UnimplementedError.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.debug; /** Something that's not implemented yet. */ public class UnimplementedError extends Error { public static final long serialVersionUID = 20981098918191L; public UnimplementedError() { super(); } public UnimplementedError(String s) { super(s); } }
677
25.076923
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/debug/VerboseAction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.debug; /** * An optional interface for data structures that provide a verbose option for debugging purposes. */ public interface VerboseAction { /** optional method used for performance debugging */ void performVerboseAction(); }
638
30.95
98
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/AbstractGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.collections.Iterator2Iterable; import java.util.Iterator; import java.util.stream.Stream; import org.jspecify.annotations.Nullable; /** Basic functionality for a {@link Graph} that delegates node and edge management. */ public abstract class AbstractGraph<T> implements Graph<T> { /** @return the object which manages nodes in the graph */ protected abstract NodeManager<T> getNodeManager(); /** @return the object which manages edges in the graph */ protected abstract EdgeManager<T> getEdgeManager(); @Override public Stream<T> stream() { return getNodeManager().stream(); } /** @see Graph#iterator() */ @Override public Iterator<T> iterator() { return getNodeManager().iterator(); } /** @see com.ibm.wala.util.graph.Graph#getNumberOfNodes() */ @Override public int getNumberOfNodes() { return getNodeManager().getNumberOfNodes(); } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(java.lang.Object) */ @Override public int getPredNodeCount(T n) throws IllegalArgumentException { if (n == null) { throw new IllegalArgumentException("n cannot be null"); } return getEdgeManager().getPredNodeCount(n); } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(java.lang.Object) */ @Override public Iterator<T> getPredNodes(@Nullable T n) throws IllegalArgumentException { if (n == null) { throw new IllegalArgumentException("n cannot be null"); } return getEdgeManager().getPredNodes(n); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(java.lang.Object) */ @Override public int getSuccNodeCount(T n) throws IllegalArgumentException { if (!containsNode(n) || n == null) { throw new IllegalArgumentException("node not in graph " + n); } return getEdgeManager().getSuccNodeCount(n); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(java.lang.Object) */ @Override public Iterator<T> getSuccNodes(@Nullable T n) throws IllegalArgumentException { if (n == null) { throw new IllegalArgumentException("n cannot be null"); } return getEdgeManager().getSuccNodes(n); } /** @see com.ibm.wala.util.graph.NodeManager#addNode(Object) */ @Override public void addNode(T n) { getNodeManager().addNode(n); } /** @see com.ibm.wala.util.graph.EdgeManager#addEdge(Object, Object) */ @Override public void addEdge(T src, T dst) throws IllegalArgumentException { getEdgeManager().addEdge(src, dst); } /** @see com.ibm.wala.util.graph.EdgeManager#removeEdge(java.lang.Object, java.lang.Object) */ @Override public void removeEdge(T src, T dst) throws IllegalArgumentException { getEdgeManager().removeEdge(src, dst); } /** @see com.ibm.wala.util.graph.EdgeManager#hasEdge(java.lang.Object, java.lang.Object) */ @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { if (src == null) { throw new IllegalArgumentException("src is null"); } if (dst == null) { throw new IllegalArgumentException("dst is null"); } return getEdgeManager().hasEdge(src, dst); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeAllIncidentEdges(T node) throws IllegalArgumentException { if (node == null) { throw new IllegalArgumentException("node cannot be null"); } getEdgeManager().removeAllIncidentEdges(node); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeIncomingEdges(T node) throws IllegalArgumentException { if (node == null) { throw new IllegalArgumentException("node cannot be null"); } getEdgeManager().removeIncomingEdges(node); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeOutgoingEdges(T node) throws IllegalArgumentException { if (node == null) { throw new IllegalArgumentException("node cannot be null"); } getEdgeManager().removeOutgoingEdges(node); } /** @see com.ibm.wala.util.graph.Graph#removeNode(Object) */ @Override public void removeNodeAndEdges(T N) throws IllegalArgumentException { if (N == null) { throw new IllegalArgumentException("N cannot be null"); } getEdgeManager().removeAllIncidentEdges(N); getNodeManager().removeNode(N); } /** @see com.ibm.wala.util.graph.NodeManager#removeNode(Object) */ @Override public void removeNode(T n) throws IllegalArgumentException { if (n == null) { throw new IllegalArgumentException("N cannot be null"); } getNodeManager().removeNode(n); } protected String nodeString(T n, @SuppressWarnings("unused") boolean forEdge) { return n.toString(); } protected String edgeString( @SuppressWarnings("unused") T from, @SuppressWarnings("unused") T to) { return " --> "; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (T n : this) { sb.append(nodeString(n, false)).append('\n'); for (T s : Iterator2Iterable.make(getSuccNodes(n))) { sb.append(edgeString(n, s)).append(nodeString(s, true)); sb.append('\n'); } sb.append('\n'); } return sb.toString(); } /** @see com.ibm.wala.util.graph.NodeManager#containsNode(Object) */ @Override public boolean containsNode(@Nullable T n) { if (n == null) { throw new IllegalArgumentException("n cannot be null"); } return getNodeManager().containsNode(n); } }
6,011
30.809524
96
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/AbstractNumberedGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.graph.impl.NumberedNodeIterator; import com.ibm.wala.util.intset.IntSet; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** * Basic functionality for a graph that delegates node and edge management, and tracks node numbers */ public abstract class AbstractNumberedGraph<T> extends AbstractGraph<T> implements NumberedGraph<T> { /** @return the object which manages nodes in the graph */ @Override protected abstract NumberedNodeManager<T> getNodeManager(); /** @return the object which manages edges in the graph */ @Override protected abstract NumberedEdgeManager<T> getEdgeManager(); /** @see com.ibm.wala.util.graph.NumberedNodeManager#getMaxNumber() */ @Override public int getMaxNumber() { return getNodeManager().getMaxNumber(); } /** @see com.ibm.wala.util.graph.NumberedNodeManager#getNode(int) */ @Override public T getNode(int number) { return getNodeManager().getNode(number); } /** @see com.ibm.wala.util.graph.NumberedNodeManager#getNumber(Object) */ @Override public int getNumber(@Nullable T N) { if (N == null) { throw new IllegalArgumentException("N cannot be null"); } return getNodeManager().getNumber(N); } /** * @see com.ibm.wala.util.graph.NumberedNodeManager#iterateNodes(com.ibm.wala.util.intset.IntSet) */ @Override public Iterator<T> iterateNodes(final IntSet s) { return new NumberedNodeIterator<>(s, this); } /** @see com.ibm.wala.util.graph.NumberedEdgeManager#getPredNodeNumbers(java.lang.Object) */ @Override public IntSet getPredNodeNumbers(@Nullable T node) throws IllegalArgumentException { assert getEdgeManager() != null; return getEdgeManager().getPredNodeNumbers(node); } /** @see com.ibm.wala.util.graph.NumberedEdgeManager#getSuccNodeNumbers(java.lang.Object) */ @Override public IntSet getSuccNodeNumbers(@Nullable T node) throws IllegalArgumentException { return getEdgeManager().getSuccNodeNumbers(node); } }
2,431
31.864865
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/Acyclic.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.intset.BasicNaturalRelation; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntPair; import java.util.ArrayDeque; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** Utilities for dealing with acyclic subgraphs */ public class Acyclic { /* * prevent instantiation */ private Acyclic() {} /** This is slow. Fix it. */ public static <T> boolean isAcyclic(NumberedGraph<T> G, T root) { IBinaryNaturalRelation r = computeBackEdges(G, root); Iterator<IntPair> it = r.iterator(); return !it.hasNext(); } public static final int THRESHOLD_FOR_NONRECURSIVE_DFS = 1000; /** * Compute a relation R s.t. (i,j) \in R iff (i,j) is a backedge according to a DFS of a numbered * graph starting from some root. * * <p>Not efficient. Recursive and uses hash sets. */ public static <T> IBinaryNaturalRelation computeBackEdges(NumberedGraph<T> G, T root) { if (G == null) { throw new IllegalArgumentException("G is null"); } final BasicNaturalRelation result = new BasicNaturalRelation(); // for large methods (e.g. obfuscated library code as found in android libraries // 'com.google.ads.ad.a([B[B)V') // the recursive dfs can lead to a stack overflow error. // for smaller methods the recursive solution seems to be faster, so we keep it. if (G.getNumberOfNodes() <= THRESHOLD_FOR_NONRECURSIVE_DFS) { final Set<T> visited = HashSetFactory.make(); final Set<T> onstack = HashSetFactory.make(); dfs(result, root, G, visited, onstack); } else { dfsNonRecursive(result, root, G); } return result; } private static <T> void dfs( BasicNaturalRelation result, T root, NumberedGraph<T> G, Set<T> visited, Set<T> onstack) { visited.add(root); onstack.add(root); for (T dstNode : Iterator2Iterable.make(G.getSuccNodes(root))) { if (onstack.contains(dstNode)) { int src = G.getNumber(root); int dst = G.getNumber(dstNode); result.add(src, dst); } if (!visited.contains(dstNode)) { dfs(result, dstNode, G, visited, onstack); } } onstack.remove(root); } private static <T> void dfsNonRecursive( final BasicNaturalRelation result, final T root, final NumberedGraph<T> G) { final ArrayDeque<T> stack = new ArrayDeque<>(); final Set<T> stackSet = new HashSet<>(); final ArrayDeque<Iterator<? extends T>> stackIt = new ArrayDeque<>(); final Set<T> finished = new HashSet<>(); stack.push(root); stackSet.add(root); stackIt.push(G.getSuccNodes(root)); while (!stack.isEmpty()) { final T current = stack.pop(); stackSet.remove(current); final Iterator<? extends T> currentIt = stackIt.pop(); if (finished.contains(current)) { continue; } boolean isFinished = true; while (isFinished && currentIt.hasNext()) { final T succ = currentIt.next(); if (!finished.contains(succ)) { if (succ == current || !stackSet.add(succ)) { // found a backedge final int src = G.getNumber(current); final int dst = G.getNumber(succ); result.add(src, dst); } else { stack.push(current); stackSet.add(current); stackIt.push(currentIt); stack.push(succ); stackIt.push(G.getSuccNodes(succ)); isFinished = false; } } } if (isFinished) { finished.add(current); } } } public static <T> boolean hasIncomingBackEdges(Path p, NumberedGraph<T> G, T root) { /* * TODO: pull out computeBackEdges, and pass in the backedge relation as a parameter to this call */ IBinaryNaturalRelation backedges = computeBackEdges(G, root); for (int index = 0; index < p.size(); index++) { int gn = p.get(index); Iterator<? extends T> predIter = G.getPredNodes(G.getNode(gn)); while (predIter.hasNext()) { if (backedges.contains(G.getNumber(predIter.next()), gn)) return true; } } return false; } /** * Compute a set of acyclic paths through a graph G from a node src to a node sink. * * <p>This is not terribly efficient. * * @param max the max number of paths to return. */ public static <T> Collection<Path> computeAcyclicPaths( NumberedGraph<T> G, T root, T src, T sink, int max) { Collection<Path> result = HashSetFactory.make(); EdgeFilteredNumberedGraph<T> acyclic = new EdgeFilteredNumberedGraph<>(G, computeBackEdges(G, root)); Collection<Path> worklist = HashSetFactory.make(); Path sinkPath = Path.make(G.getNumber(sink)); worklist.add(sinkPath); while (!worklist.isEmpty() && result.size() <= max) { Path p = worklist.iterator().next(); worklist.remove(p); int first = p.get(0); if (first == G.getNumber(src)) { result.add(p); } else { for (IntIterator it = acyclic.getPredNodeNumbers(acyclic.getNode(first)).intIterator(); it.hasNext(); ) { worklist.add(Path.prepend(it.next(), p)); } } } return result; } }
5,853
31.703911
101
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/BasicTree.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.collections.SimpleVector; import org.jspecify.annotations.Nullable; /** A simple, extremely inefficient tree implementation */ public class BasicTree<T> { private final T value; private final SimpleVector<BasicTree<T>> children = new SimpleVector<>(); protected BasicTree(T value) { this.value = value; } public static <T> BasicTree<T> make(T value) { if (value == null) { throw new IllegalArgumentException("null value"); } return new BasicTree<>(value); } public T getRootValue() { return value; } @Nullable public T getChildValue(int i) { if (children.get(i) == null) { return null; } else { return children.get(i).getRootValue(); } } public BasicTree<T> getChild(int i) { return children.get(i); } public void setChild(int i, BasicTree<T> tree) { children.set(i, tree); } public int getMaxChildIndex() { return children.getMaxIndex(); } }
1,375
22.724138
75
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/EdgeFilteredNumberedGraph.java
/* * Copyright (c) 2008 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableIntSet; import com.ibm.wala.util.intset.MutableSparseIntSet; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** View of a {@link NumberedGraph} in which some edges have been filtered out */ public class EdgeFilteredNumberedGraph<T> extends AbstractNumberedGraph<T> { private final NumberedGraph<T> delegate; private final IBinaryNaturalRelation ignoreEdges; private final Edges edges; /** * @param delegate the underlying graph * @param ignoreEdges relation specifying which edges should be filtered out */ public EdgeFilteredNumberedGraph(NumberedGraph<T> delegate, IBinaryNaturalRelation ignoreEdges) { super(); this.delegate = delegate; this.ignoreEdges = ignoreEdges; this.edges = new Edges(); } @Override protected NumberedEdgeManager<T> getEdgeManager() { return edges; } private final class Edges implements NumberedEdgeManager<T> { private final class NodeIterator implements Iterator<T> { private final IntIterator nodeNumbers; private NodeIterator(IntSet nodeNumbers) { this.nodeNumbers = nodeNumbers.intIterator(); } @Override public boolean hasNext() { return nodeNumbers.hasNext(); } @Override public T next() { return getNode(nodeNumbers.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public int getPredNodeCount(T N) { return getPredNodeNumbers(N).size(); } @Override public Iterator<T> getPredNodes(@Nullable T N) { return new NodeIterator(getPredNodeNumbers(N)); } @Override public int getSuccNodeCount(T N) { return getSuccNodeNumbers(N).size(); } @Override public Iterator<T> getSuccNodes(@Nullable T N) { return new NodeIterator(getSuccNodeNumbers(N)); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { return delegate.hasEdge(src, dst) && !ignoreEdges.contains(getNumber(src), getNumber(dst)); } @Override public IntSet getPredNodeNumbers(@Nullable T node) { return getFilteredNodeNumbers(node, delegate.getPredNodeNumbers(node)); } private IntSet getFilteredNodeNumbers(@Nullable T node, IntSet s) { MutableIntSet result = MutableSparseIntSet.makeEmpty(); for (IntIterator it = s.intIterator(); it.hasNext(); ) { int y = it.next(); if (!ignoreEdges.contains(y, getNumber(node))) { result.add(y); } } return result; } @Override public IntSet getSuccNodeNumbers(@Nullable T node) { return getFilteredNodeNumbers(node, delegate.getSuccNodeNumbers(node)); } @Override public void addEdge(T src, T dst) { Assertions.UNREACHABLE(); } @Override public void removeAllIncidentEdges(T node) throws UnsupportedOperationException { Assertions.UNREACHABLE(); } @Override public void removeEdge(T src, T dst) throws UnsupportedOperationException { Assertions.UNREACHABLE(); } @Override public void removeIncomingEdges(T node) throws UnsupportedOperationException { Assertions.UNREACHABLE(); } @Override public void removeOutgoingEdges(T node) throws UnsupportedOperationException { Assertions.UNREACHABLE(); } } @Override protected NumberedNodeManager<T> getNodeManager() { return delegate; } }
4,106
26.563758
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/EdgeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** * An object which manages edges in a directed graph. * * @param <T> the type of node in the graph */ public interface EdgeManager<T> { /** * Return an {@link Iterator} over the immediate predecessor nodes of n * * <p>This method never returns {@code null}. * * @return an {@link Iterator} over the immediate predecessor nodes of this Node. */ Iterator<T> getPredNodes(@Nullable T n); /** * Return the number of {@link #getPredNodes immediate predecessor} nodes of n * * @return the number of immediate predecessors of n. */ int getPredNodeCount(T n); /** * Return an Iterator over the immediate successor nodes of n * * <p>This method never returns {@code null}. * * @return an Iterator over the immediate successor nodes of n */ Iterator<T> getSuccNodes(@Nullable T n); /** * Return the number of {@link #getSuccNodes immediate successor} nodes of this Node in the Graph * * @return the number of immediate successor Nodes of this Node in the Graph. */ int getSuccNodeCount(T N); void addEdge(T src, T dst); void removeEdge(T src, T dst) throws UnsupportedOperationException; void removeAllIncidentEdges(T node) throws UnsupportedOperationException; void removeIncomingEdges(T node) throws UnsupportedOperationException; void removeOutgoingEdges(T node) throws UnsupportedOperationException; boolean hasEdge(@Nullable T src, @Nullable T dst); }
1,931
27.835821
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/GXL.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import java.util.Iterator; import java.util.Map; import java.util.function.Function; public class GXL { public interface EntityTypes<T> { String type(T entity); String type(Graph<T> entity); String type(T from, T to); } public static <T> String toGXL( Graph<T> G, EntityTypes<T> types, String graphId, Function<T, String> nodeIds, Function<T, Map<String, String>> nodeProperties) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); sb.append("<!DOCTYPE gxl SYSTEM \"http://www.gupro.de/GXL/gxl-1.0.dtd\">\n"); sb.append("<gxl xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n"); sb.append(" <graph id=\"") .append(graphId) .append("\" edgemode=\"directed\" hypergraph=\"false\">\n"); sb.append(" <type xlink:href=\"").append(types.type(G)).append("\"/>\n"); for (T n : G) { sb.append(" <node id=\"").append(nodeIds.apply(n)).append("\">\n"); sb.append(" <type xlink:href=\"").append(types.type(n)).append("\"/>\n"); Map<String, String> props = nodeProperties.apply(n); if (props != null) { for (Map.Entry<String, String> e : props.entrySet()) { sb.append(" <attr name=\"").append(e.getKey()).append("\">\n"); if (e.getValue() != null) { sb.append(" <string>").append(e.getValue()).append("</string>\n"); } else { sb.append(" <string/>\n"); } sb.append(" </attr>\n"); } } sb.append(" </node>\n"); } for (T n : G) { Iterator<T> ss = G.getSuccNodes(n); while (ss.hasNext()) { T s = ss.next(); sb.append(" <edge from=\"") .append(nodeIds.apply(n)) .append("\" to=\"") .append(nodeIds.apply(s)) .append("\">\n"); sb.append(" <type xlink:href=\"").append(types.type(n, s)).append("\"/>\n"); sb.append(" </edge>\n"); } } sb.append(" </graph>\n"); sb.append("</gxl>\n"); return sb.toString(); } }
2,542
30.012195
89
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/Graph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; /** * Basic interface for a directed graph. * * <p>We choose to define a {@link Graph} as a composition of a {@link NodeManager} and an {@link * EdgeManager}, which track nodes and edges, respectively. This way, in many cases we can compose * separate {@link NodeManager} and {@link EdgeManager} implementations to create {@link Graph} * implementations, using delegation. * * @param <T> the type of nodes in this graph. */ public interface Graph<T> extends NodeManager<T>, EdgeManager<T> { /** * remove a node and all its incident edges * * @throws UnsupportedOperationException if the graph implementation does not allow removal */ void removeNodeAndEdges(T n) throws UnsupportedOperationException; }
1,137
35.709677
98
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/GraphIntegrity.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.IteratorUtil; import com.ibm.wala.util.graph.traverse.BFSIterator; import com.ibm.wala.util.graph.traverse.DFS; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; /** Utility class to check integrity of a graph data structure. */ public class GraphIntegrity { /** * DEBUG_LEVEL: * * <ul> * <li>0 No output * <li>1 Print some simple stats and warning information * <li>2 Detailed debugging * </ul> */ static final int DEBUG_LEVEL = 0; public static <T> void check(Graph<T> G) throws UnsoundGraphException { if (G == null) { throw new IllegalArgumentException("G is null"); } checkNodeCount(G); checkEdges(G); checkEdgeCounts(G); } private static <T> void checkEdgeCounts(Graph<T> G) throws UnsoundGraphException { for (T N : G) { int count1 = G.getSuccNodeCount(N); int count2 = IteratorUtil.count(G.getSuccNodes(N)); if (count1 != count2) { throw new UnsoundGraphException("getSuccNodeCount " + count1 + " is wrong for node " + N); } int count3 = G.getPredNodeCount(N); int count4 = IteratorUtil.count(G.getPredNodes(N)); if (count3 != count4) { throw new UnsoundGraphException("getPredNodeCount " + count1 + " is wrong for node " + N); } } } private static <T> void checkEdges(Graph<T> G) throws UnsoundGraphException { for (T N : G) { if (!G.containsNode(N)) { throw new UnsoundGraphException( N + " is not contained in the the graph " + G.containsNode(N)); } PRED: for (T pred : Iterator2Iterable.make(G.getPredNodes(N))) { if (!G.containsNode(pred)) { throw new UnsoundGraphException( pred + " is a predecessor of " + N + " but is not contained in the graph"); } for (Object succ : Iterator2Iterable.make(G.getSuccNodes(pred))) { if (succ.equals(N)) { continue PRED; } } // didn't find N G.getPredNodes(N); G.getSuccNodes(pred); throw new UnsoundGraphException( pred + " is a predecessor of " + N + " but inverse doesn't hold"); } SUCC: for (T succ : Iterator2Iterable.make(G.getSuccNodes(N))) { if (!G.containsNode(succ)) { throw new UnsoundGraphException( succ + " is a successor of " + N + " but is not contained in the graph"); } for (Object pred : Iterator2Iterable.make(G.getPredNodes(succ))) { if (pred.equals(N)) { continue SUCC; } } // didn't find N throw new UnsoundGraphException( succ + " is a successor of " + N + " but inverse doesn't hold"); } } } @SuppressWarnings("unused") private static <T> void checkNodeCount(Graph<T> G) throws UnsoundGraphException { int n1 = 0; int n2 = 0; int n3 = 0; int n4 = 0; int n5 = 0; try { n1 = G.getNumberOfNodes(); n2 = 0; for (T t : G) { Object n = t; if (DEBUG_LEVEL > 1) { System.err.println(("n2 loop: " + n)); } n2++; } n3 = IteratorUtil.count(new BFSIterator<>(G)); n4 = IteratorUtil.count(DFS.iterateDiscoverTime(G)); n5 = IteratorUtil.count(DFS.iterateFinishTime(G)); } catch (RuntimeException e) { e.printStackTrace(); throw new UnsoundGraphException(e.toString()); } if (n1 != n2) { throw new UnsoundGraphException("n1: " + n1 + " n2: " + n2); } if (n1 != n3) { throw setDiffException("n1: " + n1 + " n3: " + n3, G.iterator(), new BFSIterator<>(G)); } if (n1 != n4) { throw new UnsoundGraphException("n1: " + n1 + " n4: " + n3); } if (n1 != n5) { throw new UnsoundGraphException("n1: " + n1 + " n5: " + n3); } } private static <T> UnsoundGraphException setDiffException( String msg, Iterator<? extends T> i1, Iterator<T> i2) { HashSet<T> set1 = HashSetFactory.make(); while (i1.hasNext()) { T o1 = i1.next(); boolean b = set1.add(o1); if (!b) { return new UnsoundGraphException("set1 already contained " + o1); } } HashSet<T> set2 = HashSetFactory.make(); while (i2.hasNext()) { T o2 = i2.next(); boolean b = set2.add(o2); if (!b) { return new UnsoundGraphException("set2 already contained " + o2); } } GraphIntegrity.printCollection("set 1 ", set1); GraphIntegrity.printCollection("set 2 ", set2); @SuppressWarnings("unchecked") HashSet<T> s1clone = (HashSet<T>) set1.clone(); set1.removeAll(set2); if (set1.size() > 0) { Object first = set1.iterator().next(); msg = msg + ", first iterator contained " + first; } else { set2.removeAll(s1clone); if (set2.size() > 0) { Object first = set2.iterator().next(); msg = msg + ", 2nd iterator contained " + first; } else { msg += "set2.size = 0"; } } return new UnsoundGraphException(msg); } public static class UnsoundGraphException extends Exception { private static final long serialVersionUID = 1503478788521696930L; public UnsoundGraphException() { super(); } public UnsoundGraphException(String s) { super(s); } } /** @throws IllegalArgumentException if c is null */ public static void printCollection(String string, Collection<?> c) { if (c == null) { throw new IllegalArgumentException("c is null"); } System.err.println(string); if (c.isEmpty()) { System.err.println("none\n"); } else { for (Object name : c) { System.err.println(name.toString()); } System.err.println("\n"); } } }
6,355
29.705314
98
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/GraphPrint.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph; /** Simple graph printing utility */ public class GraphPrint { public static <T> String genericToString(Graph<T> G) { if (G == null) { throw new IllegalArgumentException("G is null"); } SlowSparseNumberedGraph<T> sg = SlowSparseNumberedGraph.make(); for (T name : G) { sg.addNode(name); } for (T n : G) { for (T d : Iterator2Iterable.make(G.getSuccNodes(n))) { sg.addEdge(n, d); } } return sg.toString(); } }
1,005
27.742857
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/GraphReachability.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.dataflow.graph.AbstractMeetOperator; import com.ibm.wala.dataflow.graph.BitVectorFramework; import com.ibm.wala.dataflow.graph.BitVectorIdentity; import com.ibm.wala.dataflow.graph.BitVectorSolver; import com.ibm.wala.dataflow.graph.BitVectorUnion; import com.ibm.wala.dataflow.graph.BitVectorUnionConstant; import com.ibm.wala.dataflow.graph.DataflowSolver; import com.ibm.wala.dataflow.graph.ITransferFunctionProvider; import com.ibm.wala.fixpoint.BitVectorVariable; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.impl.GraphInverter; import com.ibm.wala.util.intset.MutableMapping; import com.ibm.wala.util.intset.OrdinalSet; import com.ibm.wala.util.intset.OrdinalSetMapping; import java.util.Iterator; import java.util.function.Predicate; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** * A dataflow system that computes, for each graph node, the set of "interesting" nodes that are * reachable */ public class GraphReachability<T, S> { /** Governing graph */ private final Graph<T> g; /** Killdall-style dataflow solver */ @Nullable private DataflowSolver<T, BitVectorVariable> solver; /** set of "interesting" CGNodes */ final OrdinalSetMapping<S> domain; /** * @param g call graph to analyze * @param filter "interesting" node definition * @throws IllegalArgumentException if g is null */ public GraphReachability(Graph<T> g, Predicate<? super T> filter) { if (g == null) { throw new IllegalArgumentException("g is null"); } this.g = g; Iterator<T> i = new FilterIterator<>(g.iterator(), filter); domain = new MutableMapping<>(Iterator2Collection.toSet(i).toArray()); } /** @return the set of interesting nodes reachable from n */ public OrdinalSet<S> getReachableSet(Object n) throws IllegalStateException { if (solver == null) { throw new IllegalStateException("must call solve() before calling getReachableSet()"); } BitVectorVariable v = solver.getOut(n); assert v != null : "null variable for node " + n; if (v.getValue() == null) { return OrdinalSet.empty(); } else { return new OrdinalSet<>(v.getValue(), domain); } } /** * @return true iff the evaluation of some equation caused a change in the value of some variable. */ public boolean solve(IProgressMonitor monitor) throws CancelException { ITransferFunctionProvider<T, BitVectorVariable> functions = new ITransferFunctionProvider<>() { /* * @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#getNodeTransferFunction(java.lang.Object) */ @Override public UnaryOperator<BitVectorVariable> getNodeTransferFunction(T n) { int index = domain.getMappedIndex(n); if (index > -1) { return new BitVectorUnionConstant(index); } else { return BitVectorIdentity.instance(); } } /* * @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#hasNodeTransferFunctions() */ @Override public boolean hasNodeTransferFunctions() { return true; } /* * @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#getEdgeTransferFunction(java.lang.Object, java.lang.Object) */ @NullUnmarked @Nullable @Override public UnaryOperator<BitVectorVariable> getEdgeTransferFunction(Object from, Object to) { Assertions.UNREACHABLE(); return null; } /* * @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#hasEdgeTransferFunctions() */ @Override public boolean hasEdgeTransferFunctions() { return false; } /* * @see com.ibm.wala.dataflow.graph.ITransferFunctionProvider#getMeetOperator() */ @Override public AbstractMeetOperator<BitVectorVariable> getMeetOperator() { return BitVectorUnion.instance(); } }; BitVectorFramework<T, S> f = new BitVectorFramework<>(GraphInverter.invert(g), functions, domain); solver = new BitVectorSolver<>(f); return solver.solve(monitor); } }
5,026
34.153846
131
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/GraphSlicer.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.IteratorUtil; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.impl.GraphInverter; import com.ibm.wala.util.graph.traverse.DFS; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** Utilities related to simple graph subset operations. */ public class GraphSlicer { /** * Performs a backward slice. * * @param <T> type for nodes * @param g the graph to slice * @param p identifies targets for the backward slice * @return the set of nodes in g, from which any of the targets (nodes that f accepts) is * reachable. */ public static <T> Set<T> slice(Graph<T> g, Predicate<T> p) { if (g == null) { throw new IllegalArgumentException("g is null"); } HashSet<T> roots = HashSetFactory.make(); for (T o : g) { if (p.test(o)) { roots.add(o); } } Set<T> result = DFS.getReachableNodes(GraphInverter.invert(g), roots); return result; } /** Prune a graph to only the nodes accepted by the {@link Predicate} p */ public static <T> Graph<T> prune(final Graph<T> g, final Predicate<T> p) { if (g == null) { throw new IllegalArgumentException("g is null"); } final NodeManager<T> n = new NodeManager<>() { int nodeCount = -1; @Override public Iterator<T> iterator() { return new FilterIterator<>(g.iterator(), p); } @Override public Stream<T> stream() { return g.stream().filter(p); } @Override public int getNumberOfNodes() { if (nodeCount == -1) { nodeCount = IteratorUtil.count(iterator()); } return nodeCount; } @Override public void addNode(T n) { Assertions.UNREACHABLE(); } @Override public void removeNode(T n) { Assertions.UNREACHABLE(); } @Override public boolean containsNode(@Nullable T n) { return p.test(n) && g.containsNode(n); } }; final EdgeManager<T> e = new EdgeManager<>() { @Override public Iterator<T> getPredNodes(@Nullable T n) { return new FilterIterator<>(g.getPredNodes(n), p); } @Override public int getPredNodeCount(T n) { return IteratorUtil.count(getPredNodes(n)); } @Override public Iterator<T> getSuccNodes(@Nullable T n) { return new FilterIterator<>(g.getSuccNodes(n), p); } @Override public int getSuccNodeCount(T N) { return IteratorUtil.count(getSuccNodes(N)); } @Override public void addEdge(T src, T dst) { Assertions.UNREACHABLE(); } @Override public void removeEdge(T src, T dst) { Assertions.UNREACHABLE(); } @Override public void removeAllIncidentEdges(T node) { Assertions.UNREACHABLE(); } @Override public void removeIncomingEdges(T node) { Assertions.UNREACHABLE(); } @Override public void removeOutgoingEdges(T node) { Assertions.UNREACHABLE(); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { return g.hasEdge(src, dst) && p.test(src) && p.test(dst); } }; AbstractGraph<T> output = new AbstractGraph<>() { @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected String nodeString(T n, boolean forEdge) { if (g instanceof AbstractGraph) { return ((AbstractGraph) g).nodeString(n, forEdge); } else { return super.nodeString(n, forEdge); } } @Override protected NodeManager<T> getNodeManager() { return n; } @Override protected EdgeManager<T> getEdgeManager() { return e; } }; return output; } public static <E> AbstractGraph<E> project(final Graph<E> G, final Predicate<E> fmember) { final NodeManager<E> nodeManager = new NodeManager<>() { private int count = -1; @Override public void addNode(E n) { throw new UnsupportedOperationException(); } @Override public boolean containsNode(@Nullable E N) { return G.containsNode(N) && fmember.test(N); } @Override public int getNumberOfNodes() { if (count == -1) { count = IteratorUtil.count(iterator()); } return count; } @Override public Iterator<E> iterator() { return new FilterIterator<>(G.iterator(), fmember); } @Override public Stream<E> stream() { return G.stream().filter(fmember); } @Override public void removeNode(E n) { throw new UnsupportedOperationException(); } }; final EdgeManager<E> edgeManager = new EdgeManager<>() { private final Map<E, Collection<E>> succs = new HashMap<>(); private final Map<E, Collection<E>> preds = new HashMap<>(); private Set<E> getConnected( @Nullable E inst, Function<E, Iterator<? extends E>> fconnected) { Set<E> result = new LinkedHashSet<>(); Set<E> seenInsts = new HashSet<>(); Set<E> newInsts = Iterator2Collection.toSet(fconnected.apply(inst)); while (!newInsts.isEmpty()) { Set<E> nextInsts = new HashSet<>(); for (E s : newInsts) { if (seenInsts.add(s)) { if (nodeManager.containsNode(s)) { result.add(s); } else { Iterator<? extends E> ss = fconnected.apply(s); while (ss.hasNext()) { E n = ss.next(); if (!seenInsts.contains(n)) { nextInsts.add(n); } } } } } newInsts = nextInsts; } return result; } private void setPredNodes(@Nullable E N) { preds.put(N, getConnected(N, G::getPredNodes)); } private void setSuccNodes(@Nullable E N) { succs.put(N, getConnected(N, G::getSuccNodes)); } @NullUnmarked @Override public int getPredNodeCount(E N) { if (!preds.containsKey(N)) { setPredNodes(N); } return preds.get(N).size(); } @NullUnmarked @Override public Iterator<E> getPredNodes(@Nullable E N) { if (!preds.containsKey(N)) { setPredNodes(N); } return preds.get(N).iterator(); } @NullUnmarked @Override public int getSuccNodeCount(E N) { if (!succs.containsKey(N)) { setSuccNodes(N); } return succs.get(N).size(); } @NullUnmarked @Override public Iterator<E> getSuccNodes(@Nullable E N) { if (!succs.containsKey(N)) { setSuccNodes(N); } return succs.get(N).iterator(); } @NullUnmarked @Override public boolean hasEdge(@Nullable E src, @Nullable E dst) { if (!preds.containsKey(dst)) { setPredNodes(dst); } return preds.get(dst).contains(src); } @Override public void addEdge(E src, E dst) { throw new UnsupportedOperationException(); } @Override public void removeAllIncidentEdges(E node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeEdge(E src, E dst) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeIncomingEdges(E node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeOutgoingEdges(E node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } }; return new AbstractGraph<>() { @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected String nodeString(E n, boolean forEdge) { if (G instanceof AbstractGraph) { return ((AbstractGraph) G).nodeString(n, forEdge); } else { return super.nodeString(n, forEdge); } } @Override protected EdgeManager<E> getEdgeManager() { return edgeManager; } @Override protected NodeManager<E> getNodeManager() { return nodeManager; } }; } }
10,302
27.699164
92
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/GraphUtil.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; /** Utility methods for graphs. */ public class GraphUtil { /** count the number of edges in g */ public static <T> long countEdges(Graph<T> g) { if (g == null) { throw new IllegalArgumentException("g is null"); } long edgeCount = 0; for (T t : g) { edgeCount += g.getSuccNodeCount(t); } return edgeCount; } }
755
26
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/INodeWithNumber.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; /** * Basic interface for a node which lives in one graph ... it's id is used to implement the {@link * NumberedGraph} interface. */ public interface INodeWithNumber { /** * A non-negative integer which serves as an identifier for this node in it's "dominant" graph. * Initially this number is -1; a NumberedGraph will set it to a non-negative value when this node * is inserted into the graph * * @return the identifier */ int getGraphNodeId(); void setGraphNodeId(int number); }
919
29.666667
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/INodeWithNumberedEdges.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.intset.IntSet; import org.jspecify.annotations.Nullable; /** * Basic interface for a node which lives in one graph ... it's id is used to implement the {@link * NumberedGraph} interface. */ public interface INodeWithNumberedEdges extends INodeWithNumber { /** @return set of node numbers which are successors of this node */ @Nullable IntSet getSuccNumbers(); /** @return set of node numbers which are predecessors of this node */ @Nullable IntSet getPredNumbers(); /** Modify the graph so that node number n is a successor of this node */ void addSucc(int n); /** Modify the graph so that node number n is a predecessor of this node */ void addPred(int n); /** * remove all edges that involve this node. This must fix up the other nodes involved in each edge * removed. */ void removeAllIncidentEdges(); /** * remove all incoming edges to this this node. This must fix up the other nodes involved in each * edge removed. */ void removeIncomingEdges(); /** * remove all outgoing edges to this this node. This must fix up the other nodes involved in each * edge removed. */ void removeOutgoingEdges(); }
1,606
29.320755
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/InferGraphRoots.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.collections.HashSetFactory; import java.util.HashSet; import java.util.Set; /** TODO: Move this somewhere. */ public class InferGraphRoots { public static <T> Set<T> inferRoots(Graph<T> g) { if (g == null) { throw new IllegalArgumentException("g is null"); } HashSet<T> s = HashSetFactory.make(); for (T node : g) { if (g.getPredNodeCount(node) == 0) { s.add(node); } } return s; } }
874
25.515152
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/NodeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import java.util.Collection; import java.util.Iterator; import java.util.stream.Stream; import org.jspecify.annotations.Nullable; /** * An object which tracks graph nodes. * * <p>This is effectively a stripped-down collection interface. We choose to avoid using the full * {@link Collection} interface, so that it takes less code to implement a new {@link NodeManager}. * * @param <T> the type of nodes this {@link NodeManager} tracks. */ public interface NodeManager<T> extends Iterable<T> { /** @return an {@link Iterator} of the nodes in this graph */ @Override default Iterator<T> iterator() { return stream().iterator(); } /** @return a {@link Stream} of the nodes in this graph */ Stream<T> stream(); /** @return the number of nodes in this graph */ int getNumberOfNodes(); /** add a node to this graph */ void addNode(T n); /** remove a node from this graph */ void removeNode(T n) throws UnsupportedOperationException; /** @return true iff the graph contains the specified node */ boolean containsNode(@Nullable T n); }
1,483
29.285714
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/NumberedEdgeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.intset.IntSet; import org.jspecify.annotations.Nullable; /** Additional functionality for edges in numbered graphs */ public interface NumberedEdgeManager<T> extends EdgeManager<T> { /** @return the numbers identifying the immediate successors of node */ IntSet getSuccNodeNumbers(@Nullable T node); /** @return the numbers identifying the immediate predecessors of node */ IntSet getPredNodeNumbers(@Nullable T node); }
866
33.68
75
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/NumberedGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; /** * A numbered graph is a {@link Graph} where each node has a unique persistent non-negative integer * id. */ public interface NumberedGraph<T> extends Graph<T>, NumberedNodeManager<T>, NumberedEdgeManager<T> {}
630
32.210526
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/NumberedNodeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.intset.IntSet; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** An object which tracks nodes with numbers. */ public interface NumberedNodeManager<T> extends NodeManager<T> { int getNumber(@Nullable T N); T getNode(int number); int getMaxNumber(); /** @return iterator of nodes with the numbers in set s */ Iterator<T> iterateNodes(IntSet s); }
818
27.241379
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/OrderedMultiGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; /** */ public interface OrderedMultiGraph<T> extends Graph<T> { /** get the ith successor of a node */ T getSuccessor(T node, int i); /** add an edge and record it so dst is the ith successor of src */ void addEdge(int i, T src, T dst); }
658
28.954545
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/Path.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph; import com.ibm.wala.util.intset.SimpleIntVector; /** * We represent a path in a numbered graph as a vector of integers &lt;i_1, ..., i_n&gt; where node * i_1 is the src and node i_n is the sink */ public class Path extends SimpleIntVector { private static final long serialVersionUID = 5622964158500601280L; final int size; private Path(int defaultValue, int size) { super(defaultValue, size); this.size = size; } public static Path make(int value) { return new Path(value, 1); } public static Path prepend(int x, Path p) { if (p == null) { throw new IllegalArgumentException("null p"); } Path result = new Path(0, p.size + 1); result.set(0, x); for (int i = 0; i < p.size; i++) { result.set(i + 1, p.get(i)); } return result; } @Override public int hashCode() { int result = 7; for (int i = 0; i < size; i++) { result += 31 * (get(i) + 1); } return result; } @Override public boolean equals(Object obj) { if (obj instanceof Path) { Path other = (Path) obj; if (size == other.size) { for (int i = 0; i < size; i++) { if (get(i) != other.get(i)) { return false; } } return true; } else { return false; } } else { return false; } } public int size() { return size; } @Override public String toString() { StringBuilder result = new StringBuilder("["); for (int i = 0; i < size; i++) { result.append(get(i)); if (i < size - 1) { result.append(','); } } result.append(']'); return result.toString(); } }
2,081
22.133333
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/SerializableGraph.java
package com.ibm.wala.util.graph; import java.io.Serializable; public interface SerializableGraph<T extends Serializable> extends Graph<T>, Serializable {}
157
25.333333
92
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/dominators/DominanceFrontiers.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.dominators; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.traverse.DFS; import java.util.Iterator; import java.util.Map; import java.util.Set; /** An object that computes the dominance frontiers of a graph */ public class DominanceFrontiers<T> { private final Map<T, Set<T>> DF = HashMapFactory.make(); private final Dominators<T> dom; private final Graph<T> G; private final T root; /** * @param G The graph * @param root The root from which to compute dominators */ public DominanceFrontiers(Graph<T> G, T root) { this.root = root; this.G = G; this.dom = Dominators.make(G, root); analyze(); } public Iterator<T> getDominanceFrontier(T n) { Set<T> frontier = DF.get(n); if (frontier == null) { throw new IllegalArgumentException("no dominance frontier for node " + n); } return frontier.iterator(); } public boolean isDominatedBy(T node, T master) { return dom.isDominatedBy(node, master); } public Iterator<T> dominators(T node) { return dom.dominators(node); } public Graph<T> dominatorTree() { return dom.dominatorTree(); } private void analyze() { Graph<T> DT = dom.dominatorTree(); Iterator<T> XS = DFS.iterateFinishTime(DT, new NonNullSingletonIterator<>(root)); while (XS.hasNext()) { T X = XS.next(); Set<T> DF_X = HashSetFactory.make(); DF.put(X, DF_X); // DF_local for (T Y : Iterator2Iterable.make(G.getSuccNodes(X))) { if (dom.getIdom(Y) != X) { DF_X.add(Y); } } // DF_up for (T Z : Iterator2Iterable.make(DT.getSuccNodes(X))) { for (T Y2 : Iterator2Iterable.make(getDominanceFrontier(Z))) { if (dom.getIdom(Y2) != X) DF_X.add(Y2); } } } } }
2,441
26.133333
85
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/dominators/Dominators.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.dominators; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.AbstractGraph; import com.ibm.wala.util.graph.EdgeManager; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NodeManager; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.graph.traverse.DFSDiscoverTimeIterator; import com.ibm.wala.util.graph.traverse.SlowDFSDiscoverTimeIterator; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.jspecify.annotations.Nullable; /** * Calculate dominators using Langauer and Tarjan's fastest algorithm. TOPLAS 1(1), July 1979. This * implementation uses path compression and results in a O(e * alpha(e,n)) complexity, where e is * the number of edges in the CFG and n is the number of nodes. * * <p>Sources: TOPLAS article, Muchnick book */ public abstract class Dominators<T> { static final boolean DEBUG = false; /** a mapping from DFS number to node */ private final T[] vertex; /** a convenient place to locate the graph to avoid passing it internally */ protected final Graph<T> G; /** the root node from which to build dominators */ protected final T root; /** the number of nodes reachable from the root */ protected int reachableNodeCount = 0; /** * @param G The graph * @param root The root from which to compute dominators * @throws IllegalArgumentException if G is null */ @SuppressWarnings("unchecked") public Dominators(Graph<T> G, T root) throws IllegalArgumentException { if (G == null) { throw new IllegalArgumentException("G is null"); } this.G = G; this.root = root; if (G.getNumberOfNodes() == 0) { throw new IllegalArgumentException("G has no nodes"); } this.vertex = (T[]) new Object[G.getNumberOfNodes() + 1]; } public static <T> Dominators<T> make(Graph<T> G, T root) { if (G instanceof NumberedGraph) { return new NumberedDominators<>((NumberedGraph<T>) G, root); } else { return new GenericDominators<>(G, root); } } /** is node dominated by master? */ public boolean isDominatedBy(T node, T master) { for (T ptr = node; ptr != null; ptr = getIdom(ptr)) // use equals() since sometimes the CFGs get // reconstructed --MS if (ptr.equals(master)) return true; return false; } /** return the immediate dominator of node */ @Nullable public T getIdom(@Nullable T node) { return getInfo(node).dominator; } /** return an Iterator over all nodes that dominate node */ public Iterator<T> dominators(final T node) { return new Iterator<>() { @Nullable private T current = node; @Override public void remove() { throw new UnsupportedOperationException(); } @Override public boolean hasNext() { return current != null; } @Override public T next() { if (current == null) throw new NoSuchElementException(); T nextNode = current; current = getIdom(current); return nextNode; } }; } /** return the dominator tree, which has an edge from n to n' if n dominates n' */ public Graph<T> dominatorTree() { return new AbstractGraph<>() { @Override protected NodeManager<T> getNodeManager() { return G; } @Override protected EdgeManager<T> getEdgeManager() { return edges; } private final EdgeManager<T> edges = new EdgeManager<>() { private final Map<T, Set<T>> nextMap = HashMapFactory.make(); { for (T n : G) { if (n != root) { T prev = getIdom(n); Set<T> next = nextMap.get(prev); if (next == null) nextMap.put(prev, next = HashSetFactory.make(2)); next.add(n); } } } @Override public Iterator<T> getPredNodes(@Nullable T N) { if (N == root) return EmptyIterator.instance(); else return new NonNullSingletonIterator<>(getIdom(N)); } @Override public int getPredNodeCount(Object N) { return (N == root) ? 0 : 1; } @Override public Iterator<T> getSuccNodes(@Nullable Object N) { if (nextMap.containsKey(N)) return nextMap.get(N).iterator(); else return EmptyIterator.instance(); } @Override public int getSuccNodeCount(Object N) { if (nextMap.containsKey(N)) return nextMap.get(N).size(); else return 0; } @Override public void addEdge(Object src, Object dst) { Assertions.UNREACHABLE(); } @Override public void removeEdge(Object src, Object dst) { Assertions.UNREACHABLE(); } @Override public void removeAllIncidentEdges(Object node) { Assertions.UNREACHABLE(); } @Override public void removeIncomingEdges(Object node) { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } @Override public void removeOutgoingEdges(Object node) { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } @Override public boolean hasEdge(@Nullable Object src, @Nullable Object dst) { // TODO Auto-generated method stub Assertions.UNREACHABLE(); return false; } }; }; } // // IMPLEMENTATION -- MAIN ALGORITHM // /** analyze dominators */ protected void analyze() { if (DEBUG) System.out.println("Dominators for " + G); // Step 1: Perform a DFS numbering step1(); // Step 2: the heart of the algorithm step2(); // Step 3: adjust immediate dominators of nodes whose current version of // the immediate dominators differs from the nodes with the depth-first // number of the node's semidominator. step3(); if (DEBUG) System.err.println(this); } /** * The goal of this step is to perform a DFS numbering on the CFG, starting at the root. The exit * node is not included. */ private void step1() { reachableNodeCount = 0; DFSDiscoverTimeIterator<T> dfs = new SlowDFSDiscoverTimeIterator<>(G, root) { public static final long serialVersionUID = 88831771771711L; @Override protected void visitEdge(T from, T to) { if (DEBUG) System.out.println("visiting edge " + from + " --> " + to); setParent(to, from); } }; while (dfs.hasNext()) { T node = dfs.next(); assert node != null; vertex[++reachableNodeCount] = node; setSemi(node, reachableNodeCount); if (DEBUG) System.out.println(node + " is DFS number " + reachableNodeCount); } } /** This is the heart of the algorithm. See sources for details. */ private void step2() { if (DEBUG) { System.out.println(" ******* Beginning STEP 2 *******\n"); } // Visit each node in reverse DFS order, except for the root, which // has number 1 // for i=n downto 2 for (int i = reachableNodeCount; i > 1; i--) { T node = vertex[i]; if (DEBUG) { System.out.println(" Processing: " + node + '\n'); } // visit each predecessor Iterator<? extends T> e = G.getPredNodes(node); while (e.hasNext()) { T prev = e.next(); if (DEBUG) { System.out.println(" Inspecting prev: " + prev); } T u = EVAL(prev); // if semi(u) < semi(node) then semi(node) = semi(u) // u may be part of infinite loop and thus, is unreachable from the exit // node. // In this case, it will have a semi value of 0. Thus, we screen for it // here if (getSemi(u) != 0 && getSemi(u) < getSemi(node)) { setSemi(node, getSemi(u)); } } // while prev // add "node" to bucket(vertex(semi(node))); addToBucket(vertex[getSemi(node)], node); // LINK(parent(node), node) LINK(getParent(node), node); // foreach node2 in bucket(parent(node)) do Iterator<T> bucketEnum = iterateBucket(getParent(node)); while (bucketEnum.hasNext()) { T node2 = bucketEnum.next(); // u = EVAL(node2) T u = EVAL(node2); // if semi(u) < semi(node2) then // dom(node2) = u // else // dom(node2) = parent(node) if (getSemi(u) < getSemi(node2)) { setDominator(node2, u); } else { setDominator(node2, getParent(node)); } } // while bucket has more elements } // for DFSCounter .. 1 } // method /** * This method inspects the passed node and returns the following: node, if node is a root of a * tree in the forest * * <p>any vertex, u != r such that otherwise r is the root of the tree containing node and * * semi(u) is minimum on the path r -&gt; v * * <p>See TOPLAS 1(1), July 1979, p 128 for details. * * @param node the node to evaluate * @return the node as described above */ @Nullable private T EVAL(T node) { if (DEBUG) { System.out.println(" Evaling " + node); } if (getAncestor(node) == null) { return getLabel(node); } else { compress(node); if (getSemi(getLabel(getAncestor(node))) >= getSemi(getLabel(node))) { return getLabel(node); } else { return getLabel(getAncestor(node)); } } } /** * This recursive method performs the path compression * * @param node node of interest */ private void compress(@Nullable T node) { if (getAncestor(getAncestor(node)) != null) { compress(getAncestor(node)); if (getSemi(getLabel(getAncestor(node))) < getSemi(getLabel(node))) { setLabel(node, getLabel(getAncestor(node))); } setAncestor(node, getAncestor(getAncestor(node))); } } /** * Adds edge (node1, node2) to the forest maintained as an auxiliary data structure. This * implementation uses path compression and results in a O(e * alpha(e,n)) complexity, where e is * the number of edges in the CFG and n is the number of nodes. * * @param node1 a basic node corresponding to the source of the new edge * @param node2 a basic node corresponding to the source of the new edge */ private void LINK(@Nullable T node1, T node2) { if (DEBUG) { System.out.println(" Linking " + node1 + " with " + node2); } T s = node2; while (getSemi(getLabel(node2)) < getSemi(getLabel(getChild(s)))) { if (getSize(s) + getSize(getChild(getChild(s))) >= 2 * getSize(getChild(s))) { setAncestor(getChild(s), s); setChild(s, getChild(getChild(s))); } else { setSize(getChild(s), getSize(s)); setAncestor(s, getChild(s)); s = getChild(s); } } setLabel(s, getLabel(node2)); setSize(node1, getSize(node1) + getSize(node2)); if (getSize(node1) < 2 * getSize(node2)) { T tmp = s; s = getChild(node1); setChild(node1, tmp); } while (s != null) { setAncestor(s, node1); s = getChild(s); } if (DEBUG) { System.out.println(" .... done"); } } /** This final step sets the final dominator information. */ private void step3() { // Visit each node in DFS order, except for the root, which has number 1 for (int i = 2; i <= reachableNodeCount; i++) { T node = vertex[i]; // if dom(node) != vertex[semi(node)] if (getDominator(node) != vertex[getSemi(node)]) { // dom(node) = dom(dom(node)) setDominator(node, getDominator(getDominator(node))); } } } /** LOOK-ASIDE TABLE FOR PER-NODE STATE AND ITS ACCESSORS */ protected final class DominatorInfo { /* * The result of this computation: the immediate dominator of this node */ @Nullable private T dominator; /* * The parent node in the DFS tree used in dominator computation */ @Nullable private T parent; /* * the ``semi-dominator,'' which starts as the DFS number in step 1 */ private int semiDominator; /* * The buckets used in step 2 */ private final Set<T> bucket; /* * the labels used in the fast union-find structure */ @Nullable private T label; /* * ancestor for fast union-find data structure */ @Nullable private T ancestor; /* * the size used by the fast union-find structure */ private int size; /* * the child used by the fast union-find structure */ @Nullable private T child; DominatorInfo(@Nullable T node) { semiDominator = 0; dominator = null; parent = null; bucket = HashSetFactory.make(); ancestor = null; label = node; size = 1; child = null; } } /* * Look-aside table for DominatorInfo objects */ protected abstract DominatorInfo getInfo(@Nullable T node); private Iterator<T> iterateBucket(@Nullable T node) { return getInfo(node).bucket.iterator(); } private void addToBucket(T node, T addend) { getInfo(node).bucket.add(addend); } @Nullable private T getDominator(@Nullable T node) { assert node != null; return getInfo(node).dominator; } private void setDominator(T node, @Nullable T dominator) { getInfo(node).dominator = dominator; } @Nullable private T getParent(T node) { return getInfo(node).parent; } private void setParent(T node, T parent) { getInfo(node).parent = parent; } @Nullable private T getAncestor(@Nullable T node) { return getInfo(node).ancestor; } private void setAncestor(@Nullable T node, @Nullable T ancestor) { getInfo(node).ancestor = ancestor; } @Nullable private T getLabel(@Nullable T node) { if (node == null) return null; else return getInfo(node).label; } private void setLabel(@Nullable T node, @Nullable T label) { getInfo(node).label = label; } private int getSize(@Nullable T node) { if (node == null) return 0; else return getInfo(node).size; } private void setSize(@Nullable T node, int size) { getInfo(node).size = size; } @Nullable private T getChild(@Nullable T node) { return getInfo(node).child; } private void setChild(@Nullable T node, @Nullable T child) { getInfo(node).child = child; } private int getSemi(@Nullable T node) { if (node == null) return 0; else return getInfo(node).semiDominator; } private void setSemi(T node, int semi) { getInfo(node).semiDominator = semi; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (T node : G) { sb.append("Dominators of ").append(node).append(":\n"); for (T dom : Iterator2Iterable.make(dominators(node))) sb.append(" ").append(dom).append('\n'); sb.append('\n'); } return sb.toString(); } }
16,024
27.616071
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/dominators/GenericDominators.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.dominators; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.graph.Graph; import java.util.Map; import org.jspecify.annotations.Nullable; /** * Calculate dominators using Langauer and Tarjan's fastest algorithm. TOPLAS 1(1), July 1979. This * implementation uses path compression and results in a O(e * alpha(e,n)) complexity, where e is * the number of edges in the CFG and n is the number of nodes. * * <p>Sources: TOPLAS article, Muchnick book */ public class GenericDominators<T> extends Dominators<T> { public GenericDominators(Graph<T> G, T root) throws IllegalArgumentException { super(G, root); this.infoMap = HashMapFactory.make(G.getNumberOfNodes()); analyze(); } /* * Look-aside table for DominatorInfo objects */ private final Map<Object, DominatorInfo> infoMap; @Override protected DominatorInfo getInfo(@Nullable T node) { if (!infoMap.containsKey(node)) infoMap.put(node, new DominatorInfo(node)); return infoMap.get(node); } }
1,430
31.522727
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/dominators/NumberedDominators.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.dominators; import com.ibm.wala.util.graph.NumberedGraph; import org.jspecify.annotations.Nullable; /** * Calculate dominators using Langauer and Tarjan's fastest algorithm. TOPLAS 1(1), July 1979. This * implementation uses path compression and results in a O(e * alpha(e,n)) complexity, where e is * the number of edges in the CFG and n is the number of nodes. * * <p>Sources: TOPLAS article, Muchnick book */ public class NumberedDominators<T> extends Dominators<T> { public NumberedDominators(NumberedGraph<T> G, T root) throws IllegalArgumentException { super(G, root); this.infoMap = new Object[G.getMaxNumber() + 1]; for (T n : G) { infoMap[G.getNumber(n)] = new DominatorInfo(n); } analyze(); } /* * Look-aside table for DominatorInfo objects */ private final Object[] infoMap; @SuppressWarnings("unchecked") @Override protected final DominatorInfo getInfo(@Nullable T node) { assert node != null; return (DominatorInfo) infoMap[((NumberedGraph<T>) G).getNumber(node)]; } }
1,458
29.395833
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/BasicEdgeManager.java
/* * Copyright (c) 2021 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Manu Sridharan - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.graph.EdgeManager; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.jspecify.annotations.Nullable; /** * Simple implementation of an {@link com.ibm.wala.util.graph.EdgeManager}. Does not support edge * deletion. */ public class BasicEdgeManager<T> implements EdgeManager<T> { private final Map<T, Set<T>> preds = HashMapFactory.make(); private final Map<T, Set<T>> succs = HashMapFactory.make(); @Override public Iterator<T> getPredNodes(@Nullable T n) { Set<T> nodePreds = this.preds.get(n); return nodePreds != null ? nodePreds.iterator() : Collections.emptyIterator(); } @Override public int getPredNodeCount(T n) { Set<T> nodePreds = this.preds.get(n); return nodePreds != null ? nodePreds.size() : 0; } @Override public Iterator<T> getSuccNodes(@Nullable T n) { Set<T> nodeSuccs = this.succs.get(n); return nodeSuccs != null ? nodeSuccs.iterator() : Collections.emptyIterator(); } @Override public int getSuccNodeCount(T n) { Set<T> nodeSuccs = this.succs.get(n); return nodeSuccs != null ? nodeSuccs.size() : 0; } @Override public void addEdge(T src, T dst) { MapUtil.findOrCreateSet(succs, src).add(dst); MapUtil.findOrCreateSet(preds, dst).add(src); } @Override public void removeEdge(T src, T dst) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeAllIncidentEdges(T node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeIncomingEdges(T node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeOutgoingEdges(T node) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { Set<T> succsForSrc = succs.get(src); return succsForSrc != null && succsForSrc.contains(dst); } }
2,599
28.885057
97
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/BasicGraph.java
/* * Copyright (c) 2021 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Manu Sridharan - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.AbstractGraph; import com.ibm.wala.util.graph.EdgeManager; import com.ibm.wala.util.graph.NodeManager; /** * Basic implementation of a {@link com.ibm.wala.util.graph.Graph}. Does not support node or edge * deletion. */ public class BasicGraph<T> extends AbstractGraph<T> { private final NodeManager<T> nodeManager = new BasicNodeManager<>(); private final EdgeManager<T> edgeManager = new BasicEdgeManager<>(); @Override protected NodeManager<T> getNodeManager() { return nodeManager; } @Override protected EdgeManager<T> getEdgeManager() { return edgeManager; } }
1,034
26.972973
97
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/BasicNodeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.graph.NodeManager; import java.util.HashSet; import java.util.Iterator; import java.util.stream.Stream; import org.jspecify.annotations.Nullable; /** Simple implementation of a {@link NodeManager}. */ public class BasicNodeManager<T> implements NodeManager<T> { private final HashSet<T> nodes = HashSetFactory.make(); @Override public Stream<T> stream() { return nodes.stream(); } @Override public Iterator<T> iterator() { return nodes.iterator(); } @Override public int getNumberOfNodes() { return nodes.size(); } @Override public void addNode(T n) { nodes.add(n); } @Override public void removeNode(T n) { nodes.remove(n); } @Override public boolean containsNode(@Nullable T N) { return nodes.contains(N); } }
1,275
21.785714
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/BasicOrderedMultiGraph.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.SimpleVector; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.OrderedMultiGraph; import java.util.Iterator; import java.util.Map; import java.util.stream.Stream; import org.jspecify.annotations.Nullable; /** * Inefficient implementation of OrderedMultiGraph. * * <p>UNDER CONSTRUCTION. * * @param <T> type of node in the graph */ public class BasicOrderedMultiGraph<T> implements OrderedMultiGraph<T> { final Map<T, SimpleVector<T>> successorEdges = HashMapFactory.make(); private final Graph<T> delegate; public BasicOrderedMultiGraph() { this.delegate = SlowSparseNumberedGraph.make(); } /** Add this edge, unconditionally setting it as the next successor. */ @Override public void addEdge(T src, T dst) throws IllegalArgumentException { delegate.addEdge(src, dst); SimpleVector<T> s = successorEdges.get(src); if (s == null) { s = new SimpleVector<>(); successorEdges.put(src, s); } s.set(s.getMaxIndex() + 1, dst); } @Override public void addEdge(int i, T src, T dst) throws IllegalArgumentException { delegate.addEdge(src, dst); SimpleVector<T> s = successorEdges.get(src); if (s == null) { s = new SimpleVector<>(); successorEdges.put(src, s); } s.set(i, dst); } @Override public void addNode(T n) { delegate.addNode(n); } @Override public boolean containsNode(@Nullable T N) { return delegate.containsNode(N); } @Override public int getNumberOfNodes() { return delegate.getNumberOfNodes(); } @Override public int getPredNodeCount(T N) throws IllegalArgumentException { return delegate.getPredNodeCount(N); } /** For now, this returns nodes in no particular order! Fix this when needed. */ @Override public Iterator<T> getPredNodes(@Nullable T N) throws IllegalArgumentException { return delegate.getPredNodes(N); } @Override public int getSuccNodeCount(T N) throws IllegalArgumentException { return delegate.getSuccNodeCount(N); } @Override public Iterator<T> getSuccNodes(@Nullable T N) throws IllegalArgumentException { return delegate.getSuccNodes(N); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { return delegate.hasEdge(src, dst); } @Override public Iterator<T> iterator() { return delegate.iterator(); } @Override public Stream<T> stream() { return delegate.stream(); } @Override public void removeAllIncidentEdges(T node) throws UnimplementedError { Assertions.UNREACHABLE(); delegate.removeAllIncidentEdges(node); } @Override public void removeEdge(T src, T dst) throws UnimplementedError { Assertions.UNREACHABLE(); delegate.removeEdge(src, dst); } @Override public void removeIncomingEdges(T node) throws UnimplementedError { Assertions.UNREACHABLE(); delegate.removeIncomingEdges(node); } @Override public void removeNode(T n) throws UnimplementedError { Assertions.UNREACHABLE(); delegate.removeNode(n); } @Override public void removeNodeAndEdges(T N) throws UnimplementedError { Assertions.UNREACHABLE(); delegate.removeNodeAndEdges(N); } @Override public void removeOutgoingEdges(T node) throws UnimplementedError { Assertions.UNREACHABLE(); delegate.removeOutgoingEdges(node); } @Override public T getSuccessor(T node, int i) throws IllegalArgumentException { SimpleVector<T> s = successorEdges.get(node); if (s == null) { throw new IllegalArgumentException("no successors for node " + node); } if (i > s.getMaxIndex()) { throw new IllegalArgumentException("no successor number " + i + " for " + node); } return s.get(i); } }
4,332
25.582822
86
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/DelegatingGraph.java
/* * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.Graph; import java.util.Iterator; import java.util.stream.Stream; import org.jspecify.annotations.Nullable; /** A utility class. */ public class DelegatingGraph<T> implements Graph<T> { private final Graph<T> delegate; public DelegatingGraph(Graph<T> delegate) { if (delegate == null) { throw new IllegalArgumentException("delegate is null"); } this.delegate = delegate; } @Override public void addEdge(T src, T dst) throws IllegalArgumentException { delegate.addEdge(src, dst); } @Override public void addNode(T n) { delegate.addNode(n); } @Override public boolean containsNode(@Nullable T N) { return delegate.containsNode(N); } @Override public int getNumberOfNodes() { return delegate.getNumberOfNodes(); } @Override public String toString() { return delegate.toString(); } @Override public int getPredNodeCount(T N) throws IllegalArgumentException { return delegate.getPredNodeCount(N); } @Override public Iterator<T> getPredNodes(@Nullable T N) throws IllegalArgumentException { return delegate.getPredNodes(N); } @Override public int getSuccNodeCount(T N) throws IllegalArgumentException { return delegate.getSuccNodeCount(N); } @Override public Iterator<T> getSuccNodes(@Nullable T N) throws IllegalArgumentException { return delegate.getSuccNodes(N); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { return delegate.hasEdge(src, dst); } @Override public Iterator<T> iterator() { return delegate.iterator(); } @Override public Stream<T> stream() { return delegate.stream(); } @Override public void removeAllIncidentEdges(T node) throws IllegalArgumentException { delegate.removeAllIncidentEdges(node); } @Override public void removeEdge(T src, T dst) throws IllegalArgumentException { delegate.removeEdge(src, dst); } @Override public void removeIncomingEdges(T node) throws IllegalArgumentException { delegate.removeIncomingEdges(node); } @Override public void removeNode(T n) { delegate.removeNode(n); } @Override public void removeNodeAndEdges(T N) throws IllegalArgumentException { delegate.removeNodeAndEdges(N); } @Override public void removeOutgoingEdges(T node) throws IllegalArgumentException { delegate.removeOutgoingEdges(node); } }
2,837
22.65
82
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/DelegatingNumberedEdgeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.INodeWithNumberedEdges; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.SparseIntSet; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** An object that delegates edge management to the nodes, {@link INodeWithNumberedEdges} */ public class DelegatingNumberedEdgeManager<T extends INodeWithNumberedEdges> implements NumberedEdgeManager<T> { private final DelegatingNumberedNodeManager<T> nodeManager; public DelegatingNumberedEdgeManager(DelegatingNumberedNodeManager<T> nodeManager) { if (nodeManager == null) { throw new IllegalArgumentException("nodeManager is null"); } this.nodeManager = nodeManager; } // TODO: optimization is possible private class IntSetNodeIterator implements Iterator<T> { private final IntIterator delegate; IntSetNodeIterator(IntIterator delegate) { this.delegate = delegate; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public T next() { return nodeManager.getNode(delegate.next()); } @Override public void remove() { // TODO Auto-generated method stub Assertions.UNREACHABLE(); } } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(Object) */ @Override public Iterator<T> getPredNodes(@Nullable T N) throws IllegalArgumentException { if (N == null) { throw new IllegalArgumentException("N cannot be null"); } INodeWithNumberedEdges en = N; IntSet pred = en.getPredNumbers(); Iterator<T> empty = EmptyIterator.instance(); return (pred == null) ? empty : (Iterator<T>) new IntSetNodeIterator(pred.intIterator()); } @Override public IntSet getPredNodeNumbers(@Nullable T node) { if (node == null) { throw new IllegalArgumentException("N cannot be null"); } INodeWithNumberedEdges en = node; IntSet pred = en.getPredNumbers(); return (pred == null) ? new SparseIntSet() : pred; } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(Object) */ @Override public int getPredNodeCount(T N) throws IllegalArgumentException { if (N == null) { throw new IllegalArgumentException("N cannot be null"); } INodeWithNumberedEdges en = N; IntSet s = en.getPredNumbers(); if (s == null) { return 0; } else { return s.size(); } } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(Object) */ @Override public Iterator<T> getSuccNodes(@Nullable T N) { if (N == null) { throw new IllegalArgumentException("N cannot be null"); } INodeWithNumberedEdges en = N; IntSet succ = en.getSuccNumbers(); Iterator<T> empty = EmptyIterator.instance(); return (succ == null) ? empty : (Iterator<T>) new IntSetNodeIterator(succ.intIterator()); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(Object) */ @Override public int getSuccNodeCount(T N) { if (N == null) { throw new IllegalArgumentException("N is null"); } INodeWithNumberedEdges en = N; IntSet s = en.getSuccNumbers(); return s == null ? 0 : s.size(); } /** @see com.ibm.wala.util.graph.EdgeManager#addEdge(Object, Object) */ @Override public void addEdge(T src, T dst) { if (dst == null || src == null) { throw new IllegalArgumentException("parameter is null"); } src.addSucc(dst.getGraphNodeId()); dst.addPred(src.getGraphNodeId()); } @Override public void removeEdge(T src, T dst) throws UnimplementedError { Assertions.UNREACHABLE("Implement me"); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeAllIncidentEdges(T node) throws UnimplementedError { if (node == null) { throw new IllegalArgumentException("node is null"); } INodeWithNumberedEdges n = node; n.removeAllIncidentEdges(); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeIncomingEdges(T node) throws UnimplementedError { if (node == null) { throw new IllegalArgumentException("node cannot be null"); } INodeWithNumberedEdges n = node; n.removeIncomingEdges(); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeOutgoingEdges(T node) throws UnimplementedError { if (node == null) { throw new IllegalArgumentException("node cannot be null"); } INodeWithNumberedEdges n = node; n.removeOutgoingEdges(); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) throws IllegalArgumentException { if (dst == null) { throw new IllegalArgumentException("dst == null"); } return getSuccNodeNumbers(src).contains(dst.getGraphNodeId()); } @Override public IntSet getSuccNodeNumbers(@Nullable T node) { if (node == null) { throw new IllegalArgumentException("node cannot be null"); } INodeWithNumberedEdges en = node; IntSet succ = en.getSuccNumbers(); return (succ == null) ? new SparseIntSet() : succ; } }
5,830
30.349462
93
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/DelegatingNumberedGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.AbstractNumberedGraph; import com.ibm.wala.util.graph.INodeWithNumberedEdges; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedNodeManager; /** * Basic functionality for a graph that delegates node and edge management, and tracks node numbers */ public class DelegatingNumberedGraph<T extends INodeWithNumberedEdges> extends AbstractNumberedGraph<T> { private final DelegatingNumberedNodeManager<T> nodeManager = new DelegatingNumberedNodeManager<>(); private final DelegatingNumberedEdgeManager<T> edgeManager = new DelegatingNumberedEdgeManager<>(nodeManager); /** @see com.ibm.wala.util.graph.AbstractGraph#getNodeManager() */ @Override protected NumberedNodeManager<T> getNodeManager() { return nodeManager; } /** @see com.ibm.wala.util.graph.AbstractGraph#getEdgeManager() */ @Override protected NumberedEdgeManager<T> getEdgeManager() { return edgeManager; } }
1,405
32.47619
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/DelegatingNumberedNodeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.INodeWithNumber; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.intset.IntSet; import java.util.Arrays; import java.util.Iterator; import java.util.Objects; import java.util.stream.Stream; import org.jspecify.annotations.Nullable; /** * Basic implementation of a numbered graph -- this implementation relies on nodes that carry * numbers and edges. * * <p>The management of node numbers is a bit fragile, but designed this way for efficiency. Use * this class with care. */ public class DelegatingNumberedNodeManager<T extends INodeWithNumber> implements NumberedNodeManager<T> { private final double BUFFER_FACTOR = 1.5; private INodeWithNumber[] nodes = new INodeWithNumber[20]; private int maxNumber = -1; private int numberOfNodes = 0; @Override public int getNumber(@Nullable T N) { if (N == null) { throw new IllegalArgumentException("N is null"); } INodeWithNumber n = N; return n.getGraphNodeId(); } @Override @SuppressWarnings("unchecked") public T getNode(int number) { try { return (T) nodes[number]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Invalid number " + number, e); } } @Override public int getMaxNumber() { return maxNumber; } /** @see com.ibm.wala.util.graph.Graph#iterator() */ @Override @SuppressWarnings("unused") public Iterator<T> iterator() { final INodeWithNumber[] arr = nodes; return new Iterator<T>() { int nextCounter = -1; { advance(); } void advance() { for (int i = nextCounter + 1; i < arr.length; i++) { if (arr[i] != null) { nextCounter = i; return; } } nextCounter = -1; } @Override public boolean hasNext() { return nextCounter != -1; } @Nullable @Override @SuppressWarnings("unchecked") public T next() { if (hasNext()) { int r = nextCounter; advance(); return (T) arr[r]; } else { return null; } } @Override public void remove() { Assertions.UNREACHABLE(); } }; } @SuppressWarnings("unchecked") @Override public Stream<T> stream() { return Arrays.stream(nodes).filter(Objects::nonNull).map(node -> (T) node); } /** @see com.ibm.wala.util.graph.Graph#getNumberOfNodes() */ @Override public int getNumberOfNodes() { return numberOfNodes; } /** * If N.getNumber() == -1, then set N.number and insert this node in the graph. Use with extreme * care. * * @see com.ibm.wala.util.graph.NodeManager#addNode(java.lang.Object) * @throws IllegalArgumentException if n is null */ @Override public void addNode(T n) { if (n == null) { throw new IllegalArgumentException("n is null"); } INodeWithNumber N = n; int number = N.getGraphNodeId(); if (number == -1) { maxNumber++; N.setGraphNodeId(maxNumber); number = maxNumber; } else { if (number > maxNumber) { maxNumber = number; } } ensureCapacity(number); if (nodes[number] != null && nodes[number] != N) { Assertions.UNREACHABLE("number: " + number + " N: " + N + " nodes[number]: " + nodes[number]); } nodes[number] = N; numberOfNodes++; } private void ensureCapacity(int number) { if (nodes.length < number + 1) { int newLength = (int) ((number + 1) * BUFFER_FACTOR); nodes = Arrays.copyOf(nodes, newLength); } } /** @see com.ibm.wala.util.graph.NodeManager#removeNode(Object) */ @Override public void removeNode(T n) { if (n == null) { throw new IllegalArgumentException("n is null"); } INodeWithNumber N = n; int number = N.getGraphNodeId(); if (number == -1) { throw new IllegalArgumentException("Cannot remove node, not in graph"); } if (nodes[number] != null) { nodes[number] = null; numberOfNodes--; } } @Override public String toString() { StringBuilder result = new StringBuilder("Nodes:\n"); for (int i = 0; i <= maxNumber; i++) { result.append(i).append(' '); if (nodes[i] != null) { result.append(nodes[i].toString()); } result.append('\n'); } return result.toString(); } /** @see com.ibm.wala.util.graph.NodeManager#containsNode(Object) */ @Override public boolean containsNode(@Nullable T n) { if (n == null) { throw new IllegalArgumentException("n is null"); } INodeWithNumber N = n; int number = N.getGraphNodeId(); if (number == -1) { return false; } if (number >= nodes.length) { throw new IllegalArgumentException( "node already has a graph node id, but is not registered there in this graph (number too big)\n" + "this graph implementation is fragile and won't support this kind of test\n" + n.getClass() + " : " + n); } if (nodes[number] != N) { throw new IllegalArgumentException( "node already has a graph node id, but is not registered there in this graph\n" + "this graph implementation is fragile and won't support this kind of test\n" + n.getClass() + " : " + n); } return true; // return (nodes[number] == N); } @Override public Iterator<T> iterateNodes(IntSet s) { return new NumberedNodeIterator<>(s, this); } }
6,077
25.657895
106
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/ExtensionGraph.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.collections.CompoundIterator; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.intset.EmptyIntSet; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.Iterator; import java.util.Map; import java.util.stream.Stream; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; public class ExtensionGraph<T> implements NumberedGraph<T> { private final NumberedGraph<T> original; private final NumberedNodeManager<T> additionalNodes = new SlowNumberedNodeManager<>(); private final NumberedEdgeManager<T> edgeManager = new NumberedEdgeManager<>() { private final Map<T, MutableIntSet> inEdges = HashMapFactory.make(); private final Map<T, MutableIntSet> outEdges = HashMapFactory.make(); private Iterator<T> nodes(@Nullable final T node, final Map<T, ? extends IntSet> extra) { if (extra.containsKey(node)) { return new Iterator<>() { private final IntIterator i = extra.get(node).intIterator(); @Override public boolean hasNext() { return i.hasNext(); } @Override public T next() { return ExtensionGraph.this.getNode(i.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } else { return EmptyIterator.instance(); } } @Override public Iterator<T> getPredNodes(@Nullable T n) { Iterator<T> orig = (original.containsNode(n) ? original.getPredNodes(n) : EmptyIterator.<T>instance()); return new CompoundIterator<>(orig, nodes(n, inEdges)); } @Override public int getPredNodeCount(T n) { return (original.containsNode(n) ? original.getPredNodeCount(n) : 0) + (inEdges.containsKey(n) ? inEdges.get(n).size() : 0); } @Override public Iterator<T> getSuccNodes(@Nullable T n) { Iterator<T> orig = (original.containsNode(n) ? original.getSuccNodes(n) : EmptyIterator.<T>instance()); return new CompoundIterator<>(orig, nodes(n, outEdges)); } @Override public int getSuccNodeCount(T n) { return (original.containsNode(n) ? original.getSuccNodeCount(n) : 0) + (outEdges.containsKey(n) ? outEdges.get(n).size() : 0); } @Override public void addEdge(T src, T dst) { assert !original.hasEdge(src, dst); assert containsNode(src) && containsNode(dst); if (!inEdges.containsKey(dst)) { inEdges.put(dst, IntSetUtil.make()); } inEdges.get(dst).add(getNumber(src)); if (!outEdges.containsKey(src)) { outEdges.put(src, IntSetUtil.make()); } outEdges.get(src).add(getNumber(dst)); } @NullUnmarked @Override public void removeEdge(T src, T dst) throws UnsupportedOperationException { assert hasEdge(src, dst); assert !original.hasEdge(src, dst); assert containsNode(src) && containsNode(dst); inEdges.get(dst).remove(getNumber(src)); outEdges.get(src).remove(getNumber(dst)); } @Override public void removeAllIncidentEdges(T node) throws UnsupportedOperationException { removeIncomingEdges(node); removeOutgoingEdges(node); } @Override public void removeIncomingEdges(T node) throws UnsupportedOperationException { assert !original.containsNode(node) || original.getPredNodeCount(node) == 0; inEdges.remove(node); } @Override public void removeOutgoingEdges(T node) throws UnsupportedOperationException { assert !original.containsNode(node) || original.getSuccNodeCount(node) == 0; outEdges.remove(node); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { return original.hasEdge(src, dst) || (outEdges.containsKey(src) && outEdges.get(src).contains(getNumber(dst))); } @Override public IntSet getSuccNodeNumbers(@Nullable T node) { if (original.containsNode(node)) { if (outEdges.containsKey(node)) { MutableIntSet x = IntSetUtil.makeMutableCopy(original.getSuccNodeNumbers(node)); x.addAll(outEdges.get(node)); return x; } else { return original.getSuccNodeNumbers(node); } } else { if (outEdges.containsKey(node)) { return outEdges.get(node); } else { return EmptyIntSet.instance; } } } @Override public IntSet getPredNodeNumbers(@Nullable T node) { if (original.containsNode(node)) { if (inEdges.containsKey(node)) { MutableIntSet x = IntSetUtil.makeMutableCopy(original.getPredNodeNumbers(node)); x.addAll(inEdges.get(node)); return x; } else { return original.getPredNodeNumbers(node); } } else { if (inEdges.containsKey(node)) { return inEdges.get(node); } else { return EmptyIntSet.instance; } } } }; public ExtensionGraph(NumberedGraph<T> original) { this.original = original; } @Override public Iterator<T> iterator() { return new CompoundIterator<>(original.iterator(), additionalNodes.iterator()); } @Override public Stream<T> stream() { return Stream.concat(original.stream(), additionalNodes.stream()); } @Override public int getNumberOfNodes() { return original.getNumberOfNodes() + additionalNodes.getNumberOfNodes(); } @Override public void addNode(T n) { assert !original.containsNode(n); additionalNodes.addNode(n); } @Override public void removeNode(T n) throws UnsupportedOperationException { assert !original.containsNode(n); additionalNodes.removeNode(n); } @Override public boolean containsNode(@Nullable T n) { return original.containsNode(n) || additionalNodes.containsNode(n); } @Override public int getNumber(@Nullable T N) { if (original.containsNode(N)) { return original.getNumber(N); } else { return additionalNodes.getNumber(N) + original.getMaxNumber() + 1; } } @Override public T getNode(int number) { if (number <= original.getMaxNumber()) { return original.getNode(number); } else { return additionalNodes.getNode(number - original.getMaxNumber() - 1); } } @Override public int getMaxNumber() { if (additionalNodes.iterator().hasNext()) { return original.getMaxNumber() + 1 + additionalNodes.getMaxNumber(); } else { return original.getMaxNumber(); } } @Override public Iterator<T> iterateNodes(IntSet s) { final MutableIntSet os = IntSetUtil.make(); final MutableIntSet es = IntSetUtil.make(); s.foreach( x -> { if (x <= original.getMaxNumber()) { os.add(x); } else { es.add(x - original.getMaxNumber() - 1); } }); return new CompoundIterator<>(original.iterateNodes(os), additionalNodes.iterateNodes(es)); } @Override public Iterator<T> getPredNodes(@Nullable T n) { return edgeManager.getPredNodes(n); } @Override public int getPredNodeCount(T n) { return edgeManager.getPredNodeCount(n); } @Override public IntSet getPredNodeNumbers(@Nullable T node) { return edgeManager.getPredNodeNumbers(node); } @Override public Iterator<T> getSuccNodes(@Nullable T n) { return edgeManager.getSuccNodes(n); } @Override public int getSuccNodeCount(T N) { return edgeManager.getSuccNodeCount(N); } @Override public IntSet getSuccNodeNumbers(@Nullable T node) { return edgeManager.getSuccNodeNumbers(node); } @Override public void addEdge(T src, T dst) { assert !original.hasEdge(src, dst); edgeManager.addEdge(src, dst); } @Override public void removeEdge(T src, T dst) throws UnsupportedOperationException { assert !original.hasEdge(src, dst); edgeManager.removeEdge(src, dst); } @Override public void removeAllIncidentEdges(T node) throws UnsupportedOperationException { assert !original.containsNode(node); edgeManager.removeAllIncidentEdges(node); } @Override public void removeIncomingEdges(T node) throws UnsupportedOperationException { assert !original.containsNode(node); edgeManager.removeIncomingEdges(node); } @Override public void removeOutgoingEdges(T node) throws UnsupportedOperationException { assert !original.containsNode(node); edgeManager.removeOutgoingEdges(node); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { return edgeManager.hasEdge(src, dst); } @Override public void removeNodeAndEdges(T n) throws UnsupportedOperationException { assert !original.containsNode(n); edgeManager.removeAllIncidentEdges(n); additionalNodes.removeNode(n); } }
10,174
30.116208
98
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/GraphInverter.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NumberedGraph; /** A graph view that reverses the edges in a graph */ public class GraphInverter { public static <T> NumberedGraph<T> invert(final NumberedGraph<T> G) { return new InvertedNumberedGraph<>(G); } /** @return A graph view that reverses the edges in G */ public static <T> Graph<T> invert(final Graph<T> G) { if (G instanceof NumberedGraph) { return new InvertedNumberedGraph<>((NumberedGraph<T>) G); } else { return new InvertedGraph<>(G); } } }
983
29.75
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/InvertedGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.AbstractGraph; import com.ibm.wala.util.graph.EdgeManager; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NodeManager; /** A graph view that reverses the edges in a graph */ public class InvertedGraph<T> extends AbstractGraph<T> { private final NodeManager<T> nodes; @Override protected NodeManager<T> getNodeManager() { return nodes; } private final EdgeManager<T> edges; @Override protected EdgeManager<T> getEdgeManager() { return edges; } public InvertedGraph(Graph<T> G) { nodes = G; edges = new InvertingEdgeManager<>(G); } }
1,041
25.05
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/InvertedNumberedGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.AbstractNumberedGraph; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.graph.NumberedNodeManager; /** A graph view that reverses the edges in a graph */ public class InvertedNumberedGraph<T> extends AbstractNumberedGraph<T> { private final NumberedNodeManager<T> nodes; private final NumberedEdgeManager<T> edges; @Override protected NumberedNodeManager<T> getNodeManager() { return nodes; } @Override protected NumberedEdgeManager<T> getEdgeManager() { return edges; } InvertedNumberedGraph(NumberedGraph<T> G) { nodes = G; edges = new InvertingNumberedEdgeManager<>(G); } }
1,137
28.179487
72
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/InvertingEdgeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.EdgeManager; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** An edge manager that reverses the edges in a graph */ public class InvertingEdgeManager<T> implements EdgeManager<T> { private final EdgeManager<T> original; public InvertingEdgeManager(EdgeManager<T> original) { if (original == null) { throw new IllegalArgumentException("original is null"); } this.original = original; } @Override public Iterator<T> getPredNodes(@Nullable T N) throws IllegalArgumentException { return original.getSuccNodes(N); } @Override public int getPredNodeCount(T N) throws IllegalArgumentException { return original.getSuccNodeCount(N); } @Override public Iterator<T> getSuccNodes(@Nullable T N) throws IllegalArgumentException { return original.getPredNodes(N); } @Override public int getSuccNodeCount(T N) throws IllegalArgumentException { return original.getPredNodeCount(N); } @Override public void addEdge(T src, T dst) throws IllegalArgumentException { original.addEdge(dst, src); } @Override public void removeEdge(T src, T dst) throws IllegalArgumentException { original.removeEdge(dst, src); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { return original.hasEdge(dst, src); } @Override public void removeAllIncidentEdges(T node) throws IllegalArgumentException { original.removeAllIncidentEdges(node); } @Override public void removeIncomingEdges(T node) throws IllegalArgumentException { original.removeOutgoingEdges(node); } @Override public void removeOutgoingEdges(T node) throws IllegalArgumentException { original.removeIncomingEdges(node); } }
2,177
26.56962
82
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/InvertingNumberedEdgeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.intset.IntSet; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** An edge manager that reverses the edges in a graph */ public class InvertingNumberedEdgeManager<T> implements NumberedEdgeManager<T> { private final NumberedEdgeManager<T> original; public InvertingNumberedEdgeManager(NumberedEdgeManager<T> original) { if (original == null) { throw new IllegalArgumentException("null original"); } this.original = original; } @Override public Iterator<T> getPredNodes(@Nullable T N) throws IllegalArgumentException { return original.getSuccNodes(N); } @Override public int getPredNodeCount(T N) throws IllegalArgumentException { return original.getSuccNodeCount(N); } @Override public Iterator<T> getSuccNodes(@Nullable T N) throws IllegalArgumentException { return original.getPredNodes(N); } @Override public int getSuccNodeCount(T N) throws IllegalArgumentException { return original.getPredNodeCount(N); } @Override public void addEdge(T src, T dst) throws IllegalArgumentException { original.addEdge(dst, src); } @Override public void removeEdge(T src, T dst) throws IllegalArgumentException { original.removeEdge(dst, src); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { return original.hasEdge(dst, src); } @Override public void removeAllIncidentEdges(T node) throws IllegalArgumentException { original.removeAllIncidentEdges(node); } @Override public void removeIncomingEdges(T node) throws IllegalArgumentException { original.removeOutgoingEdges(node); } @Override public void removeOutgoingEdges(T node) throws IllegalArgumentException { original.removeIncomingEdges(node); } @Override public IntSet getSuccNodeNumbers(@Nullable T node) throws IllegalArgumentException { return original.getPredNodeNumbers(node); } @Override public IntSet getPredNodeNumbers(@Nullable T node) throws IllegalArgumentException { return original.getSuccNodeNumbers(node); } }
2,562
27.477778
86
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/NodeWithNumber.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.INodeWithNumber; import com.ibm.wala.util.graph.NumberedGraph; /** * A node which carries it's own number; which identifies it in a {@link NumberedGraph} * implementation. * * <p>Note that a {@link NodeWithNumber} can live it at most one {@link NumberedGraph} at a time. * The {@link NumberedGraph} will mutate the number here. So this is a bit fragile. Use this only if * you know what you're doing. */ public class NodeWithNumber implements INodeWithNumber { private int number = -1; /** @return the number which identifies this node in the numbered graph */ @Override public int getGraphNodeId() { return number; } @Override public void setGraphNodeId(int i) { number = i; } }
1,160
28.769231
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/NodeWithNumberedEdges.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.INodeWithNumberedEdges; import com.ibm.wala.util.intset.BimodalMutableIntSet; import com.ibm.wala.util.intset.IntSet; import org.jspecify.annotations.Nullable; /** Simple implementation of {@link INodeWithNumberedEdges} */ public class NodeWithNumberedEdges extends NodeWithNumber implements INodeWithNumberedEdges { @Nullable private BimodalMutableIntSet predNumbers; @Nullable private BimodalMutableIntSet succNumbers; @Nullable @Override public IntSet getSuccNumbers() { return succNumbers; } @Nullable @Override public IntSet getPredNumbers() { return predNumbers; } /** * Note that this variable appears on the RHS of an equation. * * @param eqNumber the equation number */ @Override public void addSucc(int eqNumber) { if (succNumbers == null) { succNumbers = new BimodalMutableIntSet(); } succNumbers.add(eqNumber); } /** * Note that this variable appears on the LHS of an equation. * * @param eqNumber the equation number */ @Override public void addPred(int eqNumber) { if (predNumbers == null) { predNumbers = new BimodalMutableIntSet(); } predNumbers.add(eqNumber); } /** remove the edge that indicates this variable is Succd by a certain equation */ public void deleteSucc(int eqNumber) { if (succNumbers != null) { succNumbers.remove(eqNumber); if (succNumbers.size() == 0) { succNumbers = null; } } } /** remove the edge that indicates this variable is Predined by a certain equation */ public void deletePred(int eqNumber) { if (predNumbers != null) { predNumbers.remove(eqNumber); if (predNumbers.size() == 0) { predNumbers = null; } } } @Override public void removeAllIncidentEdges() throws UnimplementedError { Assertions.UNREACHABLE("Implement me"); } @Override public void removeIncomingEdges() throws UnimplementedError { Assertions.UNREACHABLE("Implement me"); } @Override public void removeOutgoingEdges() throws UnimplementedError { Assertions.UNREACHABLE("Implement me"); } }
2,666
25.67
93
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/NumberedNodeIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import java.util.Iterator; import java.util.NoSuchElementException; /** */ public class NumberedNodeIterator<T> implements Iterator<T> { final IntIterator numbers; final NumberedNodeManager<T> nodeManager; /** @throws IllegalArgumentException if s is null */ public NumberedNodeIterator(IntSet s, NumberedNodeManager<T> nodeManager) { if (s == null) { throw new IllegalArgumentException("s is null"); } this.numbers = s.intIterator(); this.nodeManager = nodeManager; } @Override public boolean hasNext() { return numbers.hasNext(); } @Override public T next() throws NoSuchElementException { int i = numbers.next(); T result = nodeManager.getNode(i); assert result != null : "null node for " + i; return result; } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } }
1,462
27.134615
77
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/RandomGraph.java
package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.collections.Pair; import java.util.ArrayList; import java.util.Collections; import java.util.List; public abstract class RandomGraph<T> extends SlowSparseNumberedGraph<T> { /** */ private static final long serialVersionUID = 5950736619507540953L; protected abstract T makeNode(int i); public RandomGraph(int nodes, int edges) { for (int i = 0; i < nodes; i++) { addNode(makeNode(i)); } List<Pair<Integer, Integer>> allEdges = new ArrayList<>(nodes * nodes); for (int i = 0; i < nodes; i++) { for (int j = 0; j < nodes; j++) { allEdges.add(Pair.make(i, j)); } } Collections.shuffle(allEdges); for (int i = 0; i < edges; i++) { addEdge(getNode(allEdges.get(i).fst), getNode(allEdges.get(i).snd)); } } public static class IntegerRandomGraph extends RandomGraph<Integer> { /** */ private static final long serialVersionUID = -4216451570756483022L; @Override protected Integer makeNode(int i) { return i; } public IntegerRandomGraph(int nodes, int edges) { super(nodes, edges); } } }
1,172
22.938776
75
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/SelfLoopAddedEdgeManager.java
package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.EdgeManager; import java.util.Iterator; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; public class SelfLoopAddedEdgeManager<T> implements EdgeManager<T> { private class PrependItterator implements Iterator<T> { private boolean usedFirst = false; private final Iterator<T> original; @Nullable private T first; public PrependItterator(Iterator<T> original, @Nullable T first) { super(); this.original = original; this.first = first; } @Override public boolean hasNext() { if (!usedFirst) { return true; } else { return original.hasNext(); } } @Nullable @Override public T next() { if (!usedFirst) { T tmp = first; first = null; usedFirst = true; return tmp; } else { return original.next(); } } @Override public void remove() { assert false; } } private final EdgeManager<T> original; public SelfLoopAddedEdgeManager(EdgeManager<T> original) { if (original == null) { throw new IllegalArgumentException("original is null"); } this.original = original; } @Override public Iterator<T> getPredNodes(@Nullable T n) { if (original.hasEdge(n, n)) { return original.getPredNodes(n); } else { return new PrependItterator(original.getPredNodes(n), n); } } @Override public int getPredNodeCount(T n) { if (original.hasEdge(n, n)) { return original.getPredNodeCount(n); } else { return original.getPredNodeCount(n) + 1; } } @Override public Iterator<T> getSuccNodes(@Nullable T n) { if (original.hasEdge(n, n)) { return original.getSuccNodes(n); } else { return new PrependItterator(original.getSuccNodes(n), n); } } @Override public int getSuccNodeCount(T n) { if (original.hasEdge(n, n)) { return original.getSuccNodeCount(n); } else { return original.getSuccNodeCount(n) + 1; } } @Override public void addEdge(T src, T dst) { original.addEdge(src, dst); } @Override public void removeEdge(T src, T dst) throws UnsupportedOperationException { original.removeEdge(src, dst); } @Override public void removeAllIncidentEdges(T node) throws UnsupportedOperationException { original.removeAllIncidentEdges(node); } @Override public void removeIncomingEdges(T node) throws UnsupportedOperationException { original.removeIncomingEdges(node); } @Override public void removeOutgoingEdges(T node) throws UnsupportedOperationException { original.removeOutgoingEdges(node); } @NullUnmarked @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { if (src.equals(dst)) { return true; } else { return original.hasEdge(src, dst); } } }
2,956
22.101563
83
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/SelfLoopAddedGraph.java
package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.AbstractGraph; import com.ibm.wala.util.graph.EdgeManager; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NodeManager; public class SelfLoopAddedGraph<T> extends AbstractGraph<T> { private final NodeManager<T> nodes; @Override protected NodeManager<T> getNodeManager() { return nodes; } private final EdgeManager<T> edges; @Override protected EdgeManager<T> getEdgeManager() { return edges; } public SelfLoopAddedGraph(Graph<T> G) { nodes = G; edges = new SelfLoopAddedEdgeManager<>(G); } }
625
20.586207
61
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/SlowNumberedNodeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.MutableMapping; import java.io.Serializable; import java.util.Iterator; import java.util.stream.Stream; import org.jspecify.annotations.Nullable; /** An object which manages node numbers via a mapping. */ public class SlowNumberedNodeManager<T> implements NumberedNodeManager<T>, Serializable { private static final long serialVersionUID = 8956107128389624337L; /** A bijection between integer &lt;-&gt; node */ private final MutableMapping<T> map = MutableMapping.make(); @Override public int getNumber(@Nullable T obj) { return map.getMappedIndex(obj); } @Override public T getNode(int number) { if (number < 0) { throw new IllegalArgumentException("number must be >= 0"); } T result = map.getMappedObject(number); return result; } @Override public int getMaxNumber() { return map.getMaximumIndex(); } @Override public Iterator<T> iterator() { return map.iterator(); } @Override public Stream<T> stream() { return map.stream(); } @Override public int getNumberOfNodes() { return map.getSize(); } @Override public void addNode(T n) { if (n == null) { throw new IllegalArgumentException("n is null"); } map.add(n); } /** @see com.ibm.wala.util.graph.NodeManager#removeNode(Object) */ @Override public void removeNode(T n) { map.deleteMappedObject(n); } @Override public String toString() { StringBuilder result = new StringBuilder("Nodes:\n"); for (int i = 0; i <= getMaxNumber(); i++) { result.append(i).append(" "); result.append(map.getMappedObject(i)); result.append('\n'); } return result.toString(); } /** @see com.ibm.wala.util.graph.NodeManager#containsNode(Object) */ @Override public boolean containsNode(@Nullable T N) { return getNumber(N) != -1; } @Override public Iterator<T> iterateNodes(IntSet s) { return new NumberedNodeIterator<>(s, this); } }
2,497
24.489796
89
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/SlowSparseNumberedGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.graph.AbstractNumberedGraph; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.intset.BasicNaturalRelation; import java.io.Serializable; /** A graph of numbered nodes, expected to have a fairly sparse edge structure. */ public class SlowSparseNumberedGraph<T> extends AbstractNumberedGraph<T> implements Serializable { private static final long serialVersionUID = 7014361126159594838L; private final SlowNumberedNodeManager<T> nodeManager = new SlowNumberedNodeManager<>(); private final SparseNumberedEdgeManager<T> edgeManager; protected SlowSparseNumberedGraph() { this(0); } /** * If normalOutCount == n, this edge manager will eagerly allocated n words to hold out edges for * each node. (performance optimization for time) * * @param normalOutCount what is the "normal" number of out edges for a node? */ public SlowSparseNumberedGraph(int normalOutCount) { edgeManager = new SparseNumberedEdgeManager<>( nodeManager, normalOutCount, BasicNaturalRelation.TWO_LEVEL); } /** @see com.ibm.wala.util.graph.AbstractGraph#getNodeManager() */ @Override public NumberedNodeManager<T> getNodeManager() { return nodeManager; } /** @see com.ibm.wala.util.graph.AbstractGraph#getEdgeManager() */ @Override public NumberedEdgeManager<T> getEdgeManager() { return edgeManager; } /** @return a graph with the same nodes and edges as g */ public static <T> SlowSparseNumberedGraph<T> duplicate(Graph<T> g) { SlowSparseNumberedGraph<T> result = make(); copyInto(g, result); return result; } public static <T> void copyInto(Graph<T> g, Graph<T> into) { if (g == null) { throw new IllegalArgumentException("g is null"); } for (T name : g) { into.addNode(name); } for (T n : g) { for (T succ : Iterator2Iterable.make(g.getSuccNodes(n))) { into.addEdge(n, succ); } } } public static <T> SlowSparseNumberedGraph<T> make() { return new SlowSparseNumberedGraph<>(); } }
2,644
30.86747
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/SparseNumberedEdgeManager.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.intset.BasicNaturalRelation; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.EmptyIntSet; import com.ibm.wala.util.intset.IBinaryNaturalRelation; import com.ibm.wala.util.intset.IntSet; import java.io.Serializable; import java.util.Arrays; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** An object which tracks edges for nodes that have numbers. */ public final class SparseNumberedEdgeManager<T> implements NumberedEdgeManager<T>, Serializable { private static final long serialVersionUID = 6751048618312429623L; private final NumberedNodeManager<T> nodeManager; /** cache this state here for efficiency */ private final BitVector hasSuccessor = new BitVector(); /** @param nodeManager an object to track nodes */ public SparseNumberedEdgeManager(NumberedNodeManager<T> nodeManager) { this(nodeManager, 0, BasicNaturalRelation.TWO_LEVEL); } /** * If normalOutCount == n, this edge manager will eagerly allocated n words to hold out edges for * each node. (performance optimization for time) * * @param nodeManager an object to track nodes * @param normalCase what is the "normal" number of out edges for a node? * @throws IllegalArgumentException if normalCase &lt; 0 */ public SparseNumberedEdgeManager( NumberedNodeManager<T> nodeManager, int normalCase, byte delegateImpl) throws IllegalArgumentException { if (nodeManager == null) { throw new IllegalArgumentException("null nodeManager"); } if (normalCase < 0) { throw new IllegalArgumentException("normalCase < 0"); } this.nodeManager = nodeManager; if (normalCase == 0) { successors = new BasicNaturalRelation(defaultImpl, delegateImpl); predecessors = new BasicNaturalRelation(defaultImpl, delegateImpl); } else { byte[] impl = new byte[normalCase]; Arrays.fill(impl, BasicNaturalRelation.SIMPLE); successors = new BasicNaturalRelation(impl, delegateImpl); predecessors = new BasicNaturalRelation(impl, delegateImpl); } } /** * The default implementation policy conservatively uses 2-level vectors, in an attempt to * somewhat optimize for space. */ private static final byte[] defaultImpl = new byte[] {BasicNaturalRelation.TWO_LEVEL}; private final IBinaryNaturalRelation successors; private final IBinaryNaturalRelation predecessors; /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(java.lang.Object) */ @Override public Iterator<T> getPredNodes(@Nullable T N) throws IllegalArgumentException { int number = nodeManager.getNumber(N); if (number < 0) { throw new IllegalArgumentException(N + " is not in graph"); } IntSet s = predecessors.getRelated(number); Iterator<T> empty = EmptyIterator.instance(); return (s == null) ? empty : nodeManager.iterateNodes(s); } /** @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(java.lang.Object) */ @Override public int getPredNodeCount(T N) throws IllegalArgumentException { int number = nodeManager.getNumber(N); if (number < 0) { throw new IllegalArgumentException(N + " is not in graph"); } return predecessors.getRelatedCount(number); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(java.lang.Object) */ @Override public Iterator<T> getSuccNodes(@Nullable T N) throws IllegalArgumentException { int number = nodeManager.getNumber(N); if (number == -1) { throw new IllegalArgumentException(N + " is not in graph"); } IntSet s = successors.getRelated(number); Iterator<T> empty = EmptyIterator.instance(); return (s == null) ? empty : nodeManager.iterateNodes(s); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(java.lang.Object) */ public Iterator<T> getSuccNodes(int number) { IntSet s = successors.getRelated(number); Iterator<T> empty = EmptyIterator.instance(); return (s == null) ? empty : nodeManager.iterateNodes(s); } @Override public IntSet getSuccNodeNumbers(@Nullable T node) throws IllegalArgumentException { if (nodeManager.getNumber(node) < 0) { throw new IllegalArgumentException("Node not in graph " + node); } IntSet x = successors.getRelated(nodeManager.getNumber(node)); if (x == null) { return EmptyIntSet.instance; } else { return x; } } @Override public IntSet getPredNodeNumbers(@Nullable T node) throws IllegalArgumentException { if (nodeManager.getNumber(node) < 0) { throw new IllegalArgumentException("Node not in graph " + node); } return predecessors.getRelated(nodeManager.getNumber(node)); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(java.lang.Object) */ @Override public int getSuccNodeCount(T N) throws IllegalArgumentException { return getSuccNodeCount(nodeManager.getNumber(N)); } /** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(java.lang.Object) */ public int getSuccNodeCount(int number) { return successors.getRelatedCount(number); } /** @see com.ibm.wala.util.graph.EdgeManager#addEdge(java.lang.Object, java.lang.Object) */ @Override public void addEdge(T src, T dst) throws IllegalArgumentException { int x = nodeManager.getNumber(src); int y = nodeManager.getNumber(dst); if (x < 0) { throw new IllegalArgumentException("src " + src + " is not in graph"); } if (y < 0) { throw new IllegalArgumentException("dst " + dst + " is not in graph"); } predecessors.add(y, x); successors.add(x, y); hasSuccessor.set(x); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { int x = nodeManager.getNumber(src); int y = nodeManager.getNumber(dst); if (x < 0 || y < 0) { return false; } return successors.contains(x, y); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeAllIncidentEdges(T node) throws IllegalArgumentException { final int number = nodeManager.getNumber(node); if (number < 0) { throw new IllegalArgumentException("node not in graph: " + node); } IntSet succ = successors.getRelated(number); if (succ != null) { succ.foreach(x -> predecessors.remove(x, number)); } IntSet pred = predecessors.getRelated(number); if (pred != null) { pred.foreach( x -> { successors.remove(x, number); if (successors.getRelatedCount(x) == 0) { hasSuccessor.clear(x); } }); } successors.removeAll(number); hasSuccessor.clear(number); predecessors.removeAll(number); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeIncomingEdges(T node) throws IllegalArgumentException { final int number = nodeManager.getNumber(node); if (number < 0) { throw new IllegalArgumentException("node not in graph: " + node); } IntSet pred = predecessors.getRelated(number); if (pred != null) { pred.foreach( x -> { successors.remove(x, number); if (successors.getRelatedCount(x) == 0) { hasSuccessor.clear(x); } }); } predecessors.removeAll(number); } @Override public void removeEdge(T src, T dst) throws IllegalArgumentException { final int srcNumber = nodeManager.getNumber(src); final int dstNumber = nodeManager.getNumber(dst); if (srcNumber < 0) { throw new IllegalArgumentException("src not in graph: " + src); } if (dstNumber < 0) { throw new IllegalArgumentException("dst not in graph: " + dst); } successors.remove(srcNumber, dstNumber); if (successors.getRelatedCount(srcNumber) == 0) { hasSuccessor.clear(srcNumber); } predecessors.remove(dstNumber, srcNumber); } /** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */ @Override public void removeOutgoingEdges(T node) throws IllegalArgumentException { final int number = nodeManager.getNumber(node); if (number < 0) { throw new IllegalArgumentException("node not in graph: " + node); } IntSet succ = successors.getRelated(number); if (succ != null) { succ.foreach(x -> predecessors.remove(x, number)); } successors.removeAll(number); hasSuccessor.clear(number); } /** * This is implemented as a shortcut for efficiency * * @return true iff that node has any successors */ public boolean hasAnySuccessor(int node) { return hasSuccessor.get(node); } @Override public String toString() { return "Successors relation:\n" + successors; } }
9,387
33.642066
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/impl/SparseNumberedGraph.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.impl; import com.ibm.wala.util.graph.AbstractNumberedGraph; import com.ibm.wala.util.graph.INodeWithNumber; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.intset.BasicNaturalRelation; /** A graph of numbered nodes, expected to have a fairly sparse edge structure. */ public class SparseNumberedGraph<T extends INodeWithNumber> extends AbstractNumberedGraph<T> { private final DelegatingNumberedNodeManager<T> nodeManager; private final SparseNumberedEdgeManager<T> edgeManager; public SparseNumberedGraph() { nodeManager = new DelegatingNumberedNodeManager<>(); edgeManager = new SparseNumberedEdgeManager<>(nodeManager); } /** * If normalCase == n, the s edge manager will eagerly allocated n words to hold out edges for * each node. (performance optimization for time) * * @param normalCase what is the "normal" number of out edges for a node? */ public SparseNumberedGraph(int normalCase) { nodeManager = new DelegatingNumberedNodeManager<>(); edgeManager = new SparseNumberedEdgeManager<>(nodeManager, normalCase, BasicNaturalRelation.TWO_LEVEL); } public SparseNumberedGraph( DelegatingNumberedNodeManager<T> nodeManager, SparseNumberedEdgeManager<T> edgeManager) { this.nodeManager = nodeManager; this.edgeManager = edgeManager; } /** @see com.ibm.wala.util.graph.AbstractGraph#getNodeManager() */ @Override protected NumberedNodeManager<T> getNodeManager() { return nodeManager; } /** @see com.ibm.wala.util.graph.AbstractGraph#getEdgeManager() */ @Override protected NumberedEdgeManager<T> getEdgeManager() { return edgeManager; } }
2,134
34
97
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/labeled/AbstractLabeledGraph.java
/* * Copyright (c) 2007 Manu Sridharan and Juergen Graf * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Manu Sridharan * Juergen Graf */ /* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.util.graph.labeled; import com.ibm.wala.util.graph.AbstractGraph; import java.util.Iterator; import java.util.Set; public abstract class AbstractLabeledGraph<T, U> extends AbstractGraph<T> implements LabeledGraph<T, U> { /** @return the object which manages edges in the graph */ @Override protected abstract LabeledEdgeManager<T, U> getEdgeManager(); @Override public void addEdge(T src, T dst, U label) { getEdgeManager().addEdge(src, dst, label); } @Override public Iterator<? extends U> getPredLabels(T N) { return getEdgeManager().getPredLabels(N); } @Override public int getPredNodeCount(T N, U label) { return getEdgeManager().getPredNodeCount(N, label); } @Override public Iterator<T> getPredNodes(T N, U label) { return getEdgeManager().getPredNodes(N, label); } @Override public Iterator<? extends U> getSuccLabels(T N) { return getEdgeManager().getSuccLabels(N); } @Override public int getSuccNodeCount(T N, U label) { return getEdgeManager().getSuccNodeCount(N, label); } @Override public Iterator<? extends T> getSuccNodes(T N, U label) { return getEdgeManager().getSuccNodes(N, label); } @Override public boolean hasEdge(T src, T dst, U label) { return getEdgeManager().hasEdge(src, dst, label); } @Override public void removeEdge(T src, T dst, U label) { getEdgeManager().removeEdge(src, dst, label); } @Override public Set<? extends U> getEdgeLabels(T src, T dst) { return getEdgeManager().getEdgeLabels(src, dst); } }
3,866
33.526786
73
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/labeled/AbstractNumberedLabeledGraph.java
/* * Copyright (c) 2007 Juergen Graf * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Juergen Graf */ package com.ibm.wala.util.graph.labeled; import com.ibm.wala.util.graph.AbstractNumberedGraph; import com.ibm.wala.util.intset.IntSet; import java.util.Iterator; import java.util.Set; import org.jspecify.annotations.Nullable; public abstract class AbstractNumberedLabeledGraph<T, U> extends AbstractNumberedGraph<T> implements LabeledGraph<T, U>, NumberedLabeledGraph<T, U> { /** @return the object which manages edges in the graph */ @Override protected abstract NumberedLabeledEdgeManager<T, U> getEdgeManager(); @Override public void addEdge(T src, T dst, U label) { getEdgeManager().addEdge(src, dst, label); } @Override public Iterator<? extends U> getPredLabels(T N) { return getEdgeManager().getPredLabels(N); } @Override public int getPredNodeCount(T N, U label) { return getEdgeManager().getPredNodeCount(N, label); } @Override public Iterator<T> getPredNodes(T N, U label) { return getEdgeManager().getPredNodes(N, label); } @Override public Iterator<? extends U> getSuccLabels(T N) { return getEdgeManager().getSuccLabels(N); } @Override public int getSuccNodeCount(T N, U label) { return getEdgeManager().getSuccNodeCount(N, label); } @Override public Iterator<? extends T> getSuccNodes(T N, U label) { return getEdgeManager().getSuccNodes(N, label); } @Override public IntSet getPredNodeNumbers(T node, U label) throws IllegalArgumentException { return getEdgeManager().getPredNodeNumbers(node, label); } @Override public IntSet getSuccNodeNumbers(T node, U label) throws IllegalArgumentException { return getEdgeManager().getSuccNodeNumbers(node, label); } @Override public boolean hasEdge(T src, T dst, U label) { return getEdgeManager().hasEdge(src, dst, label); } @Override public void removeEdge(T src, T dst, U label) { getEdgeManager().removeEdge(src, dst, label); } @Override public Set<? extends U> getEdgeLabels(T src, T dst) { return getEdgeManager().getEdgeLabels(src, dst); } @Nullable @Override public U getDefaultLabel() { return getEdgeManager().getDefaultLabel(); } @Override protected String edgeString(T from, T to) { Set<? extends U> labels = getEdgeLabels(from, to); if (labels != null && !labels.isEmpty()) { return "-" + labels + "->"; } else { return super.edgeString(from, to); } } }
2,743
25.901961
89
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/labeled/LabeledEdgeManager.java
/* * Copyright (c) 2007 Manu Sridharan and Juergen Graf * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Manu Sridharan * Juergen Graf */ /* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.util.graph.labeled; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.graph.EdgeManager; import java.util.Iterator; import java.util.Set; import java.util.function.Predicate; import org.jspecify.annotations.Nullable; /** * An object which tracks labeled edges in a graph. * * @param <T> type of nodes in this graph * @param <U> types of edge labels. */ public interface LabeledEdgeManager<T, U> extends EdgeManager<T> { /** * Sets the default object used as label for operations where no specific edge label is provided. * This is due to compatibility with the EdgeManager interface */ @Nullable U getDefaultLabel(); /** * Return an Iterator over the immediate predecessor nodes of this Node in the Graph on edges with * some label. * * <p>This method never returns {@code null}. * * @return an Iterator over the immediate predecessor nodes of this Node. */ Iterator<T> getPredNodes(T N, U label); default Iterator<T> getPredNodes(T N, Predicate<U> pred) { return new FilterIterator<>( getPredNodes(N), (p) -> getEdgeLabels(p, N).stream().anyMatch(pred)); } /** @return the labels on edges whose destination is N */ Iterator<? extends U> getPredLabels(T N); /** * Return the number of {@link #getPredNodes immediate predecessor} nodes of this Node in the * Graph on edges with some label. * * @return the number of immediate predecessor Nodes of this Node in the Graph. */ int getPredNodeCount(T N, U label); /** * Return an Iterator over the immediate successor nodes of this Node in the Graph on edges with * some label. * * <p>This method never returns {@code null}. * * @return an Iterator over the immediate successor Nodes of this Node. */ Iterator<? extends T> getSuccNodes(T N, U label); /** @return the labels on edges whose source is N */ Iterator<? extends U> getSuccLabels(T N); /** * Return the number of {@link #getSuccNodes immediate successor} nodes of this Node in the Graph * * @return the number of immediate successor Nodes of this Node in the Graph. */ int getSuccNodeCount(T N, U label); /** adds an edge with some label */ void addEdge(T src, T dst, U label); void removeEdge(T src, T dst, U label) throws UnsupportedOperationException; boolean hasEdge(T src, T dst, U label); /** * Returns a set of all labeled edges between node src and node dst * * @param src source node of the edge * @param dst target node of the edge * @return Set of edge labels */ Set<? extends U> getEdgeLabels(T src, T dst); }
4,936
35.57037
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/labeled/LabeledGraph.java
/* * Copyright (c) 2007 Manu Sridharan and Juergen Graf * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Manu Sridharan * Juergen Graf */ /* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.util.graph.labeled; import com.ibm.wala.util.graph.Graph; /** A graph with labeled edges. */ public interface LabeledGraph<T, U> extends Graph<T>, LabeledEdgeManager<T, U> {}
2,485
44.2
81
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/labeled/NumberedLabeledEdgeManager.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.labeled; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.intset.IntSet; public interface NumberedLabeledEdgeManager<T, U> extends LabeledEdgeManager<T, U>, NumberedEdgeManager<T> { IntSet getPredNodeNumbers(T node, U label) throws IllegalArgumentException; IntSet getSuccNodeNumbers(T node, U label) throws IllegalArgumentException; }
776
32.782609
77
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/labeled/NumberedLabeledGraph.java
package com.ibm.wala.util.graph.labeled; import com.ibm.wala.util.graph.NumberedGraph; public interface NumberedLabeledGraph<T, I> extends NumberedGraph<T>, NumberedLabeledEdgeManager<T, I> {}
199
27.571429
65
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/labeled/SlowSparseNumberedLabeledGraph.java
/* * Copyright (c) 2007 Manu Sridharan and Juergen Graf * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Manu Sridharan * Juergen Graf */ /* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.util.graph.labeled; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.graph.impl.SlowNumberedNodeManager; import java.io.Serializable; import org.jspecify.annotations.Nullable; /** A labeled graph implementation suitable for sparse graphs. */ public class SlowSparseNumberedLabeledGraph<T, U> extends AbstractNumberedLabeledGraph<T, U> implements Serializable { /** */ private static final long serialVersionUID = -6929183520814732209L; /** @return a graph with the same nodes and edges as g */ public static <T, U> SlowSparseNumberedLabeledGraph<T, U> duplicate(LabeledGraph<T, U> g) { SlowSparseNumberedLabeledGraph<T, U> result = new SlowSparseNumberedLabeledGraph<>(g.getDefaultLabel()); copyInto(g, result); return result; } public static <T, U> void copyInto(LabeledGraph<T, U> g, LabeledGraph<T, U> into) { if (g == null) { throw new IllegalArgumentException("g is null"); } for (T name : g) { into.addNode(name); } for (T n : g) { for (T s : Iterator2Iterable.make(g.getSuccNodes(n))) { for (U l : g.getEdgeLabels(n, s)) { into.addEdge(n, s, l); } } } } private final SlowNumberedNodeManager<T> nodeManager; private final SparseNumberedLabeledEdgeManager<T, U> edgeManager; public SlowSparseNumberedLabeledGraph() { nodeManager = new SlowNumberedNodeManager<>(); edgeManager = new SparseNumberedLabeledEdgeManager<>(nodeManager); } public SlowSparseNumberedLabeledGraph(@Nullable U defaultLabel) { if (defaultLabel == null) { throw new IllegalArgumentException("null default label"); } nodeManager = new SlowNumberedNodeManager<>(); edgeManager = new SparseNumberedLabeledEdgeManager<>(nodeManager, defaultLabel); } @Override protected NumberedLabeledEdgeManager<T, U> getEdgeManager() { return edgeManager; } @Override protected NumberedNodeManager<T> getNodeManager() { return nodeManager; } }
4,380
37.095652
93
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/labeled/SparseNumberedLabeledEdgeManager.java
/* * Copyright (c) 2007 Manu Sridharan and Juergen Graf * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Manu Sridharan * Juergen Graf */ /* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.util.graph.labeled; import com.ibm.wala.util.collections.ArraySetMultiMap; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.graph.impl.SparseNumberedEdgeManager; import com.ibm.wala.util.intset.BitVectorIntSet; import com.ibm.wala.util.intset.IntSet; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.jspecify.annotations.Nullable; /** */ public class SparseNumberedLabeledEdgeManager<T, U> implements Serializable, NumberedLabeledEdgeManager<T, U> { /** */ private static final long serialVersionUID = 5298089288917726790L; /** the label to be attached to an edge when no label is specified */ @Nullable private final U defaultLabel; private final NumberedNodeManager<T> nodeManager; /** maps each edge label to its own {@link SparseNumberedEdgeManager} */ private final Map<U, SparseNumberedEdgeManager<T>> edgeLabelToManager = HashMapFactory.make(); private final ArraySetMultiMap<T, U> nodeToPredLabels = new ArraySetMultiMap<>(); private final ArraySetMultiMap<T, U> nodeToSuccLabels = new ArraySetMultiMap<>(); private SparseNumberedEdgeManager<T> getManagerForLabel(@Nullable U label) { SparseNumberedEdgeManager<T> ret = edgeLabelToManager.get(label); if (ret == null) { ret = new SparseNumberedEdgeManager<>(nodeManager); edgeLabelToManager.put(label, ret); } return ret; } /** @see LabeledEdgeManager#addEdge(java.lang.Object, java.lang.Object, java.lang.Object) */ @Override public void addEdge(T src, T dst, @Nullable U label) { nodeToSuccLabels.put(src, label); nodeToPredLabels.put(dst, label); getManagerForLabel(label).addEdge(src, dst); } /** @see LabeledEdgeManager#getPredNodeCount(java.lang.Object, java.lang.Object) */ @Override public int getPredNodeCount(T N, U label) { return getManagerForLabel(label).getPredNodeCount(N); } /** @see LabeledEdgeManager#getPredNodes(java.lang.Object, java.lang.Object) */ @Override public Iterator<T> getPredNodes(@Nullable T N, U label) { return getManagerForLabel(label).getPredNodes(N); } /** @see LabeledEdgeManager#getSuccNodeCount(java.lang.Object, java.lang.Object) */ @Override public int getSuccNodeCount(T N, U label) { return getManagerForLabel(label).getSuccNodeCount(N); } /** @see LabeledEdgeManager#getSuccNodes(java.lang.Object, java.lang.Object) */ @Override public Iterator<? extends T> getSuccNodes(@Nullable T N, U label) { return getManagerForLabel(label).getSuccNodes(N); } /** @see LabeledEdgeManager#hasEdge(java.lang.Object, java.lang.Object, java.lang.Object) */ @Override public boolean hasEdge(@Nullable T src, @Nullable T dst, U label) { return getManagerForLabel(label).hasEdge(src, dst); } /* * (non-Javadoc) * * @see LabeledEdgeManager#removeAllIncidentEdges(java.lang.Object) */ @Override public void removeAllIncidentEdges(T node) { removeIncomingEdges(node); removeOutgoingEdges(node); } /** @see LabeledEdgeManager#removeEdge(java.lang.Object, java.lang.Object, java.lang.Object) */ @Override public void removeEdge(T src, T dst, U label) throws IllegalArgumentException { getManagerForLabel(label).removeEdge(src, dst); } /** @see LabeledEdgeManager#removeIncomingEdges(java.lang.Object) */ @Override public void removeIncomingEdges(T node) throws IllegalArgumentException { for (U label : nodeToPredLabels.get(node)) { getManagerForLabel(label).removeIncomingEdges(node); } } /** @see LabeledEdgeManager#removeOutgoingEdges(java.lang.Object) */ @Override public void removeOutgoingEdges(T node) throws IllegalArgumentException { for (U label : nodeToSuccLabels.get(node)) { getManagerForLabel(label).removeOutgoingEdges(node); } } public SparseNumberedLabeledEdgeManager( final NumberedNodeManager<T> nodeManager, U defaultLabel) { super(); this.defaultLabel = defaultLabel; this.nodeManager = nodeManager; if (nodeManager == null) { throw new IllegalArgumentException("null nodeManager"); } } public SparseNumberedLabeledEdgeManager(final NumberedNodeManager<T> nodeManager) { super(); this.defaultLabel = null; this.nodeManager = nodeManager; if (nodeManager == null) { throw new IllegalArgumentException("null nodeManager"); } } @Override public Iterator<? extends U> getPredLabels(T N) { return nodeToPredLabels.get(N).iterator(); } @Override public Iterator<? extends U> getSuccLabels(T N) { return nodeToSuccLabels.get(N).iterator(); } @Override public Set<? extends U> getEdgeLabels(T src, T dst) { Set<U> labels = HashSetFactory.make(); for (Map.Entry<U, SparseNumberedEdgeManager<T>> entry : edgeLabelToManager.entrySet()) { if (entry.getValue().hasEdge(src, dst)) { labels.add(entry.getKey()); } } return labels; } @Override public void addEdge(T src, T dst) { assert defaultLabel != null; addEdge(src, dst, defaultLabel); } @Override public int getPredNodeCount(T N) { int count = 0; for (U label : nodeToPredLabels.get(N)) { count += getPredNodeCount(N, label); } return count; } @Override public Iterator<T> getPredNodes(@Nullable T N) { Collection<T> preds = HashSetFactory.make(); for (U label : nodeToPredLabels.get(N)) { preds.addAll(Iterator2Collection.toSet(getPredNodes(N, label))); } return preds.iterator(); } @Override public int getSuccNodeCount(T N) { int count = 0; for (U label : nodeToSuccLabels.get(N)) { count += getSuccNodeCount(N, label); } return count; } @Override public Iterator<T> getSuccNodes(@Nullable T N) { Collection<T> succs = HashSetFactory.make(); for (U label : nodeToSuccLabels.get(N)) { succs.addAll(Iterator2Collection.toSet(getSuccNodes(N, label))); } return succs.iterator(); } @Override public boolean hasEdge(@Nullable T src, @Nullable T dst) { for (U label : nodeToSuccLabels.get(src)) { if (hasEdge(src, dst, label)) { return true; } } return false; } @Override public void removeEdge(T src, T dst) throws UnsupportedOperationException { for (U label : nodeToSuccLabels.get(src)) { if (hasEdge(src, dst, label)) { removeEdge(src, dst, label); } } } @Nullable @Override public U getDefaultLabel() { return defaultLabel; } @Override public IntSet getPredNodeNumbers(@Nullable T node, U label) throws IllegalArgumentException { return getManagerForLabel(label).getPredNodeNumbers(node); } @Override public IntSet getSuccNodeNumbers(@Nullable T node, U label) throws IllegalArgumentException { return getManagerForLabel(label).getSuccNodeNumbers(node); } @Override public IntSet getPredNodeNumbers(@Nullable T node) { BitVectorIntSet preds = new BitVectorIntSet(); for (U label : nodeToPredLabels.get(node)) { preds.addAll(getPredNodeNumbers(node, label)); } return preds; } @Override public IntSet getSuccNodeNumbers(@Nullable T node) { BitVectorIntSet succs = new BitVectorIntSet(); for (U label : nodeToSuccLabels.get(node)) { succs.addAll(getSuccNodeNumbers(node, label)); } return succs; } }
9,908
31.382353
97
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/BFSIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.Graph; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import org.jspecify.annotations.Nullable; /** * This class implements breadth-first search over a Graph, returning an Iterator of the nodes of * the graph in order of discovery. This class follows the outNodes of the graph nodes to define the * graph, but this behavior can be changed by overriding the getConnected method. */ public class BFSIterator<T> implements Iterator<T> { /** List of nodes as discovered */ final ArrayList<T> Q = new ArrayList<>(); /** Set of nodes that have been visited */ final HashSet<T> visited = HashSetFactory.make(); /** index of the node currently being searched */ private int index = 0; /** Governing Graph */ protected Graph<T> G; /** * Construct a breadth-first iterator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate * @throws IllegalArgumentException if G is null */ public BFSIterator(Graph<T> G, T N) { if (G == null) { throw new IllegalArgumentException("G is null"); } init(G, new NonNullSingletonIterator<>(N)); } /** * Construct a breadth-first enumerator across the (possibly improper) subset of nodes reachable * from the nodes in the given enumeration. * * @param nodes the set of nodes from which to start searching * @throws IllegalArgumentException if G is null */ public BFSIterator(Graph<T> G, @Nullable Iterator<? extends T> nodes) { if (G == null) { throw new IllegalArgumentException("G is null"); } if (nodes == null) { throw new IllegalArgumentException("nodes is null"); } init(G, nodes); } /** * Constructor DFSFinishTimeIterator. * * @throws NullPointerException if G is null */ public BFSIterator(Graph<T> G) throws NullPointerException { this(G, G == null ? null : G.iterator()); } private void init(Graph<T> G, Iterator<? extends T> nodes) { this.G = G; while (nodes.hasNext()) { T o = nodes.next(); if (visited.add(o)) { Q.add(o); } } index = 0; if (Q.size() > 0) { T current = Q.get(0); visitChildren(current); } } private void visitChildren(T N) { for (T child : Iterator2Iterable.make(getConnected(N))) { if (visited.add(child)) { Q.add(child); } } } /** * Return whether there are any more nodes left to enumerate. * * @return true if there nodes left to enumerate. */ @Override public boolean hasNext() { return (Q.size() > index); } /** * Find the next graph node in discover time order. * * @return the next graph node in discover time order. */ @Override public T next() throws NoSuchElementException { if (index >= Q.size()) { throw new NoSuchElementException(); } T result = Q.get(index); index++; if (hasNext()) { T N = Q.get(index); visitChildren(N); } return result; } /** * get the out edges of a given node * * @param n the node of which to get the out edges * @return the out edges */ protected Iterator<? extends T> getConnected(T n) { return G.getSuccNodes(n); } @Override public void remove() throws UnimplementedError { throw new UnimplementedError(); } }
4,072
26.153333
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/BFSPathFinder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.graph.Graph; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** * This class searches breadth-first for node that matches some criteria. If found, it reports a * path to the first node found. * * <p>This class follows the outNodes of the graph nodes to define the graph, but this behavior can * be changed by overriding the getConnected method. * * <p>TODO: if finding many paths, use a dynamic programming algorithm instead of calling this * repeatedly. */ public class BFSPathFinder<T> { private final boolean DEBUG = false; /** The graph to search */ private final Graph<T> G; /** The Filter which defines the target set of nodes to find */ private final Predicate<T> filter; /** an enumeration of all nodes to search from */ private final Iterator<T> roots; /** * Construct a breadth-first enumerator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate */ public BFSPathFinder(Graph<T> G, T N, Predicate<T> f) { if (G == null) { throw new IllegalArgumentException("G is null"); } if (f == null) { throw new IllegalArgumentException("null f"); } this.G = G; this.roots = new NonNullSingletonIterator<>(N); this.filter = f; } /** * Construct a breadth-first enumerator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate * @throws IllegalArgumentException if G is null */ public BFSPathFinder(Graph<T> G, T src, final T target) throws IllegalArgumentException { if (G == null) { throw new IllegalArgumentException("G is null"); } this.G = G; this.roots = new NonNullSingletonIterator<>(src); if (!G.containsNode(src)) { throw new IllegalArgumentException("src is not in graph " + src); } this.filter = target::equals; } /** * Construct a breadth-first enumerator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate */ public BFSPathFinder(Graph<T> G, T src, Iterator<T> targets) { if (targets == null) { throw new IllegalArgumentException("targets is null"); } final Set<T> ts = HashSetFactory.make(); while (targets.hasNext()) { ts.add(targets.next()); } this.G = G; this.roots = new NonNullSingletonIterator<>(src); this.filter = ts::contains; } /** * Construct a breadth-first enumerator starting with any of a set of nodes in a directed graph. * * @param G the graph whose nodes to enumerate */ public BFSPathFinder(Graph<T> G, Iterator<T> sources, final T target) { if (G == null) { throw new IllegalArgumentException("G is null"); } if (sources == null) { throw new IllegalArgumentException("sources is null"); } this.G = G; this.roots = sources; this.filter = target::equals; } /** * Construct a breadth-first enumerator across the (possibly improper) subset of nodes reachable * from the nodes in the given enumeration. * * @param nodes the set of nodes from which to start searching */ public BFSPathFinder(Graph<T> G, Iterator<T> nodes, Predicate<T> f) { this.G = G; this.roots = nodes; this.filter = f; if (G == null) { throw new IllegalArgumentException("G is null"); } if (roots == null) { throw new IllegalArgumentException("roots is null"); } } @Nullable private ArrayDeque<T> Q = null; @Nullable private HashMap<Object, T> history = null; /** * @return a List of nodes that specifies the first path found from a root to a node accepted by * the filter. Returns null if no path found. */ @NullUnmarked @Nullable public List<T> find() { if (Q == null) { Q = new ArrayDeque<>(); history = HashMapFactory.make(); while (roots.hasNext()) { T next = roots.next(); Q.addLast(next); history.put(next, null); } } while (!Q.isEmpty()) { T N = Q.removeFirst(); if (DEBUG) { System.err.println(("visit " + N)); } if (filter.test(N)) { return makePath(N, history); } Iterator<? extends T> children = getConnected(N); while (children.hasNext()) { T c = children.next(); if (!history.containsKey(c)) { Q.addLast(c); history.put(c, N); } } } return null; } /** * @return a List which represents a path in the breadth-first search to Q[i]. Q holds the nodes * visited during the BFS, in order. */ @NullUnmarked private List<T> makePath(T node, @Nullable Map<Object, T> history) { ArrayList<T> result = new ArrayList<>(); T n = node; result.add(n); while (true) { T parent = history.get(n); if (parent == null) return result; else { result.add(parent); n = parent; } } } /** * get the out edges of a given node * * @param n the node of which to get the out edges * @return the out edges */ protected Iterator<? extends T> getConnected(T n) { return G.getSuccNodes(n); } }
6,035
27.742857
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/BoundedBFSIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.graph.Graph; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; /** * This class implements breadth-first search over a Graph, returning an Iterator of the nodes of * the graph in order of discovery. This class follows the outNodes of the graph nodes to define the * graph, but this behavior can be changed by overriding the getConnected method. * * <p>This traversal only visits nodes within k hops of a root. */ public class BoundedBFSIterator<T> implements Iterator<T> { /** List of nodes as discovered */ final ArrayList<T> Q = new ArrayList<>(); /** Set of nodes that have been visited */ final HashSet<T> visited = HashSetFactory.make(); /** index of the node currently being searched */ private int index = 0; /** Governing Graph */ protected Graph<T> G; /** limit on number of hops */ private final int k; /** boundary[i] is the first index which represents a child that is &gt; i hops away. */ private final int[] boundary; /** how many hops away is the next element. */ private int currentHops = 0; /** * Construct a breadth-first iterator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate * @throws IllegalArgumentException if G is null */ public BoundedBFSIterator(Graph<T> G, T N, int k) { if (G == null) { throw new IllegalArgumentException("G is null"); } if (k < 0) { throw new IllegalArgumentException("invalid k : " + k); } this.k = k; boundary = new int[k]; init(G, new NonNullSingletonIterator<>(N)); } /** * Construct a breadth-first enumerator across the (possibly improper) subset of nodes reachable * from the nodes in the given enumeration. * * @param G the graph whose nodes to enumerate * @param nodes the set of nodes from which to start searching * @throws IllegalArgumentException if G is null */ public BoundedBFSIterator(Graph<T> G, Iterator<? extends T> nodes, int k) { if (G == null) { throw new IllegalArgumentException("G is null"); } if (k < 0) { throw new IllegalArgumentException("invalid k: " + k); } this.k = k; boundary = new int[k]; init(G, nodes); } private void init(Graph<T> G, Iterator<? extends T> nodes) { this.G = G; if (G.getNumberOfNodes() == 0) { return; } while (nodes.hasNext()) { T o = nodes.next(); if (visited.add(o)) { Q.add(o); } } index = 0; if (Q.size() > 0) { T current = Q.get(0); visitChildren(current); } } private void visitChildren(T N) { if (currentHops == k) { return; } if (boundary[currentHops] == 0) { boundary[currentHops] = Q.size(); } for (T child : Iterator2Iterable.make(getConnected(N))) { if (visited.add(child)) { Q.add(child); } } } /** * Return whether there are any more nodes left to enumerate. * * @return true if there nodes left to enumerate. */ @Override public boolean hasNext() { return (Q.size() > index); } /** * Find the next graph node in discover time order. * * @return the next graph node in discover time order. */ @Override public T next() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException(); } T result = Q.get(index); index++; if (currentHops < k && index == boundary[currentHops]) { currentHops++; } if (hasNext()) { T N = Q.get(index); visitChildren(N); } return result; } /** * get the out edges of a given node * * @param n the node of which to get the out edges * @return the out edges */ protected Iterator<? extends T> getConnected(T n) { return G.getSuccNodes(n); } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** @return the currentHops */ public int getCurrentHops() { return currentHops; } }
4,714
26.097701
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/DFS.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.NumberedGraph; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.function.Predicate; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** utilities related to depth-first search. */ public class DFS { /** * Perform a DFS starting with a particular node and return the set of all nodes visited. * * @param C collection of nodes to start from * @param filter only traverse nodes that need this filter * @throws IllegalArgumentException if C is null */ @SuppressWarnings("serial") public static <T> Collection<T> getReachableNodes( final Graph<T> G, Collection<? extends T> C, final Predicate<? super T> filter) { if (C == null) { throw new IllegalArgumentException("C is null"); } Iterator<T> dfs = new SlowDFSFinishTimeIterator<>(G, C.iterator()) { @Override protected Iterator<T> getConnected(@Nullable T n) { return new FilterIterator<>(G.getSuccNodes(n), filter); } }; return Iterator2Collection.toSet(dfs); } /** * Perform a DFS starting with a particular node set and return the set of all nodes visited. * * @param G the graph containing n * @return Set * @throws IllegalArgumentException if C is null */ public static <T> Set<T> getReachableNodes(Graph<T> G, Collection<? extends T> C) { if (C == null) { throw new IllegalArgumentException("C is null"); } HashSet<T> result = HashSetFactory.make(); Iterator<T> dfs = iterateFinishTime(G, C.iterator()); while (dfs.hasNext()) { result.add(dfs.next()); } return result; } /** * Perform a DFS and return the set of all nodes visited. * * @param G the graph containing n * @return Set * @throws IllegalArgumentException if G == null */ public static <T> Set<T> getReachableNodes(Graph<T> G) throws IllegalArgumentException { if (G == null) { throw new IllegalArgumentException("G == null"); } HashSet<T> result = HashSetFactory.make(); Iterator<T> dfs = iterateFinishTime(G); while (dfs.hasNext()) { result.add(dfs.next()); } return result; } /** * Perform a DFS of a graph starting with a specified node and return a sorted list of nodes. The * nodes are sorted by depth first order. * * @param G a graph * @param n the initial node * @return a sorted set of nodes in the graph in depth first order */ public static <T> SortedSet<T> sortByDepthFirstOrder(Graph<T> G, T n) { Map<T, Integer> order = HashMapFactory.make(); TreeSet<T> result = new TreeSet<>(new DFSComparator<>(order)); Iterator<T> dfs = iterateFinishTime(G, new NonNullSingletonIterator<>(n)); int i = 0; while (dfs.hasNext()) { T nxt = dfs.next(); order.put(nxt, i++); result.add(nxt); } return result; } /** Comparator class to order the nodes in the DFS according to the depth first order */ static class DFSComparator<T> implements Comparator<T> { private final Map<T, Integer> order; DFSComparator(Map<T, Integer> order) { this.order = order; } @NullUnmarked @Override public int compare(T o1, T o2) { // throws an exception if either argument is not a Node object if (o1 == o2) { return 0; } Integer t1 = order.get(o1); Integer t2 = order.get(o2); // throws an exception if either node has not been ordered return (t1 - t2); } } /** @return iterator of nodes of G in order of DFS discover time */ public static <T> DFSDiscoverTimeIterator<T> iterateDiscoverTime(Graph<T> G) { if (G instanceof NumberedGraph) { return new NumberedDFSDiscoverTimeIterator<>((NumberedGraph<T>) G); } else { return new SlowDFSDiscoverTimeIterator<>(G); } } /** * @param roots roots of traversal, in order to visit in outermost loop of DFS * @return iterator of nodes of G in order of DFS discover time * @throws IllegalArgumentException if roots == null */ public static <T> Iterator<T> iterateDiscoverTime(Graph<T> G, Iterator<T> roots) throws IllegalArgumentException { if (roots == null) { throw new IllegalArgumentException("roots == null"); } if (G instanceof NumberedGraph) { return new NumberedDFSDiscoverTimeIterator<>((NumberedGraph<T>) G, roots); } else { return new SlowDFSDiscoverTimeIterator<>(G, roots); } } /** * @param N root of traversal * @return iterator of nodes of G in order of DFS discover time */ public static <T> DFSDiscoverTimeIterator<T> iterateDiscoverTime(Graph<T> G, T N) { if (G == null) { throw new IllegalArgumentException("G == null"); } if (G instanceof NumberedGraph) { return new NumberedDFSDiscoverTimeIterator<>((NumberedGraph<T>) G, N); } else { return new SlowDFSDiscoverTimeIterator<>(G, N); } } /** * @param G a graph * @return iterator of nodes of G in order of DFS finish time * @throws IllegalArgumentException if G == null */ public static <T> DFSFinishTimeIterator<T> iterateFinishTime(Graph<T> G) throws IllegalArgumentException { if (G == null) { throw new IllegalArgumentException("G == null"); } if (G instanceof NumberedGraph) { return new NumberedDFSFinishTimeIterator<>((NumberedGraph<T>) G); } else { return new SlowDFSFinishTimeIterator<>(G); } } /** * @param G a graph * @param ie roots of traversal, in order to visit in outermost loop of DFS * @return iterator of nodes of G in order of DFS finish time */ public static <T> DFSFinishTimeIterator<T> iterateFinishTime( Graph<T> G, @Nullable Iterator<? extends T> ie) { if (ie == null) { throw new IllegalArgumentException("null ie"); } if (G instanceof NumberedGraph) { return new NumberedDFSFinishTimeIterator<>((NumberedGraph<T>) G, ie); } else { return new SlowDFSFinishTimeIterator<>(G, ie); } } }
6,984
31.337963
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/DFSAllPathsFinder.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.graph.Graph; import java.util.Iterator; import java.util.List; import java.util.function.Predicate; import org.jspecify.annotations.Nullable; /** * Extends {@link DFSPathFinder} to discover all paths from a set of root nodes to nodes passing * some {@link Predicate}. * * <p>Note that this code performs work that is potentially exponential in the size of the * underlying graph, using exponential space. It most likely won't work even for graphs of moderate * size. */ public class DFSAllPathsFinder<T> extends DFSPathFinder<T> { private static final long serialVersionUID = 5413569289853649240L; public DFSAllPathsFinder(Graph<T> G, Iterator<T> nodes, Predicate<T> f) { super(G, nodes, f); } public DFSAllPathsFinder(Graph<T> G, T N, Predicate<T> f) throws IllegalArgumentException { super(G, N, f); } @Override protected Iterator<? extends T> getConnected(T n) { final List<T> cp = currentPath(); return new FilterIterator<>(G.getSuccNodes(n), o -> !cp.contains(o)); } @Nullable @Override protected Iterator<? extends T> getPendingChildren(T n) { Pair<List<T>, T> key = Pair.make(currentPath(), n); return pendingChildren.get(key); } @Override protected void setPendingChildren(T v, Iterator<? extends T> iterator) { Pair<List<T>, T> key = Pair.make(currentPath(), v); pendingChildren.put(key, iterator); } }
1,920
31.016667
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/DFSDiscoverTimeIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.NumberedGraph; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** * This class implements depth-first search over a {@link NumberedGraph}, return an enumeration of * the nodes of the graph in order of increasing discover time. This class follows the outNodes of * the graph nodes to define the graph, but this behavior can be changed by overriding the * getConnected method. */ public abstract class DFSDiscoverTimeIterator<T> extends ArrayList<T> implements Iterator<T> { private static final long serialVersionUID = 4238700455408861924L; /** an enumeration of all nodes to search from */ @Nullable private Iterator<? extends T> roots; /** subclass constructors must call this! */ protected void init(Iterator<? extends T> nodes) { roots = nodes; assert nodes != null; if (roots.hasNext()) { T n = roots.next(); push(n); setPendingChildren(n, getConnected(n)); } } /** subclass constructors must call this! */ protected void init(T N) { init(new NonNullSingletonIterator<>(N)); } /** * Return whether there are any more nodes left to enumerate. * * @return true if there nodes left to enumerate. */ @Override public boolean hasNext() { return !empty(); } @Nullable protected abstract Iterator<? extends T> getPendingChildren(T n); protected abstract void setPendingChildren(T v, Iterator<? extends T> iterator); /** * Find the next graph node in discover time order. * * @return the next graph node in discover time order. */ @NullUnmarked @Override public T next() throws NoSuchElementException { if (empty()) { throw new NoSuchElementException(); } // we always return the top node on the stack. T toReturn = peek(); // compute the next node to return. assert getPendingChildren(toReturn) != null; do { T stackTop = peek(); for (T child : Iterator2Iterable.make(getPendingChildren(stackTop))) { if (getPendingChildren(child) == null) { // found a new child. visitEdge(stackTop, child); setPendingChildren(child, getConnected(child)); push(child); return toReturn; } } // the following saves space by allowing the original iterator to be GCed Iterator<T> empty = EmptyIterator.instance(); setPendingChildren(stackTop, empty); // didn't find any new children. pop the stack and try again. pop(); } while (!empty()); // search for the next unvisited root. while (roots.hasNext()) { T nextRoot = roots.next(); if (getPendingChildren(nextRoot) == null) { push(nextRoot); setPendingChildren(nextRoot, getConnected(nextRoot)); return toReturn; } } return toReturn; } /** * get the out edges of a given node * * @param n the node of which to get the out edges * @return the out edges */ protected abstract Iterator<? extends T> getConnected(T n); @Override public void remove() throws UnimplementedError { throw new UnimplementedError(); } /** * @param from source of the edge to visit * @param to target of the edge to visit */ protected void visitEdge(T from, T to) { // do nothing. subclasses will override. } private boolean empty() { return size() == 0; } private void push(T elt) { add(elt); } private T peek() { return get(size() - 1); } private T pop() { T e = get(size() - 1); remove(size() - 1); return e; } }
4,355
26.923077
98
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/DFSFinishTimeIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.qual.Initializer; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.Graph; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import org.jspecify.annotations.Nullable; /** * This class implements depth-first search over a {@link Graph}, return an enumeration of the nodes * of the graph in order of increasing finishing time. This class follows the outNodes of the graph * nodes to define the graph, but this behavior can be changed by overriding the getConnected * method. */ public abstract class DFSFinishTimeIterator<T> extends ArrayList<T> implements Iterator<T> { private static final long serialVersionUID = 8440061593631309429L; /** the current next element in finishing time order */ @Nullable private T theNextElement; /** an enumeration of all nodes to search from */ private Iterator<? extends T> roots; /** The governing graph. */ private Graph<T> G; /** Subclasses must call this in the constructor! */ @Initializer protected void init(Graph<T> G, Iterator<? extends T> nodes) { this.G = G; roots = nodes; if (roots.hasNext()) theNextElement = roots.next(); } private boolean empty() { return size() == 0; } /** * Return whether there are any more nodes left to enumerate. * * @return true if there nodes left to enumerate. */ @Override public boolean hasNext() { return (!empty() || (theNextElement != null && getPendingChildren(theNextElement) == null)); } @Nullable abstract Iterator<T> getPendingChildren(@Nullable T n); abstract void setPendingChildren(@Nullable T v, Iterator<T> iterator); private void push(@Nullable T elt) { add(elt); } private T peek() { return get(size() - 1); } private T pop() { T e = get(size() - 1); remove(size() - 1); return e; } /** * Find the next graph node in finishing time order. * * @return the next graph node in finishing time order. */ @Nullable @Override @SuppressWarnings("unchecked") public T next() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException(); } if (empty()) { T v = theNextElement; setPendingChildren(v, getConnected(v)); push(v); } recurse: while (!empty()) { T v = peek(); Iterator<? extends T> pc = getPendingChildren(v); for (T n : Iterator2Iterable.make(pc)) { assert n != null : "null node in pc"; Iterator<T> nChildren = getPendingChildren(n); if (nChildren == null) { // found a new child: recurse to it. setPendingChildren(n, getConnected(n)); push(n); continue recurse; } } // the following saves space by allowing the original iterator to be GCed setPendingChildren(v, (Iterator<T>) EmptyIterator.instance()); // no more children to visit: finished this vertex while (getPendingChildren(theNextElement) != null && roots.hasNext()) { theNextElement = roots.next(); } return pop(); } return null; } /** * get the out edges of a given node * * @param n the node of which to get the out edges * @return the out edges */ protected Iterator<T> getConnected(@Nullable T n) { return G.getSuccNodes(n); } @Override public void remove() throws UnimplementedError { throw new UnimplementedError(); } }
4,010
27.246479
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/DFSPathFinder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.graph.Graph; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.function.Predicate; import org.jspecify.annotations.Nullable; /** * This class searches depth-first search for node that matches some criteria. If found, it reports * a path to the first node found. * * <p>This class follows the outNodes of the graph nodes to define the graph, but this behavior can * be changed by overriding the getConnected method. */ public class DFSPathFinder<T> extends ArrayList<T> { public static final long serialVersionUID = 9939900773328288L; /** The graph to search */ protected final Graph<T> G; /** The Filter which defines the target set of nodes to find */ private final Predicate<T> filter; /** an enumeration of all nodes to search from */ private final Iterator<T> roots; /** An iterator of child nodes for each node being searched */ protected final Map<Object, Iterator<? extends T>> pendingChildren = HashMapFactory.make(25); /** Flag recording whether initialization has happened. */ private boolean initialized = false; /** * Construct a depth-first enumerator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate * @throws IllegalArgumentException if G is null */ public DFSPathFinder(Graph<T> G, T N, Predicate<T> f) throws IllegalArgumentException { if (G == null) { throw new IllegalArgumentException("G is null"); } if (!G.containsNode(N)) { throw new IllegalArgumentException("source node not in graph: " + N); } this.G = G; this.roots = new NonNullSingletonIterator<>(N); this.filter = f; } /** * Construct a depth-first enumerator across the (possibly improper) subset of nodes reachable * from the nodes in the given enumeration. * * @param nodes the set of nodes from which to start searching */ public DFSPathFinder(Graph<T> G, Iterator<T> nodes, Predicate<T> f) { this.G = G; this.roots = nodes; this.filter = f; if (G == null) { throw new IllegalArgumentException("G is null"); } if (roots == null) { throw new IllegalArgumentException("roots is null"); } if (filter == null) { throw new IllegalArgumentException("filter is null"); } } private void init() { initialized = true; if (roots.hasNext()) { T n = roots.next(); push(n); setPendingChildren(n, getConnected(n)); } } /** * @return a List of nodes that specifies the first path found from a root to a node accepted by * the filter. Returns null if no path found. */ @Nullable public List<T> find() { if (!initialized) { init(); } while (hasNext()) { T n = peek(); if (filter.test(n)) { List<T> path = currentPath(); advance(); return path; } advance(); } return null; } protected List<T> currentPath() { ArrayList<T> result = new ArrayList<>(); for (T t : this) { result.add(0, t); } return result; } /** * Return whether there are any more nodes left to enumerate. * * @return true if there nodes left to enumerate. */ public boolean hasNext() { return !empty(); } /** * Method getPendingChildren. * * @return Object */ @Nullable protected Iterator<? extends T> getPendingChildren(T n) { return pendingChildren.get(n); } /** Method setPendingChildren. */ protected void setPendingChildren(T v, Iterator<? extends T> iterator) { pendingChildren.put(v, iterator); } /** Advance to the next graph node in discover time order. */ private void advance() { // we always return the top node on the stack. T currentNode = peek(); // compute the next node to return. assert getPendingChildren(currentNode) != null; do { T stackTop = peek(); for (T child : Iterator2Iterable.make(getPendingChildren(stackTop))) { if (getPendingChildren(child) == null) { // found a new child. push(child); setPendingChildren(child, getConnected(child)); return; } } // didn't find any new children. pop the stack and try again. pop(); } while (!empty()); // search for the next unvisited root. while (roots.hasNext()) { T nextRoot = roots.next(); if (getPendingChildren(nextRoot) == null) { push(nextRoot); setPendingChildren(nextRoot, getConnected(nextRoot)); } } return; } /** * get the out edges of a given node * * @param n the node of which to get the out edges * @return the out edges */ protected Iterator<? extends T> getConnected(T n) { return G.getSuccNodes(n); } private boolean empty() { return size() == 0; } private void push(T elt) { add(elt); } private T peek() { return get(size() - 1); } private T pop() { T e = get(size() - 1); remove(size() - 1); return e; } }
5,690
25.593458
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/FloydWarshall.java
/* * Copyright (c) 2002-2010 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.graph.NumberedGraph; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Floyd-Warshall algorithm to compute all-pairs shortest path in graph with no negative cycles. * * <p>TODO: this API should be cleaned up. * * @param <T> node type in the graph */ public class FloydWarshall<T> { public interface GetPath<T> { List<T> getPath(T from, T to); } public interface GetPaths<T> { Set<List<T>> getPaths(T from, T to); } protected final NumberedGraph<T> G; public FloydWarshall(NumberedGraph<T> g) { G = g; } protected int edgeCost() { return 1; } @SuppressWarnings("unused") protected void pathCallback(int i, int j, int k) {} public int[][] allPairsShortestPaths() { final int[][] result = new int[G.getNumberOfNodes()][G.getNumberOfNodes()]; for (int[] ints : result) { Arrays.fill(ints, Integer.MAX_VALUE); } for (T from : G) { final int fn = G.getNumber(from); IntSet tos = G.getSuccNodeNumbers(from); tos.foreach(x -> result[fn][x] = edgeCost()); } for (T kn : G) { int k = G.getNumber(kn); for (T in : G) { int i = G.getNumber(in); for (T jn : G) { int j = G.getNumber(jn); long newLen = (long) result[i][k] + (long) result[k][j]; if (newLen <= result[i][j]) { pathCallback(i, j, k); } if (newLen < result[i][j]) { result[i][j] = (int) newLen; } } } } return result; } public static <T> int[][] shortestPathLengths(NumberedGraph<T> G) { return new FloydWarshall<>(G).allPairsShortestPaths(); } public static <T> GetPath<T> allPairsShortestPath(final NumberedGraph<T> G) { return new FloydWarshall<>(G) { final int[][] next = new int[G.getNumberOfNodes()][G.getNumberOfNodes()]; @Override protected void pathCallback(int i, int j, int k) { next[i][j] = k; } private GetPath<T> doit() { for (int[] ints : next) { Arrays.fill(ints, -1); } final int[][] paths = allPairsShortestPaths(); return new GetPath<>() { @Override public String toString() { final StringBuilder s = new StringBuilder(); for (int i = 0; i <= G.getMaxNumber(); i++) { for (int j = 0; j <= G.getMaxNumber(); j++) { try { s.append(getPath(G.getNode(i), G.getNode(j))); } catch (UnsupportedOperationException e) { } } } return s.toString(); } @Override public List<T> getPath(T from, T to) { int fn = G.getNumber(from); int tn = G.getNumber(to); if (paths[fn][tn] == Integer.MAX_VALUE) { throw new UnsupportedOperationException("no path from " + from + " to " + to); } else { int intermediate = next[fn][tn]; if (intermediate == -1) { return Collections.emptyList(); } else { T in = G.getNode(intermediate); List<T> result = new ArrayList<>(getPath(from, in)); result.add(in); result.addAll(getPath(in, to)); return result; } } } }; } }.doit(); } public static <T> GetPaths<T> allPairsShortestPaths(final NumberedGraph<T> G) { return new FloydWarshall<>(G) { final MutableIntSet[][] next = new MutableIntSet[G.getNumberOfNodes()][G.getNumberOfNodes()]; @Override protected void pathCallback(int i, int j, int k) { if (next[i][j] == null) { next[i][j] = IntSetUtil.make(); } next[i][j].add(k); } private GetPaths<T> doit() { final int[][] paths = allPairsShortestPaths(); return new GetPaths<>() { @Override public String toString() { List<Set<List<T>>> x = new ArrayList<>(); for (int i = 0; i <= G.getMaxNumber(); i++) { for (int j = 0; j <= G.getMaxNumber(); j++) { try { x.add(getPaths(G.getNode(i), G.getNode(j))); } catch (UnsupportedOperationException e) { } } } return x.toString(); } @Override public Set<List<T>> getPaths(final T from, final T to) { int fn = G.getNumber(from); int tn = G.getNumber(to); if (paths[fn][tn] == Integer.MAX_VALUE) { throw new UnsupportedOperationException("no path from " + from + " to " + to); } else { MutableIntSet intermediate = next[fn][tn]; if (intermediate == null) { List<T> none = Collections.emptyList(); return Collections.singleton(none); } else { final Set<List<T>> result = new HashSet<>(); intermediate.foreach( x -> { T in = G.getNode(x); for (List<T> pre : getPaths(from, in)) { for (List<T> post : getPaths(in, to)) { List<T> path = new ArrayList<>(pre); path.add(in); path.addAll(post); result.add(path); } } }); return result; } } } }; } }.doit(); } }
6,335
28.607477
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/GraphDFSDiscoverTimeIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.graph.Graph; import java.util.Iterator; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; abstract class GraphDFSDiscoverTimeIterator<T> extends DFSDiscoverTimeIterator<T> { private static final long serialVersionUID = -5673397879499010863L; /** the graph being searched */ @Nullable private Graph<T> G; protected void init(Graph<T> G, Iterator<? extends T> nodes) { if (G == null) { throw new IllegalArgumentException("G is null"); } this.G = G; super.init(nodes); } @NullUnmarked @Override protected Iterator<? extends T> getConnected(T n) { return G.getSuccNodes(n); } }
1,103
28.052632
83
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/NumberedDFSDiscoverTimeIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.graph.NumberedGraph; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** * This class implements depth-first search over a NumberedGraph, return an enumeration of the nodes * of the graph in order of increasing discover time. This class follows the outNodes of the graph * nodes to define the graph, but this behavior can be changed by overriding the getConnected * method. */ public class NumberedDFSDiscoverTimeIterator<T> extends GraphDFSDiscoverTimeIterator<T> { private static final long serialVersionUID = -3919708273323217304L; /** An iterator of child nodes for each node being searched */ private final Iterator<? extends T>[] pendingChildren; /** The Graph being traversed */ protected final NumberedGraph<T> G; /** * Construct a depth-first enumerator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate * @throws IllegalArgumentException if G is null */ @SuppressWarnings("unchecked") public NumberedDFSDiscoverTimeIterator(NumberedGraph<T> G, T N) { if (G == null) { throw new IllegalArgumentException("G is null"); } this.G = G; pendingChildren = new Iterator[G.getMaxNumber() + 1]; init(G, new NonNullSingletonIterator<>(N)); } /** * Construct a depth-first enumerator across the (possibly improper) subset of nodes reachable * from the nodes in the given enumeration. * * @param G the graph whose nodes to enumerate * @param nodes the set of nodes from which to start searching * @throws IllegalArgumentException if G is null * @throws IllegalArgumentException if nodes == null */ @SuppressWarnings("unchecked") public NumberedDFSDiscoverTimeIterator(NumberedGraph<T> G, @Nullable Iterator<? extends T> nodes) throws IllegalArgumentException { if (G == null) { throw new IllegalArgumentException("G is null"); } if (nodes == null) { throw new IllegalArgumentException("nodes == null"); } this.G = G; pendingChildren = new Iterator[G.getMaxNumber() + 1]; init(G, nodes); } /** * Constructor DFSFinishTimeIterator. * * @throws NullPointerException if G is null */ public NumberedDFSDiscoverTimeIterator(NumberedGraph<T> G) throws NullPointerException { this(G, G == null ? null : G.iterator()); } /** * Method getPendingChildren. * * @return Object */ @Override protected Iterator<? extends T> getPendingChildren(T n) { return pendingChildren[G.getNumber(n)]; } /** Method setPendingChildren. */ @Override protected void setPendingChildren(T v, Iterator<? extends T> iterator) { pendingChildren[G.getNumber(v)] = iterator; } }
3,227
31.606061
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/NumberedDFSFinishTimeIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.graph.NumberedGraph; import java.util.Arrays; import java.util.Iterator; import org.jspecify.annotations.Nullable; /** * This class implements depth-first search over a NumberedGraph, return an enumeration of the nodes * of the graph in order of increasing discover time. This class follows the outNodes of the graph * nodes to define the graph, but this behavior can be changed by overriding the getConnected * method. */ public class NumberedDFSFinishTimeIterator<T> extends DFSFinishTimeIterator<T> { public static final long serialVersionUID = 8737376661L; /** An iterator of child nodes for each node being searched */ private Iterator<T>[] pendingChildren; /** The Graph being traversed */ private final NumberedGraph<T> G; /** * Construct a depth-first enumerator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate */ @SuppressWarnings("unchecked") NumberedDFSFinishTimeIterator(NumberedGraph<T> G, T N) { this.G = G; pendingChildren = new Iterator[G.getMaxNumber() + 1]; init(G, new NonNullSingletonIterator<>(N)); } /** * Construct a depth-first enumerator across the (possibly improper) subset of nodes reachable * from the nodes in the given enumeration. * * @param G the graph whose nodes to enumerate * @param nodes the set of nodes from which to start searching */ @SuppressWarnings("unchecked") NumberedDFSFinishTimeIterator(NumberedGraph<T> G, Iterator<? extends T> nodes) { this.G = G; pendingChildren = new Iterator[G.getMaxNumber() + 1]; init(G, nodes); } /** Constructor DFSFinishTimeIterator. */ NumberedDFSFinishTimeIterator(NumberedGraph<T> G) { this(G, G.iterator()); } @Nullable @Override Iterator<T> getPendingChildren(@Nullable T n) { int number = G.getNumber(n); if (number >= pendingChildren.length) { // the graph is probably growing as we travserse pendingChildren = Arrays.copyOf(pendingChildren, number * 2); return null; } if (number < 0) { assert false : "negative number for " + n + ' ' + n.getClass(); } return pendingChildren[number]; } /** Method setPendingChildren. */ @Override void setPendingChildren(@Nullable T v, Iterator<T> iterator) { pendingChildren[G.getNumber(v)] = iterator; } }
2,857
32.232558
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/SCCIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.ReverseIterator; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.impl.GraphInverter; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import org.jspecify.annotations.Nullable; /** * This class computes strongly connected components for a Graph (or a subset of it). It does not * store the SCCs in any lookaside structure, but rather simply generates an enumeration of them. * See Cormen, Leiserson, Rivest Ch. 23 Sec. 5 */ public class SCCIterator<T> implements Iterator<Set<T>> { /** The second DFS (the reverse one) needed while computing SCCs */ private final DFSFinishTimeIterator<T> rev; /** * Construct an enumeration across the SCCs of a given graph. * * @param G The graph over which to construct SCCs * @throws NullPointerException if G is null */ public SCCIterator(Graph<T> G) throws NullPointerException { this(G, G == null ? null : G.iterator()); } /** * Construct an enumeration of the SCCs of the subset of a given graph determined by starting at a * given set of nodes. */ public SCCIterator(Graph<T> G, @Nullable Iterator<T> nodes) { if (G == null) { throw new IllegalArgumentException("G cannot be null"); } Iterator<T> reverseFinishTime = ReverseIterator.reverse(DFS.iterateFinishTime(G, nodes)); rev = DFS.iterateFinishTime(GraphInverter.invert(G), reverseFinishTime); } /** Determine whether there are any more SCCs remaining in this enumeration. */ @Override public boolean hasNext() { return rev.hasNext(); } /** Find the next SCC in this enumeration */ @Override public Set<T> next() throws NoSuchElementException { Set<T> currentSCC = HashSetFactory.make(); T v = rev.next(); currentSCC.add(v); while (rev.hasNext() && !rev.isEmpty()) { currentSCC.add(rev.next()); } return currentSCC; } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } }
2,540
30.7625
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/SlowDFSDiscoverTimeIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.graph.Graph; import java.util.Iterator; import java.util.Map; import org.jspecify.annotations.Nullable; /** * This class implements depth-first search over a Graph, return an enumeration of the nodes of the * graph in order of increasing discover time. This class follows the outNodes of the graph nodes to * define the graph, but this behavior can be changed by overriding the getConnected method. */ public class SlowDFSDiscoverTimeIterator<T> extends GraphDFSDiscoverTimeIterator<T> { public static final long serialVersionUID = 9439217987188L; /** An iterator of child nodes for each node being searched A Map: Node -&gt; Iterator */ private final Map<T, Iterator<? extends T>> pendingChildren = HashMapFactory.make(25); /** For use with extreme care by subclasses that know what they're doing. */ protected SlowDFSDiscoverTimeIterator() {} /** * Construct a depth-first enumerator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate */ public SlowDFSDiscoverTimeIterator(Graph<T> G, T N) { init(G, new NonNullSingletonIterator<>(N)); } /** * Construct a depth-first enumerator across the (possibly improper) subset of nodes reachable * from the nodes in the given enumeration. * * @param G the graph whose nodes to enumerate * @param nodes the set of nodes from which to start searching */ public SlowDFSDiscoverTimeIterator(Graph<T> G, Iterator<T> nodes) { if (nodes == null) { throw new IllegalArgumentException("null nodes"); } init(G, nodes); } /** * Constructor SlowDFSDiscoverTimeIterator. * * @throws NullPointerException if G is null */ public SlowDFSDiscoverTimeIterator(Graph<T> G) throws NullPointerException { if (G == null) { throw new IllegalArgumentException("G is null"); } init(G, G.iterator()); } @Nullable @Override protected Iterator<? extends T> getPendingChildren(Object n) { return pendingChildren.get(n); } /** Method setPendingChildren. */ @Override protected void setPendingChildren(T v, Iterator<? extends T> iterator) { pendingChildren.put(v, iterator); } }
2,745
32.901235
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/SlowDFSFinishTimeIterator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.graph.Graph; import java.util.Iterator; import java.util.Map; import org.jspecify.annotations.Nullable; /** * This class implements depth-first search over a Graph, return an enumeration of the nodes of the * graph in order of increasing finishing time. This class follows the outNodes of the graph nodes * to define the graph, but this behavior can be changed by overriding the getConnected method. */ public class SlowDFSFinishTimeIterator<T> extends DFSFinishTimeIterator<T> { public static final long serialVersionUID = 3903190104743762628L; /** An iterator of child nodes for each node being searched */ private final Map<T, Iterator<T>> pendingChildren = HashMapFactory.make(25); /** * Construct a depth-first enumerator starting with a particular node in a directed graph. * * @param G the graph whose nodes to enumerate * @throws IllegalArgumentException if G is null */ public SlowDFSFinishTimeIterator(Graph<T> G, T N) throws IllegalArgumentException { if (G == null) { throw new IllegalArgumentException("G is null"); } if (!G.containsNode(N)) { throw new IllegalArgumentException("source node not in graph: " + N); } init(G, new NonNullSingletonIterator<>(N)); } /** * Construct a depth-first enumerator across the (possibly improper) subset of nodes reachable * from the nodes in the given enumeration. * * @param G the graph whose nodes to enumerate * @param nodes the set of nodes from which to start searching */ public SlowDFSFinishTimeIterator(Graph<T> G, @Nullable Iterator<? extends T> nodes) { if (G == null) { throw new IllegalArgumentException("G is null"); } if (nodes == null) { throw new IllegalArgumentException("G is null"); } init(G, nodes); } /** @throws NullPointerException if G is null */ public SlowDFSFinishTimeIterator(Graph<T> G) throws NullPointerException { this(G, G == null ? null : G.iterator()); } @Nullable @Override Iterator<T> getPendingChildren(@Nullable T n) { return pendingChildren.get(n); } @Override void setPendingChildren(@Nullable T v, Iterator<T> iterator) { pendingChildren.put(v, iterator); } }
2,770
33.6375
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/Topological.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.ReverseIterator; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.impl.GraphInverter; import java.util.Iterator; /** Utilities for iterating over graphs in topological order. */ public class Topological { /** * Build an Iterator over all the nodes in the graph, in an order such that SCCs are visited in * topological order. * * @throws IllegalArgumentException if graph == null */ public static <T> Iterable<T> makeTopologicalIter(final Graph<T> graph) throws IllegalArgumentException { if (graph == null) { throw new IllegalArgumentException("graph == null"); } return () -> { // the following code ensures a topological order over SCCs. // note that the first two lines of the following give a topological // order for dags, but that can get screwed up by cycles. so // instead, we use Tarjan's SCC algorithm, which happens to // visit nodes in an order consistent with a top. order over SCCs. // finish time is post-order // note that if you pay attention only to the first representative // of each SCC discovered, we have a top. order of these SCC // representatives Iterator<T> finishTime = DFS.iterateFinishTime(graph); // reverse postorder is usual topological sort. Iterator<T> rev = ReverseIterator.reverse(finishTime); // the following statement helps out the GC; note that finishTime holds // on to a large array finishTime = null; Graph<T> G_T = GraphInverter.invert(graph); return DFS.iterateFinishTime(G_T, rev); }; } }
2,059
36.454545
97
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/graph/traverse/WelshPowell.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.graph.traverse; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.graph.NumberedGraph; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; public class WelshPowell<T> { public static class ColoredVertices<T> { private final boolean fullColoring; private final Map<T, Integer> colors; private final int numColors; public boolean isFullColoring() { return fullColoring; } public Map<T, Integer> getColors() { return colors; } public int getNumColors() { return numColors; } public ColoredVertices(boolean fullColoring, NumberedGraph<T> G, int colors[], int numColors) { this(fullColoring, makeMap(G, colors), numColors); } private static <T> Map<T, Integer> makeMap(NumberedGraph<T> G, int[] colors) { Map<T, Integer> colorMap = HashMapFactory.make(); for (int i = 0; i < colors.length; i++) { if (colors[i] != -1) { colorMap.put(G.getNode(i), colors[i]); } } return colorMap; } public ColoredVertices(boolean fullColoring, Map<T, Integer> colors, int numColors) { this.fullColoring = fullColoring; this.colors = colors; this.numColors = numColors; } @Override public String toString() { return colors.toString(); } } public static <T> Comparator<T> defaultComparator(final NumberedGraph<T> G) { return (o1, o2) -> { int o1edges = G.getSuccNodeCount(o1) + G.getPredNodeCount(o1); int o2edges = G.getSuccNodeCount(o2) + G.getPredNodeCount(o2); if (o1edges != o2edges) { return o2edges - o1edges; } else { return o2.toString().compareTo(o1.toString()); } }; } public ColoredVertices<T> color(final NumberedGraph<T> G) { return color(G, defaultComparator(G), Integer.MAX_VALUE); } public ColoredVertices<T> color(final NumberedGraph<T> G, int maxColors) { return color(G, defaultComparator(G), maxColors); } public ColoredVertices<T> color(final NumberedGraph<T> G, Comparator<T> order, int maxColors) { int[] colors = new int[G.getMaxNumber() + 1]; Arrays.fill(colors, -1); SortedSet<T> vertices = new TreeSet<>(order); for (T n : G) { vertices.add(n); } int currentColor = 0; int colored = 0; for (T n : vertices) { int id = G.getNumber(n); if (colors[id] == -1) { colors[id] = currentColor; colored++; for (T m : vertices) { if (colors[G.getNumber(m)] == -1) { color_me: { for (T p : Iterator2Iterable.make(G.getPredNodes(m))) { if (colors[G.getNumber(p)] == currentColor) { break color_me; } } for (T s : Iterator2Iterable.make(G.getSuccNodes(m))) { if (colors[G.getNumber(s)] == currentColor) { break color_me; } } colors[G.getNumber(m)] = currentColor; colored++; if (currentColor == maxColors - 1) { return new ColoredVertices<>(false, G, colors, currentColor); } } } } currentColor++; if (currentColor == maxColors - 1) { return new ColoredVertices<>(false, G, colors, currentColor); } } } assert colored == G.getNumberOfNodes(); return new ColoredVertices<>(true, G, colors, currentColor); } }
4,050
26.937931
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/heapTrace/HeapTracer.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.heapTrace; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import java.io.File; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayDeque; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** Simple utility that uses reflection to trace memory */ public class HeapTracer { private static final boolean DEBUG = false; /** Names of all classes considered for analysis */ private static final String[] rootClasses = generateRootClassesFromWorkspace(); /** Object instances that should be considered roots of the heap trace */ private final Collection<?> rootInstances; /** Stack of instance objects discovered but not yet traced. */ private final ArrayDeque<Object> scalarWorkList = new ArrayDeque<>(); /** Stack of array objects discovered but not yet traced. */ private final ArrayDeque<Object> arrayWorkList = new ArrayDeque<>(); /** How many bytes do we assume the JVM wastes on each instance? */ private static final int BYTES_IN_HEADER = 12; /** Should all static fields be considered roots of the heap traversal? */ private final boolean traceStatics; /** Map: Class -&gt; Integer, the size of each class */ private final HashMap<Class<?>, Integer> sizeMap = HashMapFactory.make(); private static final Object DUMMY = new Object(); /** Classes that we should understand because they're internal to a container object */ private static final HashSet<Class<?>> internalClasses = HashSetFactory.make(); static { try { internalClasses.add(Class.forName("java.lang.String")); internalClasses.add(Class.forName("java.util.HashMap$Entry")); internalClasses.add(Class.forName("java.util.HashMap")); internalClasses.add(Class.forName("java.util.HashSet")); internalClasses.add(Class.forName("java.util.Vector")); internalClasses.add(Class.forName("com.ibm.wala.util.collections.SmallMap")); internalClasses.add(Class.forName("com.ibm.wala.util.collections.SimpleVector")); internalClasses.add(Class.forName("com.ibm.wala.util.intset.SimpleIntVector")); internalClasses.add(Class.forName("com.ibm.wala.util.intset.BasicNaturalRelation")); internalClasses.add(Class.forName("com.ibm.wala.util.intset.SparseIntSet")); internalClasses.add(Class.forName("com.ibm.wala.util.collections.SparseVector")); internalClasses.add(Class.forName("com.ibm.wala.util.intset.MutableSharedBitVectorIntSet")); internalClasses.add(Class.forName("com.ibm.wala.util.intset.MutableSparseIntSet")); internalClasses.add(Class.forName("com.ibm.wala.util.collections.TwoLevelVector")); internalClasses.add( Class.forName("com.ibm.wala.util.graph.impl.DelegatingNumberedNodeManager")); internalClasses.add(Class.forName("com.ibm.wala.util.graph.impl.SparseNumberedEdgeManager")); } catch (ClassNotFoundException e) { e.printStackTrace(); Assertions.UNREACHABLE(); } } /** @param traceStatics Should all static fields be considered roots of the heap traversal? */ HeapTracer(boolean traceStatics) { rootInstances = Collections.emptySet(); this.traceStatics = traceStatics; } public HeapTracer(Collection<?> c, boolean traceStatics) { rootInstances = c; this.traceStatics = traceStatics; } public static void main(String[] args) { try { Result r = new HeapTracer(true).perform(); System.err.println(r.toString()); } catch (Throwable t) { t.printStackTrace(); } } /** @return the name of each class that's in the classpath */ private static String[] generateRootClassesFromWorkspace() { String classpath = System.getProperty("java.class.path"); Object[] binDirectories = extractBinDirectories(classpath); HashSet<String> classFileNames = HashSetFactory.make(); for (Object binDirectorie : binDirectories) { String dir = (String) binDirectorie; File fdir = new File(dir); classFileNames.addAll(findClassNames(dir, fdir)); } return classFileNames.toArray(new String[0]); } /** * @param rootDir root of the classpath governing file f * @param f a File or directory * @return {@link Collection}&lt;{@link String}&gt; representing the class names in f */ private static Collection<String> findClassNames(String rootDir, File f) { HashSet<String> result = HashSetFactory.make(); if (f.isDirectory()) { File[] files = f.listFiles(); for (File file : files) { result.addAll(findClassNames(rootDir, file)); } } else { if (f.getName().indexOf(".class") > 0) { String p = f.getAbsolutePath(); p = p.substring(rootDir.length() + 1); // trim the last 6 characters which hold ".class" p = p.substring(0, p.length() - 6); p = p.replace('\\', '.'); return Collections.singleton(p); } } return result; } /** @return set of strings that are names of directories that contain "bin" */ private static Object[] extractBinDirectories(String classpath) { StringTokenizer t = new StringTokenizer(classpath, ";"); HashSet<String> result = HashSetFactory.make(); while (t.hasMoreTokens()) { String n = t.nextToken(); if (n.indexOf("bin") > 0) { result.add(n); } } return result.toArray(); } /** Trace the heap and return the results */ public Result perform() throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException { Result result = new Result(); IdentityHashMap<Object, Object> objectsVisited = new IdentityHashMap<>(); if (traceStatics) { for (String rootClasse : rootClasses) { Class<?> c = Class.forName(rootClasse); Field[] fields = c.getDeclaredFields(); for (Field field : fields) { if (isStatic(field)) { traverse(field, result, objectsVisited); } } } } for (Object instance : rootInstances) { Class<?> c = instance.getClass(); Set<Field> fields = getAllInstanceFields(c); for (Field f : fields) { traverse(f, instance, result, objectsVisited); } } return result; } /** @return the estimated size of the object */ private static int computeSizeOf(Object o) { int result = BYTES_IN_HEADER; Class<?> c = o.getClass(); if (c.isArray()) { Class<?> elementType = c.getComponentType(); int length = Array.getLength(o); result += length * sizeOfSlot(elementType); } else if (c.isPrimitive()) { throw new Error(); } else { Collection<Field> fields = getAllInstanceFields(c); for (Field f : fields) { result += sizeOfSlot(f.getType()); } } return result; } /** @return the estimated size of the object */ private int sizeOf(Object o) { Class<?> c = o.getClass(); if (c.isArray()) { return computeSizeOf(o); } else { Integer S = sizeMap.get(c); if (S == null) { S = computeSizeOf(o); sizeMap.put(c, S); } return S; } } /** @return size of a field of type c, in bytes */ private static int sizeOfSlot(Class<?> c) { if (!c.isPrimitive()) { return 4; } else { if (c.equals(Boolean.TYPE) || c.equals(Character.TYPE) || c.equals(Byte.TYPE)) { return 1; } else if (c.equals(Short.TYPE)) { return 2; } else if (c.equals(Integer.TYPE) || c.equals(Float.TYPE)) { return 4; } else if (c.equals(Long.TYPE) || c.equals(Double.TYPE)) { return 8; } else { throw new Error(); } } } /** Traverse the heap starting at a static field */ private void traverse(Field root, Result result, IdentityHashMap<Object, Object> objectsVisited) throws IllegalArgumentException, IllegalAccessException { if (DEBUG) { System.err.println(("traverse root " + root)); } root.setAccessible(true); Object contents = root.get(null); if (contents != null && (objectsVisited.get(contents) == null)) { objectsVisited.put(contents, DUMMY); Class<?> c = contents.getClass(); if (c.isArray()) { result.registerReachedFrom(root, root, contents); arrayWorkList.push(Pair.make(root, contents)); } else { result.registerReachedFrom(root, root, contents); if (internalClasses.contains(c)) { contents = Pair.make(root, contents); } scalarWorkList.push(contents); } } drainWorkLists(root, result, objectsVisited); } private void traverse( Field root, Object instance, Result result, IdentityHashMap<Object, Object> objectsVisited) throws IllegalArgumentException, IllegalAccessException { traverseFieldOfScalar(root, root, instance, null, objectsVisited, result); drainWorkLists(root, result, objectsVisited); } @SuppressWarnings("rawtypes") private void drainWorkLists( Field root, Result result, IdentityHashMap<Object, Object> objectsVisited) throws IllegalAccessException { while (!scalarWorkList.isEmpty() || !arrayWorkList.isEmpty()) { if (!scalarWorkList.isEmpty()) { Object scalar = scalarWorkList.pop(); if (scalar instanceof Pair) { Pair p = (Pair) scalar; traverseScalar(root, p.snd, p.fst, result, objectsVisited); } else { traverseScalar(root, scalar, null, result, objectsVisited); } } if (!arrayWorkList.isEmpty()) { Pair p = (Pair) arrayWorkList.pop(); traverseArray(root, p.snd, p.fst, result, objectsVisited); } } } private void traverseArray( Field root, Object array, Object container, Result result, IdentityHashMap<Object, Object> objectsVisited) throws IllegalArgumentException { if (DEBUG) { System.err.println(("traverse array " + array.getClass())); } Class<?> elementKlass = array.getClass().getComponentType(); if (elementKlass.isPrimitive()) { return; } assert container != null; int length = Array.getLength(array); for (int i = 0; i < length; i++) { Object contents = Array.get(array, i); if (contents != null && (objectsVisited.get(contents) == null)) { objectsVisited.put(contents, DUMMY); Class<?> klass = contents.getClass(); if (klass.isArray()) { result.registerReachedFrom(root, container, contents); contents = Pair.make(container, contents); arrayWorkList.push(contents); } else { result.registerReachedFrom(root, container, contents); contents = Pair.make(container, contents); scalarWorkList.push(contents); } } } } private void traverseScalar( Field root, Object scalar, @Nullable Object container, Result result, IdentityHashMap<Object, Object> objectsVisited) throws IllegalArgumentException, IllegalAccessException { Class<?> c = scalar.getClass(); if (DEBUG) { System.err.println(("traverse scalar " + c)); } Field[] fields = getAllReferenceInstanceFields(c); for (Field field : fields) { traverseFieldOfScalar(root, field, scalar, container, objectsVisited, result); } } private final Object OK = new Object(); private final Object BAD = new Object(); private final HashMap<Package, Object> packageStatus = HashMapFactory.make(); private final boolean isInBadPackage(Class<?> c) { Package p = c.getPackage(); if (p == null) { return false; } Object status = packageStatus.get(p); if (status == OK) { return false; } else if (status == BAD) { return true; } else { if (p.getName() != null && p.getName().contains("sun.reflect")) { if (DEBUG) { System.err.println(("making " + p + " a BAD package")); } packageStatus.put(p, BAD); return true; } else { if (DEBUG) { System.err.println(("making " + p + " an OK package")); } packageStatus.put(p, OK); return false; } } } private void traverseFieldOfScalar( Field root, Field f, Object scalar, @Nullable Object container, IdentityHashMap<Object, Object> objectsVisited, Result result) throws IllegalArgumentException, IllegalAccessException { // The following atrocious hack is needed to prevent the IBM 141 VM // from crashing if (isInBadPackage(f.getType())) { return; } if (container == null) { container = f; } f.setAccessible(true); Object contents = f.get(scalar); if (contents != null && (objectsVisited.get(contents) == null)) { try { objectsVisited.put(contents, DUMMY); } catch (Exception e) { e.printStackTrace(); return; } Class<?> klass = contents.getClass(); if (klass.isArray()) { result.registerReachedFrom(root, container, contents); contents = Pair.make(container, contents); arrayWorkList.push(contents); } else { result.registerReachedFrom(root, container, contents); if (internalClasses.contains(klass)) { contents = Pair.make(container, contents); } scalarWorkList.push(contents); } } } private static HashSet<Field> getAllInstanceFields(Class<?> c) { HashSet<Field> result = HashSetFactory.make(); Class<?> klass = c; while (klass != null) { Field[] fields = klass.getDeclaredFields(); for (Field field : fields) { if (!isStatic(field)) { result.add(field); } } klass = klass.getSuperclass(); } return result; } private final HashMap<Class<?>, Field[]> allReferenceFieldsCache = HashMapFactory.make(); /** @return Field[] representing reference instance fields of a class */ private Field[] getAllReferenceInstanceFields(Class<?> c) { if (allReferenceFieldsCache.containsKey(c)) return allReferenceFieldsCache.get(c); else { HashSet<Field> s = HashSetFactory.make(); Class<?> klass = c; while (klass != null) { Field[] fields = klass.getDeclaredFields(); for (Field field : fields) { if (!isStatic(field)) { Class<?> fc = field.getType(); if (!fc.isPrimitive()) { s.add(field); } } } klass = klass.getSuperclass(); } Field[] result = s.toArray(new Field[0]); allReferenceFieldsCache.put(c, result); return result; } } private static boolean isStatic(Field field) { return Modifier.isStatic(field.getModifiers()); } public static void analyzeLeaks() { analyzeLeaks(true); } /** * Trace the heap and dump the output to the tracefile * * @param traceStatics should all static fields be considered roots? */ public static void analyzeLeaks(boolean traceStatics) { try { System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); long t = Runtime.getRuntime().totalMemory(); long f = Runtime.getRuntime().freeMemory(); System.err.println(("Total Memory: " + t)); System.err.println(("Occupied Memory: " + (t - f))); HeapTracer.Result r = new HeapTracer(traceStatics).perform(); System.err.println("HeapTracer Analysis:"); System.err.println(r.toString()); } catch (IllegalArgumentException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } } /** * Trace the heap and dump the output to the tracefile * * @param instances instances to be considered roots of the heap traversal * @param traceStatics should all static fields be considered roots? */ @NullUnmarked public static HeapTracer.Result traceHeap(Collection<?> instances, boolean traceStatics) { try { System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); long t = Runtime.getRuntime().totalMemory(); long f = Runtime.getRuntime().freeMemory(); System.err.println(("Total Memory: " + t)); System.err.println(("Occupied Memory: " + (t - f))); HeapTracer.Result r = new HeapTracer(instances, traceStatics).perform(); System.err.println("HeapTracer Analysis:"); System.err.println(r.toString()); return r; } catch (IllegalArgumentException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * @author sfink * <p>Statistics about objects reached from a single root */ class Demographics { /** mapping: Object (key) -&gt; Integer (number of instances in a partition) */ private final HashMap<Object, Integer> instanceCount = HashMapFactory.make(); /** mapping: Object (key) -&gt; Integer (bytes) */ private final HashMap<Object, Integer> sizeCount = HashMapFactory.make(); /** Total number of instances discovered */ private int totalInstances = 0; /** Total number of bytes discovered */ private int totalSize = 0; /** * @param key a name for the heap partition to which o belongs * @param o the object to register */ public void registerObject(Object key, Object o) { Integer I = instanceCount.get(key); int newCount = (I == null) ? 1 : I + 1; instanceCount.put(key, newCount); totalInstances++; I = sizeCount.get(key); int s = sizeOf(o); int newSizeCount = (I == null) ? s : I + s; sizeCount.put(key, newSizeCount); totalSize += s; } @NullUnmarked @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("Totals: ").append(totalInstances).append(' ').append(totalSize).append('\n'); TreeSet<Object> sorted = new TreeSet<>(new SizeComparator()); sorted.addAll(instanceCount.keySet()); for (Object key : sorted) { Integer I = instanceCount.get(key); Integer bytes = sizeCount.get(key); result.append(" ").append(I).append(" ").append(bytes).append(" "); result.append(bytes / I).append(" "); result.append(key); result.append('\n'); } return result.toString(); } /** compares two keys based on the total size of the heap traced from that key */ private class SizeComparator implements Comparator<Object> { /* * @see java.util.Comparator#compare(java.lang.Object, * java.lang.Object) */ @NullUnmarked @Override public int compare(Object o1, Object o2) { Integer i1 = sizeCount.get(o1); Integer i2 = sizeCount.get(o2); return i2 - i1; } } /** @return Returns the totalSize. */ public int getTotalSize() { return totalSize; } /** @return Returns the totalInstances. */ public int getTotalInstances() { return totalInstances; } } /** * @author sfink * <p>Results of the heap trace */ public class Result { /** a mapping from Field (static field roots) -&gt; Demographics object */ private final HashMap<Field, Demographics> roots = HashMapFactory.make(); /** @return the Demographics object tracking objects traced from that root */ private Demographics findOrCreateDemographics(Field root) { Demographics d = roots.get(root); if (d == null) { d = new Demographics(); roots.put(root, d); } return d; } public void registerReachedFrom(Field root, Object predecessor, Object contents) { Demographics d = findOrCreateDemographics(root); d.registerObject(Pair.make(predecessor, contents.getClass()), contents); } public int getTotalSize() { int totalSize = 0; for (Demographics d : roots.values()) { totalSize += d.getTotalSize(); } return totalSize; } @NullUnmarked @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("Assuming " + BYTES_IN_HEADER + " header bytes per object\n"); int totalInstances = 0; int totalSize = 0; for (Demographics d : roots.values()) { totalInstances += d.getTotalInstances(); totalSize += d.getTotalSize(); } result.append("Total instances: ").append(totalInstances).append('\n'); result.append("Total size(bytes): ").append(totalSize).append('\n'); TreeSet<Field> sortedDemo = new TreeSet<>(new SizeComparator()); sortedDemo.addAll(roots.keySet()); for (Field field : sortedDemo) { Object root = field; Demographics d = roots.get(root); if (d.getTotalSize() > 10000) { result.append(" root: ").append(root).append('\n'); result.append(d); } } return result.toString(); } /** compares two keys based on the total size of the heap traced from that key */ private class SizeComparator implements Comparator<Field> { /* * @see java.util.Comparator#compare(java.lang.Object, * java.lang.Object) */ @NullUnmarked @Override public int compare(Field o1, Field o2) { Demographics d1 = roots.get(o1); Demographics d2 = roots.get(o2); return d2.getTotalSize() - d1.getTotalSize(); } } } }
22,385
32.06647
99
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/intset/BasicNaturalRelation.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.intset; import com.ibm.wala.util.collections.IVector; import com.ibm.wala.util.collections.SimpleVector; import com.ibm.wala.util.collections.TwoLevelVector; import com.ibm.wala.util.debug.Assertions; import java.io.Serializable; import java.util.Iterator; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** * A relation between non-negative integers * * <p>This implementation uses n IntVectors, to hold the first n y's associated with each x, and * then 1 extra vector of SparseIntSet to hold the remaining ys. */ public final class BasicNaturalRelation implements IBinaryNaturalRelation, Serializable { private static final long serialVersionUID = 4483720230344867621L; private static final boolean VERBOSE = false; private static final boolean DEBUG = false; /** Tokens used as enumerated types to control the representation */ public static final byte SIMPLE = 0; public static final byte TWO_LEVEL = 1; public static final byte SIMPLE_SPACE_STINGY = 2; private static final int EMPTY_CODE = -1; private static final int DELEGATE_CODE = -2; /** * smallStore[i][x] holds * * <ul> * <li>if &gt;=0, the ith integer associated with x * <li>if -2, then use the delegateStore instead of the small store * <li>if -1, then R(x) is empty * </ul> * * represented. */ final IntVector[] smallStore; /** delegateStore[x] holds an int set of the y's s.t. R(x,y) */ final IVector<IntSet> delegateStore; /** * @param implementation a set of codes that represent how the first n IntVectors should be * implemented. * @param vectorImpl a code that indicates how to represent the delegateStore. * <p>For example implementation = * {SIMPLE_INT_VECTOR,TWO_LEVEL_INT_VECTOR,TWO_LEVEL_INT_VECTOR} will result in an * implementation where the first 3 y's associated with each x are represented in IntVectors. * The IntVector for the first y will be implemented with a SimpleIntVector, and the 2nd and * 3rd are implemented with TwoLevelIntVector * @throws IllegalArgumentException if implementation is null * @throws IllegalArgumentException if implementation.length == 0 */ public BasicNaturalRelation(byte[] implementation, byte vectorImpl) throws IllegalArgumentException { if (implementation == null) { throw new IllegalArgumentException("implementation is null"); } if (implementation.length == 0) { throw new IllegalArgumentException("implementation.length == 0"); } smallStore = new IntVector[implementation.length]; for (int i = 0; i < implementation.length; i++) { switch (implementation[i]) { case SIMPLE: smallStore[i] = new SimpleIntVector(EMPTY_CODE); break; case TWO_LEVEL: smallStore[i] = new TwoLevelIntVector(EMPTY_CODE); break; case SIMPLE_SPACE_STINGY: smallStore[i] = new TunedSimpleIntVector(EMPTY_CODE, 1, 1.1f); break; default: throw new IllegalArgumentException("unsupported implementation " + implementation[i]); } } switch (vectorImpl) { case SIMPLE: delegateStore = new SimpleVector<>(); break; case TWO_LEVEL: delegateStore = new TwoLevelVector<>(); break; default: throw new IllegalArgumentException("unsupported implementation " + vectorImpl); } } public BasicNaturalRelation() { this(new byte[] {SIMPLE}, TWO_LEVEL); } /** maximum x for any pair in this relation. */ private int maxX = -1; /** * Add (x,y) to the relation. * * <p>This is performance-critical, so the implementation looks a little ugly in order to help out * the compiler with redundancy elimination. * * @return true iff the relation changes as a result of this call. */ @NullUnmarked @Override public boolean add(int x, int y) throws IllegalArgumentException { if (x < 0) { throw new IllegalArgumentException("illegal x: " + x); } if (y < 0) { throw new IllegalArgumentException("illegal y: " + y); } maxX = Math.max(maxX, x); MutableIntSet delegated = (MutableIntSet) delegateStore.get(x); if (delegated != null) { return delegated.add(y); } else { IntVector smallStore0 = smallStore[0]; if (smallStore0.get(x) != EMPTY_CODE) { int i = 0; IntVector v = null; int ssLength = smallStore.length; for (; i < ssLength; i++) { v = smallStore[i]; int val = v.get(x); if (val == y) { return false; } else if (val == EMPTY_CODE) { break; } } if (i == ssLength) { MutableIntSet s = new BimodalMutableIntSet(ssLength + 1, 1.1f); delegateStore.set(x, s); for (IntVector vv : smallStore) { s.add(vv.get(x)); vv.set(x, DELEGATE_CODE); } s.add(y); } else { v.set(x, y); } return true; } else { // smallStore[0].get(x) == EMPTY_CODE : just add smallStore0.set(x, y); return true; } } } private boolean usingDelegate(int x) { return smallStore[0].get(x) == DELEGATE_CODE; } @Override public Iterator<IntPair> iterator() { return new TotalIterator(); } private class TotalIterator implements Iterator<IntPair> { /** the next x that will be returned in a pair (x,y), or -1 if not hasNext() */ private int nextX = -1; /** * the source of the next y ... an integer between 0 and smallStore.length .. nextIndex == * smallStore.length means use the delegateIterator */ private int nextIndex = -1; @Nullable private IntIterator delegateIterator = null; TotalIterator() { advanceX(); } private void advanceX() { delegateIterator = null; for (int i = nextX + 1; i <= maxX; i++) { if (anyRelated(i)) { nextX = i; nextIndex = getFirstIndex(i); if (nextIndex == smallStore.length) { IntSet s = delegateStore.get(i); assert s.size() > 0; delegateIterator = s.intIterator(); } return; } } nextX = -1; } private int getFirstIndex(int x) { if (smallStore[0].get(x) >= 0) { // will get first y for x from smallStore[0][x] return 0; } else { // will get first y for x from delegateStore[x] return smallStore.length; } } @Override public boolean hasNext() { return nextX != -1; } @NullUnmarked @Override public IntPair next() { IntPair result = null; if (nextIndex == smallStore.length) { int y = delegateIterator.next(); result = new IntPair(nextX, y); if (!delegateIterator.hasNext()) { advanceX(); } } else { result = new IntPair(nextX, smallStore[nextIndex].get(nextX)); if (nextIndex == (smallStore.length - 1) || smallStore[nextIndex + 1].get(nextX) == EMPTY_CODE) { advanceX(); } else { nextIndex++; } } return result; } @Override public void remove() { Assertions.UNREACHABLE(); } } private IntSet getDelegate(int x) { return delegateStore.get(x); } /** @return true iff there exists pair (x,y) for some y */ @Override public boolean anyRelated(int x) { return smallStore[0].get(x) != EMPTY_CODE; } @NullUnmarked @Override public IntSet getRelated(int x) { if (DEBUG) { assert x >= 0; } int ss0 = smallStore[0].get(x); if (ss0 == EMPTY_CODE) { return null; } else { if (ss0 == DELEGATE_CODE) { return getDelegate(x); } else { int ssLength = smallStore.length; switch (ssLength) { case 2: { int ss1 = smallStore[1].get(x); if (ss1 == EMPTY_CODE) { return SparseIntSet.singleton(ss0); } else { return SparseIntSet.pair(ss0, ss1); } } case 1: return SparseIntSet.singleton(ss0); default: { int ss1 = smallStore[1].get(x); if (ss1 == EMPTY_CODE) { return SparseIntSet.singleton(ss0); } else { MutableSparseIntSet result = MutableSparseIntSet.createMutableSparseIntSet(ssLength); for (IntVector element : smallStore) { if (element.get(x) == EMPTY_CODE) { break; } result.add(element.get(x)); } return result; } } } } } } @Override public int getRelatedCount(int x) throws IllegalArgumentException { if (x < 0) { throw new IllegalArgumentException("x must be greater than zero"); } if (!anyRelated(x)) { return 0; } else { if (usingDelegate(x)) { return getDelegate(x).size(); } else { int result = 0; for (IntVector element : smallStore) { if (element.get(x) == EMPTY_CODE) { break; } result++; } return result; } } } @Override public void remove(int x, int y) { if (x < 0) { throw new IllegalArgumentException("illegal x: " + x); } if (y < 0) { throw new IllegalArgumentException("illegal y: " + y); } if (usingDelegate(x)) { // TODO: switch representation back to small store? MutableIntSet s = (MutableIntSet) delegateStore.get(x); s.remove(y); if (s.size() == 0) { delegateStore.set(x, null); for (IntVector element : smallStore) { element.set(x, EMPTY_CODE); } } } else { for (int i = 0; i < smallStore.length; i++) { if (smallStore[i].get(x) == y) { for (int j = i; j < smallStore.length; j++) { if (j < (smallStore.length - 1)) { smallStore[j].set(x, smallStore[j + 1].get(x)); } else { smallStore[j].set(x, EMPTY_CODE); } } return; } } } } @Override public void removeAll(int x) { for (IntVector element : smallStore) { element.set(x, EMPTY_CODE); } delegateStore.set(x, null); } /** @see com.ibm.wala.util.debug.VerboseAction#performVerboseAction() */ @Override public void performVerboseAction() { if (VERBOSE) { System.err.println((getClass() + " stats:")); System.err.println(("count: " + countPairs())); System.err.println(("delegate: " + delegateStore.getClass())); delegateStore.performVerboseAction(); for (int i = 0; i < smallStore.length; i++) { System.err.println(("smallStore[" + i + "]: " + smallStore[i].getClass())); } } } /** * This is slow. * * @return the size of this relation, in the number of pairs */ private int countPairs() { int result = 0; for (@SuppressWarnings("unused") Object name : this) { result++; } return result; } @Override public boolean contains(int x, int y) { if (x < 0) { throw new IllegalArgumentException("invalid x: " + x); } if (y < 0) { throw new IllegalArgumentException("invalid y: " + y); } if (usingDelegate(x)) { return getDelegate(x).contains(y); } else { for (IntVector element : smallStore) { if (element.get(x) == y) { return true; } } return false; } } @Override public int maxKeyValue() { return maxX; } @Override public String toString() { StringBuilder result = new StringBuilder(); for (int i = 0; i <= maxX; i++) { result.append(i).append(':'); result.append(getRelated(i)); result.append('\n'); } return result.toString(); } }
12,571
27.12528
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/intset/BimodalMutableIntSet.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.intset; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; /** * An implementation of {@link MutableIntSet} that delegates to either a {@link MutableSparseIntSet} * or a {@link BitVectorIntSet} */ public class BimodalMutableIntSet implements MutableIntSet { private static final long serialVersionUID = 7332332295529936562L; MutableIntSet impl; @Override public void copySet(IntSet set) { if (set == null) { throw new IllegalArgumentException("null set"); } if (set instanceof BimodalMutableIntSet) { impl = IntSetUtil.makeMutableCopy(((BimodalMutableIntSet) set).impl); } else if (sameRepresentation(impl, set)) { // V and other.V use the same representation. update in place. impl.copySet(set); } else if (set instanceof BitVectorIntSet || set instanceof SparseIntSet) { // other.V has a different representation. make a new copy impl = IntSetUtil.makeMutableCopy(set); } else if (set instanceof MutableSharedBitVectorIntSet) { impl = IntSetUtil.makeMutableCopy(((MutableSharedBitVectorIntSet) set).makeSparseCopy()); } else { Assertions.UNREACHABLE("Unexpected type " + set.getClass()); } assert impl instanceof BitVectorIntSet || impl instanceof MutableSparseIntSet; } /** @return true iff we would like to use the same representation for V as we do for W */ private static boolean sameRepresentation(IntSet V, IntSet W) { // for now we assume that we always want to use the same representation for // V as // for W. return V.getClass().equals(W.getClass()); } @Override public boolean addAll(IntSet set) { if (set instanceof BitVectorIntSet && !(impl instanceof BitVectorIntSet)) { // change the representation before performing the operation impl = new BitVectorIntSet(impl); } boolean result = impl.addAll(set); if (result) { maybeChangeRepresentation(); } return result; } /** @see com.ibm.wala.util.intset.MutableIntSet#addAll(com.ibm.wala.util.intset.IntSet) */ @Override public boolean addAllInIntersection(IntSet other, IntSet filter) { if (other instanceof BitVectorIntSet && !(impl instanceof BitVectorIntSet)) { // change the representation before performing the operation impl = new BitVectorIntSet(impl); } boolean result = impl.addAllInIntersection(other, filter); if (result) { maybeChangeRepresentation(); } return result; } /** * If appropriate, change the representation of V. * * <p>For now, this method will change a MutableSparseIntSet to a BitVector if it saves space. * * <p>TODO: add more variants. */ private void maybeChangeRepresentation() { assert impl instanceof BitVectorIntSet || impl instanceof MutableSparseIntSet; if (impl == null) { return; } int sparseSize = impl.size(); if (sparseSize <= 2) { // don't bother return; } int bvSize = BitVectorBase.subscript(impl.max()) + 1; if (sparseSize > bvSize) { if (!(impl instanceof BitVectorIntSet)) { impl = new BitVectorIntSet(impl); } } else { if (!(impl instanceof MutableSparseIntSet)) { impl = MutableSparseIntSet.make(impl); } } assert impl instanceof BitVectorIntSet || impl instanceof MutableSparseIntSet; } @Override public boolean add(int i) { boolean result = impl.add(i); if (result) { maybeChangeRepresentation(); } return result; } @Override public boolean remove(int i) { boolean result = impl.remove(i); maybeChangeRepresentation(); return result; } @Override public void intersectWith(IntSet set) throws UnimplementedError { if (set == null) { throw new IllegalArgumentException("null set"); } if (set instanceof BimodalMutableIntSet) { BimodalMutableIntSet that = (BimodalMutableIntSet) set; impl.intersectWith(that.impl); } else { Assertions.UNREACHABLE(); } } /** @see com.ibm.wala.util.intset.IntSet#contains(int) */ @Override public boolean contains(int i) { return impl.contains(i); } /** @see com.ibm.wala.util.intset.IntSet#intersection(com.ibm.wala.util.intset.IntSet) */ @NullUnmarked @Nullable @Override public IntSet intersection(IntSet that) throws UnimplementedError { if (that instanceof BimodalMutableIntSet) { BimodalMutableIntSet b = (BimodalMutableIntSet) that; return impl.intersection(b.impl); } else if (that instanceof BitVectorIntSet) { return impl.intersection(that); } else { Assertions.UNREACHABLE("Unexpected: " + that); return null; } } /** @see com.ibm.wala.util.intset.IntSet#union(com.ibm.wala.util.intset.IntSet) */ @Override public IntSet union(IntSet that) { BimodalMutableIntSet temp = new BimodalMutableIntSet(); temp.addAll(this); temp.addAll(that); return temp; } /** @see com.ibm.wala.util.intset.IntSet#isEmpty() */ @Override public boolean isEmpty() { return impl.isEmpty(); } /** @see com.ibm.wala.util.intset.IntSet#size() */ @Override public int size() { return impl.size(); } /** @see IntSet#intIterator() */ @Override public IntIterator intIterator() { return impl.intIterator(); } /** @see com.ibm.wala.util.intset.IntSet#foreach(com.ibm.wala.util.intset.IntSetAction) */ @Override public void foreach(IntSetAction action) { impl.foreach(action); } /** * @see com.ibm.wala.util.intset.IntSet#foreachExcluding(com.ibm.wala.util.intset.IntSet, * com.ibm.wala.util.intset.IntSetAction) */ @Override public void foreachExcluding(IntSet X, IntSetAction action) { impl.foreachExcluding(X, action); } /** @see com.ibm.wala.util.intset.IntSet#max() */ @Override public int max() throws IllegalStateException { return impl.max(); } public static BimodalMutableIntSet makeCopy(IntSet B) throws UnimplementedError, IllegalArgumentException { if (B == null) { throw new IllegalArgumentException("B == null"); } if (B instanceof BimodalMutableIntSet) { BimodalMutableIntSet that = (BimodalMutableIntSet) B; BimodalMutableIntSet result = new BimodalMutableIntSet(); result.impl = IntSetUtil.makeMutableCopy(that.impl); return result; } else if (B instanceof MutableSharedBitVectorIntSet) { BimodalMutableIntSet result = new BimodalMutableIntSet(); MutableSharedBitVectorIntSet s = (MutableSharedBitVectorIntSet) B; result.impl = IntSetUtil.makeMutableCopy(s.makeSparseCopy()); assert result.impl instanceof BitVectorIntSet || result.impl instanceof MutableSparseIntSet; return result; } else { BimodalMutableIntSet result = new BimodalMutableIntSet(); result.impl = IntSetUtil.makeMutableCopy(B); assert result.impl instanceof BitVectorIntSet || result.impl instanceof MutableSparseIntSet; return result; } } public BimodalMutableIntSet() { impl = MutableSparseIntSet.makeEmpty(); } public BimodalMutableIntSet(int initialSize, float expansionFactor) { impl = new TunedMutableSparseIntSet(initialSize, expansionFactor); } @Override public void clear() { impl = MutableSparseIntSet.makeEmpty(); } /** @throws IllegalArgumentException if x is null */ public BimodalMutableIntSet(BimodalMutableIntSet x) { if (x == null) { throw new IllegalArgumentException("x is null"); } impl = IntSetUtil.makeMutableCopy(x.impl); assert impl instanceof BitVectorIntSet || impl instanceof MutableSparseIntSet; } /** @see com.ibm.wala.util.intset.IntSet#sameValue(com.ibm.wala.util.intset.IntSet) */ @Override public boolean sameValue(IntSet that) { return impl.sameValue(that); } /** @see com.ibm.wala.util.intset.IntSet#isSubset(IntSet) */ @Override public boolean isSubset(IntSet that) throws IllegalArgumentException { if (that == null) { throw new IllegalArgumentException("that == null"); } if (that instanceof BimodalMutableIntSet) { BimodalMutableIntSet b = (BimodalMutableIntSet) that; return impl.isSubset(b.impl); } else { // slow! BitVectorIntSet a = new BitVectorIntSet(this); BitVectorIntSet b = new BitVectorIntSet(that); return a.isSubset(b); } } /** use with care */ public IntSet getBackingStore() { return impl; } @Override public String toString() { return impl.toString(); } /** @see com.ibm.wala.util.intset.IntSet#containsAny(com.ibm.wala.util.intset.IntSet) */ @Override public boolean containsAny(IntSet that) throws IllegalArgumentException, UnimplementedError { if (that == null) { throw new IllegalArgumentException("that == null"); } if (that instanceof BimodalMutableIntSet) { BimodalMutableIntSet b = (BimodalMutableIntSet) that; return impl.containsAny(b.impl); } else if (that instanceof SparseIntSet) { return impl.containsAny(that); } else if (that instanceof BitVectorIntSet) { return impl.containsAny(that); } else { Assertions.UNREACHABLE("unsupported " + that.getClass()); return false; } } /** * TODO: optimize ME! * * @throws IllegalArgumentException if that is null */ public boolean removeAll(IntSet that) { if (that == null) { throw new IllegalArgumentException("that is null"); } boolean result = false; for (IntIterator it = that.intIterator(); it.hasNext(); ) { result |= remove(it.next()); } return result; } /** * TODO: optimize ME! * * @throws IllegalArgumentException if that is null */ public boolean containsAll(BimodalMutableIntSet that) { if (that == null) { throw new IllegalArgumentException("that is null"); } for (IntIterator it = that.intIterator(); it.hasNext(); ) { if (!contains(it.next())) { return false; } } return true; } }
10,561
29.614493
100
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/intset/BimodalMutableIntSetFactory.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.intset; import com.ibm.wala.util.debug.UnimplementedError; /** An object that creates some bimodal mutable int sets. */ public class BimodalMutableIntSetFactory implements MutableIntSetFactory<BimodalMutableIntSet> { private final MutableSparseIntSetFactory factory = new MutableSparseIntSetFactory(); @Override public BimodalMutableIntSet make(int[] set) { BimodalMutableIntSet result = new BimodalMutableIntSet(); result.impl = factory.make(set); return result; } @Override public BimodalMutableIntSet parse(String string) throws NumberFormatException { BimodalMutableIntSet result = new BimodalMutableIntSet(); result.impl = factory.parse(string); return result; } @Override public BimodalMutableIntSet makeCopy(IntSet x) throws UnimplementedError, IllegalArgumentException { if (x == null) { throw new IllegalArgumentException("x == null"); } return BimodalMutableIntSet.makeCopy(x); } @Override public BimodalMutableIntSet make() { return new BimodalMutableIntSet(); } }
1,462
29.479167
96
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/intset/BitSet.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.intset; import com.ibm.wala.util.debug.Assertions; import java.util.Iterator; /** A bit set is a set of elements, each of which corresponds to a unique integer from [0,MAX]. */ public final class BitSet<T> { /** The backing bit vector that determines set membership. */ private final BitVector vector; /** The bijection between integer to object. */ private OrdinalSetMapping<T> map; /** * Constructor: create an empty set corresponding to a given mapping * * @throws IllegalArgumentException if map is null */ public BitSet(OrdinalSetMapping<T> map) { if (map == null) { throw new IllegalArgumentException("map is null"); } int length = map.getMaximumIndex(); vector = new BitVector(length); this.map = map; } public static <T> BitSet<T> createBitSet(BitSet<T> B) { if (B == null) { throw new IllegalArgumentException("null B"); } return new BitSet<>(B); } private BitSet(BitSet<T> B) { this(B.map); addAll(B); } /** * Add all elements in bitset B to this bit set * * @throws IllegalArgumentException if B is null */ public void addAll(BitSet<?> B) { if (B == null) { throw new IllegalArgumentException("B is null"); } vector.or(B.vector); } /** Add all bits in BitVector B to this bit set */ public void addAll(BitVector B) { vector.or(B); } /** Add an object to this bit set. */ public void add(T o) { int n = map.getMappedIndex(o); vector.set(n); } /** * Remove an object from this bit set. * * @param o the object to remove */ public void clear(T o) { int n = map.getMappedIndex(o); if (n == -1) { return; } vector.clear(n); } /** Does this set contain a certain object? */ public boolean contains(T o) { int n = map.getMappedIndex(o); if (n == -1) { return false; } return vector.get(n); } /** @return a String representation */ @Override public String toString() { return vector.toString(); } /** * Method copy. Copies the bits in the bit vector, but only assigns the object map. No need to * create a new object/bit bijection object. * * @throws IllegalArgumentException if other is null */ public void copyBits(BitSet<T> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } vector.copyBits(other.vector); map = other.map; } /** * Does this object hold the same bits as other? * * @throws IllegalArgumentException if other is null */ public boolean sameBits(BitSet<?> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } return vector.equals(other.vector); } /** Not very efficient. */ public Iterator<T> iterator() { return new Iterator<>() { private int nextCounter = -1; { for (int i = 0; i < vector.length(); i++) { if (vector.get(i)) { nextCounter = i; break; } } } @Override public boolean hasNext() { return (nextCounter != -1); } @Override public T next() { T result = map.getMappedObject(nextCounter); int start = nextCounter + 1; nextCounter = -1; for (int i = start; i < vector.length(); i++) { if (vector.get(i)) { nextCounter = i; break; } } return result; } @Override public void remove() { Assertions.UNREACHABLE(); } }; } public int size() { return vector.populationCount(); } public int length() { return vector.length(); } /** Set all the bits to 0. */ public void clearAll() { vector.clearAll(); } /** Set all the bits to 1. */ public void setAll() { vector.setAll(); } /** * Perform intersection of two bitsets * * @param other the other bitset in the operation * @throws IllegalArgumentException if other is null */ public void intersect(BitSet<?> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } vector.and(other.vector); } /** * Perform the difference of two bit sets * * @param other the other bitset in the operation * @throws IllegalArgumentException if other is null */ public void difference(BitSet<T> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } vector.and(BitVector.not(other.vector)); } /** */ public boolean isEmpty() { return size() == 0; } }
5,035
22.207373
98
java
WALA
WALA-master/util/src/main/java/com/ibm/wala/util/intset/BitVector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.intset; import java.util.Arrays; /** */ public class BitVector extends BitVectorBase<BitVector> { private static final long serialVersionUID = 9087259335807761617L; private static final int MAX_BITS = Integer.MAX_VALUE / 4; public BitVector() { this(1); } /** * Creates an empty string with the specified size. * * @param nbits the size of the string */ public BitVector(int nbits) { if (nbits > MAX_BITS || nbits < 0) { throw new IllegalArgumentException("invalid nbits: " + nbits); } bits = new int[subscript(nbits) + 1]; } /** Expand this bit vector to size newCapacity. */ void expand(int newCapacity) { bits = Arrays.copyOf(bits, subscript(newCapacity) + 1); } /** * Creates a copy of a Bit String * * @param s the string to copy * @throws IllegalArgumentException if s is null */ public BitVector(BitVector s) { if (s == null) { throw new IllegalArgumentException("s is null"); } bits = new int[s.bits.length]; copyBits(s); } /** * Sets a bit. * * @param bit the bit to be set */ @Override public final void set(int bit) { int shiftBits = bit & LOW_MASK; int subscript = subscript(bit); if (subscript >= bits.length) { expand(bit); } try { bits[subscript] |= (1 << shiftBits); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Clears a bit. * * @param bit the bit to be cleared */ @Override public final void clear(int bit) { if (bit < 0) { throw new IllegalArgumentException("invalid bit: " + bit); } int ss = subscript(bit); if (ss >= bits.length) { return; } int shiftBits = bit & LOW_MASK; bits[ss] &= ~(1 << shiftBits); } /** * Gets a bit. * * @param bit the bit to be gotten */ @Override public final boolean get(int bit) { if (bit < 0) { throw new IllegalArgumentException("illegal bit: " + bit); } int ss = subscript(bit); if (ss >= bits.length) { return false; } int shiftBits = bit & LOW_MASK; return ((bits[ss] & (1 << shiftBits)) != 0); } /** Return the NOT of a bit string */ public static BitVector not(BitVector s) { BitVector b = new BitVector(s); b.not(); return b; } /** * Logically ANDs this bit set with the specified set of bits. * * @param set the bit set to be ANDed with */ @Override public final void and(BitVector set) { if (set == null) { throw new IllegalArgumentException("null set"); } if (this == set) { return; } int n = Math.min(bits.length, set.bits.length); for (int i = n - 1; i >= 0; ) { bits[i] &= set.bits[i]; i--; } for (int i = n; i < bits.length; i++) { bits[i] = 0; } } /** Return a new bit string as the AND of two others. */ public static BitVector and(BitVector b1, BitVector b2) { if (b1 == null) { throw new IllegalArgumentException("null b1"); } if (b2 == null) { throw new IllegalArgumentException("null b2"); } BitVector b = new BitVector(b1); b.and(b2); return b; } /** * Logically ORs this bit set with the specified set of bits. * * @param set the bit set to be ORed with */ @Override public final void or(BitVector set) { if (set == null) { throw new IllegalArgumentException("null set"); } if (this == set) { // should help alias analysis return; } ensureCapacity(set); int n = Math.min(bits.length, set.bits.length); for (int i = n - 1; i >= 0; ) { bits[i] |= set.bits[i]; i--; } } private void ensureCapacity(BitVector set) { if (set.bits.length > bits.length) { expand(BITS_PER_UNIT * set.bits.length - 1); } } /** * Logically ORs this bit set with the specified set of bits. This is performance-critical, and * so, a little ugly in an attempt to help out the compiler. * * @return the number of bits added to this. * @throws IllegalArgumentException if set is null */ public final int orWithDelta(BitVector set) { if (set == null) { throw new IllegalArgumentException("set is null"); } int delta = 0; ensureCapacity(set); int[] otherBits = set.bits; int n = Math.min(bits.length, otherBits.length); for (int i = n - 1; i >= 0; ) { int v1 = bits[i]; int v2 = otherBits[i]; if (v1 != v2) { delta -= Bits.populationCount(v1); int v3 = v1 | v2; delta += Bits.populationCount(v3); bits[i] = v3; } i--; } return delta; } /** Return a new FixedSizeBitVector as the OR of two others */ public static BitVector or(BitVector b1, BitVector b2) { if (b1 == null) { throw new IllegalArgumentException("null b1"); } if (b2 == null) { throw new IllegalArgumentException("null b2"); } BitVector b = new BitVector(b1); b.or(b2); return b; } /** Return a new FixedSizeBitVector as the XOR of two others */ public static BitVector xor(BitVector b1, BitVector b2) { if (b1 == null) { throw new IllegalArgumentException("null b1"); } if (b2 == null) { throw new IllegalArgumentException("null b2"); } BitVector b = new BitVector(b1); b.xor(b2); return b; } /** * Logically XORs this bit set with the specified set of bits. * * @param set the bit set to be XORed with * @throws IllegalArgumentException if set is null */ @Override public final void xor(BitVector set) { if (set == null) { throw new IllegalArgumentException("set is null"); } ensureCapacity(set); int n = Math.min(bits.length, set.bits.length); for (int i = n - 1; i >= 0; ) { bits[i] ^= set.bits[i]; i--; } } /** * Check if the intersection of the two sets is empty * * @param other the set to check intersection with * @throws IllegalArgumentException if other is null */ @Override public final boolean intersectionEmpty(BitVector other) { if (other == null) { throw new IllegalArgumentException("other is null"); } int n = Math.min(bits.length, other.bits.length); for (int i = n - 1; i >= 0; ) { if ((bits[i] & other.bits[i]) != 0) { return false; } i--; } return true; } /** * Calculates and returns the set's size in bits. The maximum element in the set is the size - 1st * element. */ @Override public final int length() { return bits.length << LOG_BITS_PER_UNIT; } /** * Compares this object against the specified object. * * @param B the object to compare with * @return true if the objects are the same; false otherwise. */ @Override public final boolean sameBits(BitVector B) { if (B == null) { throw new IllegalArgumentException("null B"); } if (this == B) { // should help alias analysis return true; } int n = Math.min(bits.length, B.bits.length); if (bits.length > B.bits.length) { for (int i = n; i < bits.length; i++) { if (bits[i] != 0) return false; } } else if (B.bits.length > bits.length) { for (int i = n; i < B.bits.length; i++) { if (B.bits[i] != 0) return false; } } for (int i = n - 1; i >= 0; ) { if (bits[i] != B.bits[i]) { return false; } i--; } return true; } /** @return true iff this is a subset of other */ @Override public boolean isSubset(BitVector other) { if (other == null) { throw new IllegalArgumentException("null other"); } if (this == other) { // should help alias analysis return true; } for (int i = 0; i < bits.length; i++) { if (i >= other.bits.length) { if (bits[i] != 0) { return false; } } else { if ((bits[i] & ~other.bits[i]) != 0) { return false; } } } return true; } @Override public void andNot(BitVector vector) { if (vector == null) { throw new IllegalArgumentException("null vector"); } int ai = 0; int bi = 0; for (ai = 0, bi = 0; ai < bits.length && bi < vector.bits.length; ai++, bi++) { bits[ai] &= ~vector.bits[bi]; } } /** * Compares this object against the specified object. * * @param obj the object to compare with * @return true if the objects are the same; false otherwise. */ @Override public boolean equals(Object obj) { if ((obj != null) && (obj instanceof BitVector)) { if (this == obj) { // should help alias analysis return true; } BitVector set = (BitVector) obj; return sameBits(set); } return false; } /** Sets all bits. */ public final void setAll() { Arrays.fill(bits, MASK); } /** Logically NOT this bit string */ public final void not() { for (int i = 0; i < bits.length; i++) { bits[i] ^= MASK; } } /** Return a new bit string as the AND of two others. */ public static BitVector andNot(BitVector b1, BitVector b2) { BitVector b = new BitVector(b1); b.andNot(b2); return b; } }
9,693
23.604061
100
java