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