35addff359d8b726dd5e5e62176a4c17d8e5fe3e
[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                 for (ReadEnd o : attached)
190                         o.update();
191         }
192
193         /**
194          * Create and register a {@link ReadWriteEnd} object, which is tied to this {@link Wire}. This {@link ReadWriteEnd} can be written to.
195          */
196         public ReadWriteEnd createReadWriteEnd()
197         {
198                 return new ReadWriteEnd();
199         }
200
201         /**
202          * Create a {@link ReadEnd} object, which is tied to this {@link Wire}. This {@link ReadEnd} cannot be written to.
203          */
204         public ReadEnd createReadOnlyEnd()
205         {
206                 return new ReadEnd();
207         }
208
209         void registerInput(ReadWriteEnd toRegister)
210         {
211                 inputs.add(toRegister);
212         }
213
214         /**
215          * A {@link ReadEnd} feeds a constant signal into the {@link Wire} it is tied to. The combination of all inputs determines the
216          * {@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
217          * and 1 turn into X when they are mixed
218          * 
219          * @author Fabian Stemmler
220          */
221         public class ReadEnd implements LogicObservable
222         {
223                 private List<LogicObserver> observers = new ArrayList<>();
224
225                 ReadEnd()
226                 {
227                         super();
228                         Wire.this.attachEnd(this);
229                 }
230
231                 public void update()
232                 {
233                         notifyObservers();
234                 }
235
236                 /**
237                  * Included for convenient use on {@link Wire}s of length 1.
238                  * 
239                  * @return The value of bit 0.
240                  * 
241                  * @author Fabian Stemmler
242                  */
243                 public Bit getValue()
244                 {
245                         return Wire.this.getValue();
246                 }
247
248                 /**
249                  * @param index Index of the requested bit.
250                  * @return The value of the indexed bit.
251                  * 
252                  * @author Fabian Stemmler
253                  */
254                 public Bit getValue(int index)
255                 {
256                         return Wire.this.getValue(index);
257                 }
258
259                 /**
260                  * @param index Index of the requested bit.
261                  * @return The value of the indexed bit.
262                  * 
263                  * @author Fabian Stemmler
264                  */
265                 public BitVector getValues()
266                 {
267                         return Wire.this.getValues();
268                 }
269
270                 /**
271                  * @param start Start of the wanted segment. (inclusive)
272                  * @param end   End of the wanted segment. (exclusive)
273                  * @return The values of the segment of {@link Bit}s indexed.
274                  * 
275                  * @author Fabian Stemmler
276                  */
277                 public BitVector getValues(int start, int end)
278                 {
279                         return Wire.this.getValues(start, end);
280                 }
281
282                 /**
283                  * The {@link Wire} is interpreted as an unsigned integer with n bits.
284                  * 
285                  * @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
286                  *         same value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
287                  * 
288                  * @author Fabian Stemmler
289                  */
290                 public boolean hasNumericValue()
291                 {
292                         return Wire.this.hasNumericValue();
293                 }
294
295                 /**
296                  * The {@link Wire} is interpreted as an unsigned integer with n bits.
297                  * 
298                  * @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.
299                  * 
300                  * @author Fabian Stemmler
301                  */
302                 public long getUnsignedValue()
303                 {
304                         return Wire.this.getUnsignedValue();
305                 }
306
307                 /**
308                  * The {@link Wire} is interpreted as a signed integer with n bits.
309                  * 
310                  * @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.
311                  * 
312                  * @author Fabian Stemmler
313                  */
314                 public long getSignedValue()
315                 {
316                         return Wire.this.getSignedValue();
317                 }
318
319                 @Override
320                 public String toString()
321                 {
322                         return Wire.this.toString();
323                 }
324
325                 public void close()
326                 {
327                         inputs.remove(this);
328                         detachEnd(this);
329                         recalculate();
330                 }
331
332                 public int length()
333                 {
334                         return length;
335                 }
336
337                 public Wire getWire()
338                 {
339                         return Wire.this;
340                 }
341
342                 @Override
343                 public void registerObserver(LogicObserver ob)
344                 {
345                         observers.add(ob);
346                 }
347
348                 @Override
349                 public void deregisterObserver(LogicObserver ob)
350                 {
351                         observers.remove(ob);
352                 }
353
354                 @Override
355                 public void notifyObservers()
356                 {
357                         for (LogicObserver ob : observers)
358                                 ob.update(this);
359                 }
360         }
361
362         public class ReadWriteEnd extends ReadEnd
363         {
364                 private boolean open;
365                 private BitVector inputValues;
366
367                 ReadWriteEnd()
368                 {
369                         super();
370                         open = true;
371                         initValues();
372                         registerInput(this);
373                 }
374
375                 private void initValues()
376                 {
377                         inputValues = U.toVector(length);
378                 }
379
380                 /**
381                  * Sets the wires values. This takes up time, as specified by the {@link Wire}s travel time.
382                  * 
383                  * @param newValues The new values the wires should take on.
384                  * 
385                  * @author Fabian Stemmler
386                  */
387                 public void feedSignals(Bit... newValues)
388                 {
389                         feedSignals(BitVector.of(newValues));
390                 }
391
392                 public void feedSignals(BitVector newValues)
393                 {
394                         if (newValues.length() != length)
395                                 throw new IllegalArgumentException(
396                                                 String.format("Attempted to input %d bits instead of %d bits.", newValues.length(), length));
397                         if (!open)
398                                 throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
399                         timeline.addEvent(e -> setValues(newValues), travelTime);
400                 }
401
402                 /**
403                  * Sets values of a subarray of wires. This takes up time, as specified by the {@link Wire}s travel time.
404                  * 
405                  * @param bitVector   The new values the wires should take on.
406                  * @param startingBit The first index of the subarray of wires.
407                  * 
408                  * @author Fabian Stemmler
409                  */
410                 public void feedSignals(int startingBit, BitVector bitVector)
411                 {
412                         if (!open)
413                                 throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
414                         timeline.addEvent(e -> setValues(startingBit, bitVector), travelTime);
415                 }
416
417                 private void setValues(int startingBit, BitVector newValues)
418                 {
419                         // index check covered in equals
420                         if (!inputValues.equalsWithOffset(newValues, startingBit))
421                         {
422                                 Bit[] vals = inputValues.getBits();
423                                 System.arraycopy(newValues.getBits(), 0, vals, startingBit, newValues.length());
424                                 inputValues = BitVector.of(vals);
425                                 Wire.this.recalculate();
426                         }
427                 }
428
429                 private void setValues(BitVector newValues)
430                 {
431                         if (inputValues.equals(newValues))
432                                 return;
433                         inputValues = newValues;
434                         Wire.this.recalculate();
435                 }
436
437                 /**
438                  * @return The value (of bit 0) the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
439                  */
440                 public Bit getInputValue()
441                 {
442                         return getInputValue(0);
443                 }
444
445                 /**
446                  * @return The value which the {@link ReadEnd} is currently feeding into the associated {@link Wire} at the indexed {@link Bit}.
447                  */
448                 public Bit getInputValue(int index)
449                 {
450                         return inputValues.getBit(index);
451                 }
452
453                 /**
454                  * @return A copy (safe to modify) of the values the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
455                  */
456                 public BitVector getInputValues()
457                 {
458                         return getInputValues(0, length);
459                 }
460
461                 public BitVector getInputValues(int start, int end)
462                 {
463                         return inputValues.subVector(start, end);
464                 }
465
466                 /**
467                  * {@link ReadEnd} now feeds Z into the associated {@link Wire}.
468                  */
469                 public void clearSignals()
470                 {
471                         feedSignals(Z.toVector(length));
472                 }
473
474                 public BitVector wireValuesExcludingMe()
475                 {
476                         BitVectorMutator mutator = BitVectorMutator.empty();
477                         for (ReadWriteEnd wireEnd : inputs)
478                         {
479                                 if (wireEnd == this)
480                                         continue;
481                                 mutator.join(wireEnd.inputValues);
482                         }
483                         return mutator.get();
484                 }
485
486                 @Override
487                 public String toString()
488                 {
489                         return inputValues.toString();
490                 }
491         }
492
493         @Override
494         public String toString()
495         {
496                 return String.format("wire 0x%08x value: %s inputs: %s", hashCode(), values, inputs);
497         }
498
499         public static ReadEnd[] extractEnds(Wire[] w)
500         {
501                 ReadEnd[] inputs = new ReadEnd[w.length];
502                 for (int i = 0; i < w.length; i++)
503                         inputs[i] = w[i].createReadWriteEnd();
504                 return inputs;
505         }
506 }