Added forceValues(...) method to Wire
[Mograsim.git] / net.mograsim.logic.core / src / net / mograsim / logic / core / wires / Wire.java
1 package net.mograsim.logic.core.wires;
2
3 import static net.mograsim.logic.core.types.Bit.U;
4 import static net.mograsim.logic.core.types.Bit.Z;
5
6 import java.util.ArrayList;
7 import java.util.List;
8
9 import net.mograsim.logic.core.LogicObservable;
10 import net.mograsim.logic.core.LogicObserver;
11 import net.mograsim.logic.core.timeline.Timeline;
12 import net.mograsim.logic.core.types.Bit;
13 import net.mograsim.logic.core.types.BitVector;
14 import net.mograsim.logic.core.types.BitVector.BitVectorMutator;
15
16 /**
17  * Represents an array of wires that can store n bits of information.
18  * 
19  * @author Fabian Stemmler
20  *
21  */
22 public class Wire
23 {
24         public final String name;
25         private BitVector values;
26         public final int travelTime;
27         private List<ReadEnd> attached = new ArrayList<>();
28         public final int length;
29         List<ReadWriteEnd> inputs = new ArrayList<>();
30         Timeline timeline;
31
32         public Wire(Timeline timeline, int length, int travelTime)
33         {
34                 this(timeline, length, travelTime, null);
35         }
36
37         public Wire(Timeline timeline, int length, int travelTime, String name)
38         {
39                 if (length < 1)
40                         throw new IllegalArgumentException(
41                                         String.format("Tried to create an array of wires with length %d, but a length of less than 1 makes no sense.", length));
42                 this.name = name;
43                 this.timeline = timeline;
44                 this.length = length;
45                 this.travelTime = travelTime;
46                 initValues();
47         }
48
49         private void initValues()
50         {
51                 values = U.toVector(length);
52         }
53
54         private void setNewValues(BitVector newValues)
55         {
56                 if (values.equals(newValues))
57                         return;
58 //              BitVector oldValues = values;
59                 values = newValues;
60                 notifyObservers();
61         }
62
63         void recalculate()
64         {
65                 if (inputs.size() == 0)
66                         setNewValues(BitVector.of(Bit.U, length));
67                 else
68                 {
69                         BitVectorMutator mutator = BitVectorMutator.empty();
70                         for (ReadWriteEnd wireArrayEnd : inputs)
71                                 mutator.join(wireArrayEnd.getInputValues());
72                         setNewValues(mutator.toBitVector());
73                 }
74         }
75
76         /**
77          * 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.
78          * WARNING! Use this with care! The preferred way of writing the values is ReadWriteEnd.feedSignals(BitVector)
79          * 
80          * @param values The values the <code>Wire</code> will have immediately after this method is called
81          */
82         public void forceValues(BitVector values)
83         {
84                 setNewValues(values);
85         }
86
87         /**
88          * The {@link Wire} is interpreted as an unsigned integer with n bits.
89          * 
90          * @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
91          *         value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
92          * 
93          * @author Fabian Stemmler
94          */
95         public boolean hasNumericValue()
96         {
97                 for (Bit b : values)
98                 {
99                         if (b != Bit.ZERO && b != Bit.ONE)
100                                 return false;
101                 }
102                 return true;
103         }
104
105         /**
106          * The {@link Wire} is interpreted as an unsigned integer with n bits.
107          * 
108          * @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.
109          * 
110          * @author Fabian Stemmler
111          */
112         public long getUnsignedValue()
113         {
114                 long val = 0;
115                 long mask = 1;
116                 for (Bit bit : values)
117                 {
118                         switch (bit)
119                         {
120                         default:
121                         case Z:
122                         case X:
123                                 return 0; // TODO: Proper handling for getUnsignedValue(), if not all bits are 1 or 0;
124                         case ONE:
125                                 val |= mask;
126                                 break;
127                         case ZERO:
128                         }
129                         mask = mask << 1;
130                 }
131                 return val;
132         }
133
134         /**
135          * The {@link Wire} is interpreted as a signed integer with n bits.
136          * 
137          * @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.
138          * 
139          * @author Fabian Stemmler
140          */
141         public long getSignedValue()
142         {
143                 long val = getUnsignedValue();
144                 long mask = 1 << (length - 1);
145                 if ((mask & val) != 0)
146                 {
147                         int shifts = 64 - length;
148                         return (val << shifts) >> shifts;
149                 }
150                 return val;
151         }
152
153         public Bit getValue()
154         {
155                 return getValue(0);
156         }
157
158         public Bit getValue(int index)
159         {
160                 return values.getBit(index);
161         }
162
163         public BitVector getValues(int start, int end)
164         {
165                 return values.subVector(start, end);
166         }
167
168         public BitVector getValues()
169         {
170                 return values;
171         }
172
173         /**
174          * Adds an {@link LogicObserver}, who will be notified when the value of the {@link Wire} is updated.
175          * 
176          * @param ob The {@link LogicObserver} to be notified of changes.
177          * @return true if the given {@link LogicObserver} was not already registered, false otherwise
178          * 
179          * @author Fabian Stemmler
180          */
181         void attachEnd(ReadEnd end)
182         {
183                 attached.add(end);
184         }
185
186         void detachEnd(ReadEnd end)
187         {
188                 attached.remove(end);
189         }
190
191         private void notifyObservers()
192         {
193                 attached.forEach(r -> r.update());
194         }
195
196         /**
197          * Create and register a {@link ReadWriteEnd} object, which is tied to this {@link Wire}. This {@link ReadWriteEnd} can be written to.
198          */
199         public ReadWriteEnd createReadWriteEnd()
200         {
201                 return new ReadWriteEnd();
202         }
203
204         /**
205          * Create a {@link ReadEnd} object, which is tied to this {@link Wire}. This {@link ReadEnd} cannot be written to.
206          */
207         public ReadEnd createReadOnlyEnd()
208         {
209                 return new ReadEnd();
210         }
211
212         void registerInput(ReadWriteEnd toRegister)
213         {
214                 inputs.add(toRegister);
215         }
216
217         /**
218          * A {@link ReadEnd} feeds a constant signal into the {@link Wire} it is tied to. The combination of all inputs determines the
219          * {@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
220          * and 1 turn into X when they are mixed
221          * 
222          * @author Fabian Stemmler
223          */
224         public class ReadEnd implements LogicObservable
225         {
226                 private List<LogicObserver> observers = new ArrayList<>();
227
228                 ReadEnd()
229                 {
230                         super();
231                         Wire.this.attachEnd(this);
232                 }
233
234                 public void update()
235                 {
236                         notifyObservers();
237                 }
238
239                 /**
240                  * Included for convenient use on {@link Wire}s of length 1.
241                  * 
242                  * @return The value of bit 0.
243                  * 
244                  * @author Fabian Stemmler
245                  */
246                 public Bit getValue()
247                 {
248                         return Wire.this.getValue();
249                 }
250
251                 /**
252                  * @param index Index of the requested bit.
253                  * @return The value of the indexed bit.
254                  * 
255                  * @author Fabian Stemmler
256                  */
257                 public Bit getValue(int index)
258                 {
259                         return Wire.this.getValue(index);
260                 }
261
262                 /**
263                  * @param index Index of the requested bit.
264                  * @return The value of the indexed bit.
265                  * 
266                  * @author Fabian Stemmler
267                  */
268                 public BitVector getValues()
269                 {
270                         return Wire.this.getValues();
271                 }
272
273                 /**
274                  * @param start Start of the wanted segment. (inclusive)
275                  * @param end   End of the wanted segment. (exclusive)
276                  * @return The values of the segment of {@link Bit}s indexed.
277                  * 
278                  * @author Fabian Stemmler
279                  */
280                 public BitVector getValues(int start, int end)
281                 {
282                         return Wire.this.getValues(start, end);
283                 }
284
285                 /**
286                  * The {@link Wire} is interpreted as an unsigned integer with n bits.
287                  * 
288                  * @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
289                  *         same value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
290                  * 
291                  * @author Fabian Stemmler
292                  */
293                 public boolean hasNumericValue()
294                 {
295                         return Wire.this.hasNumericValue();
296                 }
297
298                 /**
299                  * The {@link Wire} is interpreted as an unsigned integer with n bits.
300                  * 
301                  * @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.
302                  * 
303                  * @author Fabian Stemmler
304                  */
305                 public long getUnsignedValue()
306                 {
307                         return Wire.this.getUnsignedValue();
308                 }
309
310                 /**
311                  * The {@link Wire} is interpreted as a signed integer with n bits.
312                  * 
313                  * @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.
314                  * 
315                  * @author Fabian Stemmler
316                  */
317                 public long getSignedValue()
318                 {
319                         return Wire.this.getSignedValue();
320                 }
321
322                 @Override
323                 public String toString()
324                 {
325                         return Wire.this.toString();
326                 }
327
328                 public void close()
329                 {
330                         inputs.remove(this);
331                         detachEnd(this);
332                         recalculate();
333                 }
334
335                 public int length()
336                 {
337                         return length;
338                 }
339
340                 public Wire getWire()
341                 {
342                         return Wire.this;
343                 }
344
345                 @Override
346                 public void registerObserver(LogicObserver ob)
347                 {
348                         observers.add(ob);
349                 }
350
351                 @Override
352                 public void deregisterObserver(LogicObserver ob)
353                 {
354                         observers.remove(ob);
355                 }
356
357                 @Override
358                 public void notifyObservers()
359                 {
360                         observers.forEach(ob -> ob.update(this));
361                 }
362         }
363
364         public class ReadWriteEnd extends ReadEnd
365         {
366                 private boolean open, isWriting;
367                 private BitVector inputValues;
368
369                 ReadWriteEnd()
370                 {
371                         super();
372                         open = true;
373                         isWriting = true;
374                         initValues();
375                         registerInput(this);
376                 }
377
378                 private void initValues()
379                 {
380                         inputValues = U.toVector(length);
381                 }
382
383                 /**
384                  * Sets the wires values. This takes up time, as specified by the {@link Wire}s travel time.
385                  * 
386                  * @param newValues The new values the wires should take on.
387                  * 
388                  * @author Fabian Stemmler
389                  */
390                 public void feedSignals(Bit... newValues)
391                 {
392                         feedSignals(BitVector.of(newValues));
393                 }
394
395                 public void feedSignals(BitVector newValues)
396                 {
397                         if (newValues.length() != length)
398                                 throw new IllegalArgumentException(
399                                                 String.format("Attempted to input %d bits instead of %d bits.", newValues.length(), length));
400                         if (!open)
401                                 throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
402                         timeline.addEvent(e -> setValues(newValues), travelTime);
403                 }
404
405                 /**
406                  * Sets values of a subarray of wires. This takes up time, as specified by the {@link Wire}s travel time.
407                  * 
408                  * @param bitVector   The new values the wires should take on.
409                  * @param startingBit The first index of the subarray of wires.
410                  * 
411                  * @author Fabian Stemmler
412                  */
413                 public void feedSignals(int startingBit, BitVector bitVector)
414                 {
415                         if (!open)
416                                 throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
417                         timeline.addEvent(e -> setValues(startingBit, bitVector), travelTime);
418                 }
419
420                 /**
421                  * Sets the values that are being fed into the {@link Wire}. The preferred way of setting {@link ReadWriteEnd} values is via
422                  * feedValues(...) with a delay.
423                  */
424                 void setValues(int startingBit, BitVector newValues)
425                 {
426                         // index check covered in equals
427                         if (!inputValues.equalsWithOffset(newValues, startingBit))
428                         {
429                                 Bit[] vals = inputValues.getBits();
430                                 System.arraycopy(newValues.getBits(), 0, vals, startingBit, newValues.length());
431                                 inputValues = BitVector.of(vals);
432                                 Wire.this.recalculate();
433                         }
434                 }
435
436                 /**
437                  * Sets the values that are being fed into the {@link Wire}. The preferred way of setting {@link ReadWriteEnd} values is via
438                  * feedValues(...) with a delay.
439                  */
440                 void setValues(BitVector newValues)
441                 {
442                         if (inputValues.equals(newValues))
443                                 return;
444                         inputValues = newValues;
445                         Wire.this.recalculate();
446                 }
447
448                 /**
449                  * @return The value (of bit 0) the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
450                  */
451                 public Bit getInputValue()
452                 {
453                         return getInputValue(0);
454                 }
455
456                 /**
457                  * @return The value which the {@link ReadEnd} is currently feeding into the associated {@link Wire} at the indexed {@link Bit}.
458                  */
459                 public Bit getInputValue(int index)
460                 {
461                         return inputValues.getBit(index);
462                 }
463
464                 /**
465                  * @return A copy (safe to modify) of the values the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
466                  */
467                 public BitVector getInputValues()
468                 {
469                         return getInputValues(0, length);
470                 }
471
472                 public BitVector getInputValues(int start, int end)
473                 {
474                         return inputValues.subVector(start, end);
475                 }
476
477                 /**
478                  * {@link ReadEnd} now feeds Z into the associated {@link Wire}.
479                  */
480                 public void clearSignals()
481                 {
482                         feedSignals(Z.toVector(length));
483                 }
484
485                 public BitVector wireValuesExcludingMe()
486                 {
487                         BitVectorMutator mutator = BitVectorMutator.empty();
488                         for (ReadWriteEnd wireEnd : inputs)
489                         {
490                                 if (wireEnd == this)
491                                         continue;
492                                 mutator.join(wireEnd.inputValues);
493                         }
494                         return mutator.toBitVector();
495                 }
496
497                 @Override
498                 public String toString()
499                 {
500                         return inputValues.toString();
501                 }
502
503                 @Override
504                 public void close()
505                 {
506                         super.close();
507                         open = false;
508                 }
509
510                 void setWriting(boolean isWriting)
511                 {
512                         if (this.isWriting != isWriting)
513                         {
514                                 this.isWriting = isWriting;
515                                 if (isWriting)
516                                         inputs.add(this);
517                                 else
518                                         inputs.remove(this);
519                                 Wire.this.recalculate();
520                         }
521                 }
522
523                 boolean isWriting()
524                 {
525                         return isWriting;
526                 }
527         }
528
529         @Override
530         public String toString()
531         {
532                 String name = this.name == null ? String.format("0x%08x", hashCode()) : this.name;
533                 return String.format("wire %s value: %s inputs: %s", name, values, inputs);
534         }
535
536         public static ReadEnd[] extractEnds(Wire[] w)
537         {
538                 ReadEnd[] inputs = new ReadEnd[w.length];
539                 for (int i = 0; i < w.length; i++)
540                         inputs[i] = w[i].createReadWriteEnd();
541                 return inputs;
542         }
543
544         // TODO Fix ReadWriteEnd feeding signals to entire Wire (Z) instead of only selected Bits
545         /**
546          * Fuses the selected bits of two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning:
547          * The bits are permanently fused together.
548          * 
549          * @param a      The {@link Wire} to be (partially) fused with b
550          * @param b      The {@link Wire} to be (partially) fused with a
551          * @param fromA  The first bit of {@link Wire} a to be fused
552          * @param fromB  The first bit of {@link Wire} b to be fused
553          * @param length The amount of bits to fuse
554          */
555         public static void fuse(Wire a, Wire b, int fromA, int fromB, int length)
556         {
557                 ReadWriteEnd rA = a.createReadWriteEnd(), rB = b.createReadWriteEnd();
558                 rA.setWriting(false);
559                 rB.setWriting(false);
560                 rA.setValues(BitVector.of(Bit.Z, a.length));
561                 rB.setValues(BitVector.of(Bit.Z, b.length));
562                 Fusion aF = new Fusion(rB, fromA, fromB, length), bF = new Fusion(rA, fromB, fromA, length);
563                 rA.registerObserver(aF);
564                 rB.registerObserver(bF);
565                 aF.update(rA);
566                 bF.update(rB);
567         }
568
569         /**
570          * 
571          * Fuses two wires together. If the bits change in one Wire, the other is changed accordingly immediately. Warning: The bits are
572          * permanently fused together.
573          * 
574          * @param a The {@link Wire} to be fused with b
575          * @param b The {@link Wire} to be fused with a
576          */
577         public static void fuse(Wire a, Wire b)
578         {
579                 fuse(a, b, 0, 0, a.length);
580         }
581
582         private static class Fusion implements LogicObserver
583         {
584                 private ReadWriteEnd target;
585                 int fromSource, fromTarget, length;
586
587                 public Fusion(ReadWriteEnd target, int fromSource, int fromTarget, int length)
588                 {
589                         this.target = target;
590                         this.fromSource = fromSource;
591                         this.fromTarget = fromTarget;
592                         this.length = length;
593                 }
594
595                 @Override
596                 public void update(LogicObservable initiator)
597                 {
598                         ReadWriteEnd source = (ReadWriteEnd) initiator;
599                         if (source.getWire().inputs.size() - (source.isWriting() ? 1 : 0) == 0)
600                                 target.setWriting(false);
601                         else
602                         {
603                                 target.setWriting(true);
604                                 BitVector targetInput = source.wireValuesExcludingMe().subVector(fromSource, fromSource + length);
605                                 target.setValues(fromTarget, targetInput);
606                         }
607                 }
608         }
609 }