1 package net.mograsim.logic.core.wires;
3 import static net.mograsim.logic.core.types.Bit.U;
4 import static net.mograsim.logic.core.types.Bit.Z;
6 import java.util.ArrayList;
7 import java.util.Arrays;
10 import net.mograsim.logic.core.LogicObservable;
11 import net.mograsim.logic.core.LogicObserver;
12 import net.mograsim.logic.core.timeline.Timeline;
13 import net.mograsim.logic.core.types.Bit;
14 import net.mograsim.logic.core.types.BitVector;
15 import net.mograsim.logic.core.types.BitVector.BitVectorMutator;
18 * Represents an array of wires that can store n bits of information.
20 * @author Fabian Stemmler
25 public final String name;
26 private BitVector cachedValues;
27 public final int travelTime;
28 private List<ReadEnd> attached = new ArrayList<>();
29 public final int width;
30 List<ReadWriteEnd> inputs = new ArrayList<>();
32 private Bit[] bitsWithoutFusions;
35 public Wire(Timeline timeline, int width, int travelTime)
37 this(timeline, width, travelTime, null);
40 public Wire(Timeline timeline, int width, int travelTime, String name)
43 throw new IllegalArgumentException(
44 String.format("Tried to create an array of wires with width %d, but a width of less than 1 makes no sense.", width));
46 this.timeline = timeline;
48 this.travelTime = travelTime;
52 private void initValues()
54 cachedValues = U.toVector(width);
55 bitsWithoutFusions = cachedValues.getBits();
58 private void setNewValues(BitVector newValues)
60 cachedValues = newValues;
64 private void invalidateCachedValuesForAllFusedWires()
66 invalidateCachedValues();
67 if (fusedBits != null)
68 for (FusedBit fusion : fusedBits)
70 fusion.invalidateCachedValuesForAllParticipatingWires();
73 private void invalidateCachedValues()
79 void recalculateValuesWithoutFusions()
81 Bit[] bits = new Bit[width];
86 System.arraycopy(inputs.get(0).getInputValues().getBits(), 0, bits, 0, width);
87 for (int i = 1; i < inputs.size(); i++)
88 Bit.join(bits, inputs.get(i).getInputValues().getBits());
90 bitsWithoutFusions = bits;
91 if (fusedBits == null)
92 setNewValues(BitVector.of(bits));
94 invalidateCachedValuesForAllFusedWires();
97 private void recalculatedCachedValues()
100 if (fusedBits == null)
101 bits = bitsWithoutFusions;
104 bits = new Bit[width];
105 for (int i = 0; i < width; i++)
107 FusedBit fusion = fusedBits[i];
109 bits[i] = bitsWithoutFusions[i];
111 bits[i] = fusion.getValue();
114 cachedValues = BitVector.of(bits);
118 * Forces a Wire to take on specific values. If the new values differ from the old ones, the observers of the Wire will be notified.
119 * WARNING! Use this with care! The preferred way of writing the values is ReadWriteEnd.feedSignals(BitVector)
121 * @param values The values the <code>Wire</code> will have immediately after this method is called
123 public void forceValues(BitVector values)
125 setNewValues(values);
129 * The {@link Wire} is interpreted as an unsigned integer with n bits.
131 * @return <code>true</code> if all bits are either <code>Bit.ONE</code> or <code>Bit.ZERO</code> (they do not all have to have the same
132 * value), not <code>Bit.U</code>, <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
134 * @author Fabian Stemmler
136 public boolean hasNumericValue()
138 return getValues().isBinary();
142 * The {@link Wire} is interpreted as an unsigned integer with n bits.
144 * @return The unsigned value of the {@link Wire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
146 * @author Fabian Stemmler
148 public long getUnsignedValue()
152 for (Bit bit : getValues())
159 return 0; // TODO: Proper handling for getUnsignedValue(), if not all bits are 1 or 0;
171 * The {@link Wire} is interpreted as a signed integer with n bits.
173 * @return The signed value of the {@link Wire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
175 * @author Fabian Stemmler
177 public long getSignedValue()
179 long val = getUnsignedValue();
180 long mask = 1 << (width - 1);
181 if ((mask & val) != 0)
183 int shifts = 64 - width;
184 return (val << shifts) >> shifts;
190 * Returns the least significant bit (LSB)
192 public Bit getValue()
198 * Returns the least significant bit (LSB) of the given index
200 public Bit getValue(int index)
202 return getValues().getLSBit(index);
205 public BitVector getValues(int start, int end)
207 return getValues().subVector(start, end);
210 public BitVector getValues()
212 if (cachedValues == null)
213 recalculatedCachedValues();
218 * Adds an {@link LogicObserver}, who will be notified when the value of the {@link Wire} is updated.
220 * @param ob The {@link LogicObserver} to be notified of changes.
221 * @return true if the given {@link LogicObserver} was not already registered, false otherwise
223 * @author Fabian Stemmler
225 boolean attachEnd(ReadEnd end)
227 return attached.add(end);
230 void detachEnd(ReadEnd end)
232 attached.remove(end);
235 private void notifyObservers()
237 attached.forEach(ReadEnd::update);
241 * Create and register a {@link ReadWriteEnd} object, which is tied to this {@link Wire}. This {@link ReadWriteEnd} can be written to.
243 public ReadWriteEnd createReadWriteEnd()
245 return new ReadWriteEnd();
249 * Create a {@link ReadEnd} object, which is tied to this {@link Wire}. This {@link ReadEnd} cannot be written to.
251 public ReadEnd createReadOnlyEnd()
253 return new ReadEnd();
256 void registerInput(ReadWriteEnd toRegister)
258 inputs.add(toRegister);
259 recalculateValuesWithoutFusions();
263 * A {@link ReadEnd} feeds a constant signal into the {@link Wire} it is tied to. The combination of all inputs determines the
264 * {@link Wire}s final value. X dominates all other inputs Z does not affect the final value, unless there are no other inputs than Z 0
265 * and 1 turn into X when they are mixed
267 * @author Fabian Stemmler
269 public class ReadEnd implements LogicObservable
271 private List<LogicObserver> observers = new ArrayList<>();
276 Wire.this.attachEnd(this);
285 * Included for convenient use on {@link Wire}s of width 1.
287 * @return The value of bit 0.
289 * @author Fabian Stemmler
291 public Bit getValue()
293 return Wire.this.getValue();
297 * @param index Index of the requested bit.
298 * @return The value of the indexed bit.
300 * @author Fabian Stemmler
302 public Bit getValue(int index)
304 return Wire.this.getValue(index);
307 public BitVector getValues()
309 return Wire.this.getValues();
313 * @param start Start of the wanted segment. (inclusive)
314 * @param end End of the wanted segment. (exclusive)
315 * @return The values of the segment of {@link Bit}s indexed.
317 * @author Fabian Stemmler
319 public BitVector getValues(int start, int end)
321 return Wire.this.getValues(start, end);
325 * The {@link Wire} is interpreted as an unsigned integer with n bits.
327 * @return <code>true</code> if all bits are either <code>Bit.ONE</code> or <code>Bit.ZERO</code> (they do not all have to have the
328 * same value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
330 * @author Fabian Stemmler
332 public boolean hasNumericValue()
334 return Wire.this.hasNumericValue();
338 * The {@link Wire} is interpreted as an unsigned integer with n bits.
340 * @return The unsigned value of the {@link Wire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
342 * @author Fabian Stemmler
344 public long getUnsignedValue()
346 return Wire.this.getUnsignedValue();
350 * The {@link Wire} is interpreted as a signed integer with n bits.
352 * @return The signed value of the {@link Wire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
354 * @author Fabian Stemmler
356 public long getSignedValue()
358 return Wire.this.getSignedValue();
362 public String toString()
364 return Wire.this.toString();
371 recalculateValuesWithoutFusions();
379 public Wire getWire()
385 public void registerObserver(LogicObserver ob)
391 public void deregisterObserver(LogicObserver ob)
393 observers.remove(ob);
396 // void registerCloseObserver(LogicObserver ob)
398 // closeObserver.add(ob);
401 // void deregisterCloseObserver(LogicObserver ob)
403 // closeObserver.remove(ob);
407 public void notifyObservers()
409 observers.forEach(ob -> ob.update(this));
413 public class ReadWriteEnd extends ReadEnd
415 private boolean open;
416 private boolean isWriting;
417 private BitVector inputValues;
428 private void initValues()
430 inputValues = U.toVector(width);
434 * Sets the wires values. This takes up time, as specified by the {@link Wire}s travel time.
436 * @param newValues The new values the wires should take on.
438 * @author Fabian Stemmler
440 public void feedSignals(Bit... newValues)
442 feedSignals(BitVector.of(newValues));
445 public void feedSignals(BitVector newValues)
447 if (newValues.length() != width)
448 throw new IllegalArgumentException(
449 String.format("Attempted to input %d bits instead of %d bits.", newValues.length(), width));
451 throw new IllegalStateException("Attempted to write to closed WireArrayEnd.");
452 timeline.addEvent(e -> setValues(newValues), travelTime);
456 * Sets values of a subarray of wires. This takes up time, as specified by the {@link Wire}s travel time.
458 * @param bitVector The new values the wires should take on.
459 * @param startingBit The first index of the subarray of wires.
461 * @author Fabian Stemmler
463 public void feedSignals(int startingBit, BitVector bitVector)
466 throw new IllegalStateException("Attempted to write to closed WireArrayEnd.");
467 timeline.addEvent(e -> setValues(startingBit, bitVector), travelTime);
471 * Sets the values that are being fed into the {@link Wire}. The preferred way of setting {@link ReadWriteEnd} values is via
472 * feedValues(...) with a delay.
474 void setValues(int startingBit, BitVector newValues)
476 // index check covered in equals
477 if (!inputValues.equalsWithOffset(newValues, startingBit))
479 Bit[] vals = inputValues.getBits();
480 System.arraycopy(newValues.getBits(), 0, vals, startingBit, newValues.length());
481 inputValues = BitVector.of(vals);
482 Wire.this.recalculateValuesWithoutFusions();
487 * Sets the values that are being fed into the {@link Wire}. The preferred way of setting {@link ReadWriteEnd} values is via
488 * feedValues(...) with a delay.
490 void setValues(BitVector newValues)
492 if (inputValues.equals(newValues))
494 inputValues = newValues;
495 Wire.this.recalculateValuesWithoutFusions();
499 * @return The value (of bit 0) the {@link ReadEnd} is currently feeding into the associated {@link Wire}.Returns the least
500 * significant bit (LSB)
502 public Bit getInputValue()
504 return getInputValue(0);
508 * @return The value which the {@link ReadEnd} is currently feeding into the associated {@link Wire} at the indexed {@link Bit}.
509 * Returns the least significant bit (LSB)
512 public Bit getInputValue(int index)
514 return inputValues.getLSBit(index);
518 * @return A copy (safe to modify) of the values the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
520 public BitVector getInputValues()
525 public BitVector getInputValues(int start, int end)
527 return inputValues.subVector(start, end);
531 * {@link ReadEnd} now feeds Z into the associated {@link Wire}.
533 public void clearSignals()
535 feedSignals(Z.toVector(width));
538 public BitVector wireValuesExcludingMe()
540 BitVectorMutator mutator = BitVectorMutator.empty();
541 boolean modified = false;
542 for (ReadWriteEnd wireEnd : inputs)
547 mutator.join(wireEnd.inputValues);
550 mutator.join(BitVector.of(Bit.Z, width));
551 return mutator.toBitVector();
555 public String toString()
557 return inputValues.toString();
567 void setWriting(boolean isWriting)
569 if (this.isWriting != isWriting)
571 this.isWriting = isWriting;
576 Wire.this.recalculateValuesWithoutFusions();
587 public String toString()
589 String name = this.name == null ? String.format("0x%08x", hashCode()) : this.name;
590 return String.format("wire %s value: %s inputs: %s", name, getValues(), inputs);
593 public static ReadEnd[] extractEnds(Wire[] w)
595 ReadEnd[] inputs = new ReadEnd[w.length];
596 for (int i = 0; i < w.length; i++)
597 inputs[i] = w[i].createReadWriteEnd();
603 * Fuses two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning: The bits are
604 * permanently fused together.
606 * @param a The {@link Wire} to be fused with b
607 * @param b The {@link Wire} to be fused with a
609 public static void fuse(Wire a, Wire b)
611 fuse(a, b, 0, 0, a.width);
615 * Fuses the selected bits of two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning:
616 * The bits are permanently fused together.
618 * @param a The {@link Wire} to be (partially) fused with b
619 * @param b The {@link Wire} to be (partially) fused with a
620 * @param fromA The first bit of {@link Wire} a to be fused
621 * @param fromB The first bit of {@link Wire} b to be fused
622 * @param width The amount of bits to fuse
624 public static void fuse(Wire a, Wire b, int fromA, int fromB, int width)
626 // iterate in this direction to be fail-fast (rely on the checks in fuse(Wire, Wire, int, int)
627 for (int i = width - 1; i >= 0; i--)
628 fuse(a, b, fromA + i, fromB + i);
632 * Fuses one bit of two wires together. If this bit changes in one Wire, the other is changed accordingly immediately. Warning: The bits
633 * are permanently fused together.
635 * @param a The {@link Wire} to be (partially) fused with b
636 * @param b The {@link Wire} to be (partially) fused with a
637 * @param bitA The bit of {@link Wire} a to be fused
638 * @param bitB The bit of {@link Wire} b to be fused
640 public static void fuse(Wire a, Wire b, int bitA, int bitB)
643 throw new IllegalArgumentException("No bit " + bitA + " in " + a + " (width " + a.width + ")");
645 throw new IllegalArgumentException("No bit " + bitB + " in " + b + " (width " + b.width + ")");
646 if (a.fusedBits == null)
647 a.fusedBits = new FusedBit[a.width];
648 if (b.fusedBits == null)
649 b.fusedBits = new FusedBit[b.width];
650 FusedBit oldFusionA = a.fusedBits[bitA];
651 FusedBit oldFusionB = b.fusedBits[bitB];
652 if (oldFusionA == null)
653 if (oldFusionB == null)
655 FusedBit fusion = new FusedBit();
656 fusion.addParticipatingWireBit(a, bitA);
657 fusion.addParticipatingWireBit(b, bitB);
659 oldFusionB.addParticipatingWireBit(a, bitA);
660 else if (oldFusionB == null)
661 oldFusionA.addParticipatingWireBit(b, bitB);
663 oldFusionA.mergeOtherIntoThis(oldFusionB);
666 private static class FusedBit
668 private final List<WireBit> participatingWireBits;
672 this.participatingWireBits = new ArrayList<>();
675 public void addParticipatingWireBit(Wire w, int bit)
677 addParticipatingWireBit(new WireBit(w, bit));
680 private void addParticipatingWireBit(WireBit wb)
682 wb.wire.fusedBits[wb.bit] = this;
683 participatingWireBits.add(wb);
684 wb.wire.invalidateCachedValuesForAllFusedWires();
687 public void mergeOtherIntoThis(FusedBit other)
689 for (WireBit wb : other.participatingWireBits)
690 addParticipatingWireBit(wb);
693 public void invalidateCachedValuesForAllParticipatingWires()
695 for (WireBit wb : participatingWireBits)
696 wb.wire.invalidateCachedValues();
699 public Bit getValue()
702 for (WireBit wb : participatingWireBits)
703 if (!wb.wire.inputs.isEmpty())
705 Bit bit = wb.wire.bitsWithoutFusions[wb.bit];
706 result = result == null ? bit : result.join(bit);
708 return result == null ? U : result;
712 private static class WireBit
714 public final Wire wire;
715 public final int bit;
717 public WireBit(Wire wire, int bit)