b26111f53ad558975bd26d26a4b224dda44e22e7
[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         private BitVector values;
25         public final int travelTime;
26         private List<ReadEnd> attached = new ArrayList<>();
27         public final int length;
28         List<ReadWriteEnd> inputs = new ArrayList<>();
29         Timeline timeline;
30
31         public Wire(Timeline timeline, int length, int travelTime)
32         {
33                 if (length < 1)
34                         throw new IllegalArgumentException(
35                                         String.format("Tried to create an array of wires with length %d, but a length of less than 1 makes no sense.", length));
36                 this.timeline = timeline;
37                 this.length = length;
38                 this.travelTime = travelTime;
39                 initValues();
40         }
41
42         private void initValues()
43         {
44                 values = U.toVector(length);
45         }
46
47         private void recalculateSingleInput()
48         {
49                 setNewValues(inputs.get(0).getInputValues());
50         }
51
52         private void recalculateMultipleInputs()
53         {
54                 BitVectorMutator mutator = BitVectorMutator.empty();
55                 for (ReadWriteEnd wireArrayEnd : inputs)
56                         mutator.join(wireArrayEnd.getInputValues());
57                 setNewValues(mutator.get());
58         }
59
60         private void setNewValues(BitVector newValues)
61         {
62                 if (values.equals(newValues))
63                         return;
64 //              BitVector oldValues = values;
65                 values = newValues;
66                 notifyObservers();
67         }
68
69         void recalculate()
70         {
71                 switch (inputs.size())
72                 {
73                 case 0:
74                         return;
75                 case 1:
76                         recalculateSingleInput();
77                         break;
78                 default:
79                         recalculateMultipleInputs();
80                 }
81         }
82
83         /**
84          * The {@link Wire} is interpreted as an unsigned integer with n bits.
85          * 
86          * @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
87          *         value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
88          * 
89          * @author Fabian Stemmler
90          */
91         public boolean hasNumericValue()
92         {
93                 for (Bit b : values)
94                 {
95                         if (b != Bit.ZERO && b != Bit.ONE)
96                                 return false;
97                 }
98                 return true;
99         }
100
101         /**
102          * The {@link Wire} is interpreted as an unsigned integer with n bits.
103          * 
104          * @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.
105          * 
106          * @author Fabian Stemmler
107          */
108         public long getUnsignedValue()
109         {
110                 long val = 0;
111                 long mask = 1;
112                 for (Bit bit : values)
113                 {
114                         switch (bit)
115                         {
116                         default:
117                         case Z:
118                         case X:
119                                 return 0; // TODO: Proper handling for getUnsignedValue(), if not all bits are 1 or 0;
120                         case ONE:
121                                 val |= mask;
122                                 break;
123                         case ZERO:
124                         }
125                         mask = mask << 1;
126                 }
127                 return val;
128         }
129
130         /**
131          * The {@link Wire} is interpreted as a signed integer with n bits.
132          * 
133          * @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.
134          * 
135          * @author Fabian Stemmler
136          */
137         public long getSignedValue()
138         {
139                 long val = getUnsignedValue();
140                 long mask = 1 << (length - 1);
141                 if ((mask & val) != 0)
142                 {
143                         int shifts = 64 - length;
144                         return (val << shifts) >> shifts;
145                 }
146                 return val;
147         }
148
149         public Bit getValue()
150         {
151                 return getValue(0);
152         }
153
154         public Bit getValue(int index)
155         {
156                 return values.getBit(index);
157         }
158
159         public BitVector getValues(int start, int end)
160         {
161                 return values.subVector(start, end);
162         }
163
164         public BitVector getValues()
165         {
166                 return values;
167         }
168
169         /**
170          * Adds an {@link LogicObserver}, who will be notified when the value of the {@link Wire} is updated.
171          * 
172          * @param ob The {@link LogicObserver} to be notified of changes.
173          * @return true if the given {@link LogicObserver} was not already registered, false otherwise
174          * 
175          * @author Fabian Stemmler
176          */
177         void attachEnd(ReadEnd end)
178         {
179                 attached.add(end);
180         }
181
182         void detachEnd(ReadEnd end)
183         {
184                 attached.remove(end);
185         }
186
187         private void notifyObservers()
188         {
189                 attached.forEach(r -> r.update());
190         }
191
192         /**
193          * Create and register a {@link ReadWriteEnd} object, which is tied to this {@link Wire}. This {@link ReadWriteEnd} can be written to.
194          */
195         public ReadWriteEnd createReadWriteEnd()
196         {
197                 return new ReadWriteEnd();
198         }
199
200         /**
201          * Create a {@link ReadEnd} object, which is tied to this {@link Wire}. This {@link ReadEnd} cannot be written to.
202          */
203         public ReadEnd createReadOnlyEnd()
204         {
205                 return new ReadEnd();
206         }
207
208         void registerInput(ReadWriteEnd toRegister)
209         {
210                 inputs.add(toRegister);
211         }
212
213         /**
214          * A {@link ReadEnd} feeds a constant signal into the {@link Wire} it is tied to. The combination of all inputs determines the
215          * {@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
216          * and 1 turn into X when they are mixed
217          * 
218          * @author Fabian Stemmler
219          */
220         public class ReadEnd implements LogicObservable
221         {
222                 private List<LogicObserver> observers = new ArrayList<>();
223
224                 ReadEnd()
225                 {
226                         super();
227                         Wire.this.attachEnd(this);
228                 }
229
230                 public void update()
231                 {
232                         notifyObservers();
233                 }
234
235                 /**
236                  * Included for convenient use on {@link Wire}s of length 1.
237                  * 
238                  * @return The value of bit 0.
239                  * 
240                  * @author Fabian Stemmler
241                  */
242                 public Bit getValue()
243                 {
244                         return Wire.this.getValue();
245                 }
246
247                 /**
248                  * @param index Index of the requested bit.
249                  * @return The value of the indexed bit.
250                  * 
251                  * @author Fabian Stemmler
252                  */
253                 public Bit getValue(int index)
254                 {
255                         return Wire.this.getValue(index);
256                 }
257
258                 /**
259                  * @param index Index of the requested bit.
260                  * @return The value of the indexed bit.
261                  * 
262                  * @author Fabian Stemmler
263                  */
264                 public BitVector getValues()
265                 {
266                         return Wire.this.getValues();
267                 }
268
269                 /**
270                  * @param start Start of the wanted segment. (inclusive)
271                  * @param end   End of the wanted segment. (exclusive)
272                  * @return The values of the segment of {@link Bit}s indexed.
273                  * 
274                  * @author Fabian Stemmler
275                  */
276                 public BitVector getValues(int start, int end)
277                 {
278                         return Wire.this.getValues(start, end);
279                 }
280
281                 /**
282                  * The {@link Wire} is interpreted as an unsigned integer with n bits.
283                  * 
284                  * @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
285                  *         same value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
286                  * 
287                  * @author Fabian Stemmler
288                  */
289                 public boolean hasNumericValue()
290                 {
291                         return Wire.this.hasNumericValue();
292                 }
293
294                 /**
295                  * The {@link Wire} is interpreted as an unsigned integer with n bits.
296                  * 
297                  * @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.
298                  * 
299                  * @author Fabian Stemmler
300                  */
301                 public long getUnsignedValue()
302                 {
303                         return Wire.this.getUnsignedValue();
304                 }
305
306                 /**
307                  * The {@link Wire} is interpreted as a signed integer with n bits.
308                  * 
309                  * @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.
310                  * 
311                  * @author Fabian Stemmler
312                  */
313                 public long getSignedValue()
314                 {
315                         return Wire.this.getSignedValue();
316                 }
317
318                 @Override
319                 public String toString()
320                 {
321                         return Wire.this.toString();
322                 }
323
324                 public void close()
325                 {
326                         inputs.remove(this);
327                         detachEnd(this);
328                         recalculate();
329                 }
330
331                 public int length()
332                 {
333                         return length;
334                 }
335
336                 public Wire getWire()
337                 {
338                         return Wire.this;
339                 }
340
341                 @Override
342                 public void registerObserver(LogicObserver ob)
343                 {
344                         observers.add(ob);
345                 }
346
347                 @Override
348                 public void deregisterObserver(LogicObserver ob)
349                 {
350                         observers.remove(ob);
351                 }
352
353                 @Override
354                 public void notifyObservers()
355                 {
356                         observers.forEach(ob -> ob.update(this));
357                 }
358         }
359
360         public class ReadWriteEnd extends ReadEnd
361         {
362                 private boolean open;
363                 private BitVector inputValues;
364
365                 ReadWriteEnd()
366                 {
367                         super();
368                         open = true;
369                         initValues();
370                         registerInput(this);
371                 }
372
373                 private void initValues()
374                 {
375                         inputValues = U.toVector(length);
376                 }
377
378                 /**
379                  * Sets the wires values. This takes up time, as specified by the {@link Wire}s travel time.
380                  * 
381                  * @param newValues The new values the wires should take on.
382                  * 
383                  * @author Fabian Stemmler
384                  */
385                 public void feedSignals(Bit... newValues)
386                 {
387                         feedSignals(BitVector.of(newValues));
388                 }
389
390                 public void feedSignals(BitVector newValues)
391                 {
392                         if (newValues.length() != length)
393                                 throw new IllegalArgumentException(
394                                                 String.format("Attempted to input %d bits instead of %d bits.", newValues.length(), length));
395                         if (!open)
396                                 throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
397                         timeline.addEvent(e -> setValues(newValues), travelTime);
398                 }
399
400                 /**
401                  * Sets values of a subarray of wires. This takes up time, as specified by the {@link Wire}s travel time.
402                  * 
403                  * @param bitVector   The new values the wires should take on.
404                  * @param startingBit The first index of the subarray of wires.
405                  * 
406                  * @author Fabian Stemmler
407                  */
408                 public void feedSignals(int startingBit, BitVector bitVector)
409                 {
410                         if (!open)
411                                 throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
412                         timeline.addEvent(e -> setValues(startingBit, bitVector), travelTime);
413                 }
414
415                 private void setValues(int startingBit, BitVector newValues)
416                 {
417                         // index check covered in equals
418                         if (!inputValues.equalsWithOffset(newValues, startingBit))
419                         {
420                                 Bit[] vals = inputValues.getBits();
421                                 System.arraycopy(newValues.getBits(), 0, vals, startingBit, newValues.length());
422                                 inputValues = BitVector.of(vals);
423                                 Wire.this.recalculate();
424                         }
425                 }
426
427                 private void setValues(BitVector newValues)
428                 {
429                         if (inputValues.equals(newValues))
430                                 return;
431                         inputValues = newValues;
432                         Wire.this.recalculate();
433                 }
434
435                 /**
436                  * @return The value (of bit 0) the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
437                  */
438                 public Bit getInputValue()
439                 {
440                         return getInputValue(0);
441                 }
442
443                 /**
444                  * @return The value which the {@link ReadEnd} is currently feeding into the associated {@link Wire} at the indexed {@link Bit}.
445                  */
446                 public Bit getInputValue(int index)
447                 {
448                         return inputValues.getBit(index);
449                 }
450
451                 /**
452                  * @return A copy (safe to modify) of the values the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
453                  */
454                 public BitVector getInputValues()
455                 {
456                         return getInputValues(0, length);
457                 }
458
459                 public BitVector getInputValues(int start, int end)
460                 {
461                         return inputValues.subVector(start, end);
462                 }
463
464                 /**
465                  * {@link ReadEnd} now feeds Z into the associated {@link Wire}.
466                  */
467                 public void clearSignals()
468                 {
469                         feedSignals(Z.toVector(length));
470                 }
471
472                 public BitVector wireValuesExcludingMe()
473                 {
474                         BitVectorMutator mutator = BitVectorMutator.empty();
475                         for (ReadWriteEnd wireEnd : inputs)
476                         {
477                                 if (wireEnd == this)
478                                         continue;
479                                 mutator.join(wireEnd.inputValues);
480                         }
481                         return mutator.get();
482                 }
483
484                 @Override
485                 public String toString()
486                 {
487                         return inputValues.toString();
488                 }
489         }
490
491         @Override
492         public String toString()
493         {
494                 return String.format("wire 0x%08x value: %s inputs: %s", hashCode(), values, inputs);
495         }
496
497         public static ReadEnd[] extractEnds(Wire[] w)
498         {
499                 ReadEnd[] inputs = new ReadEnd[w.length];
500                 for (int i = 0; i < w.length; i++)
501                         inputs[i] = w[i].createReadWriteEnd();
502                 return inputs;
503         }
504 }