1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.millscript.millscript.datatypes;
22
23 import org.millscript.commons.util.map.EHashMap;
24 import org.millscript.millscript.alert.Alerts;
25 import org.millscript.millscript.functions.SlotFunction;
26
27 /**
28 * This class represents an instance of a Spice class.
29 */
30 public final class SpiceObject {
31
32 /**
33 * This objects class.
34 */
35 private final SpiceClass spiceClass;
36
37 /**
38 * A HashMap where we will store slots and their values.
39 */
40 private final EHashMap< SlotFunction, Object > slots = new EHashMap< SlotFunction, Object >();
41
42 /**
43 * Constructs a new Spice object instance, for the specified class.
44 *
45 * @param sc the class this object is an instance of
46 */
47 public SpiceObject( final SpiceClass sc ) {
48 this.spiceClass = sc;
49 }
50
51 /**
52 * Returns the value of the specified slot.
53 *
54 * @param sf the slot accessor function for the required slot
55 * @return the value of the specified slot
56 */
57 public Object getSlotValue( final SlotFunction sf ) {
58
59
60
61 if ( slots.containsKey( sf ) ) {
62
63 return slots.get( sf );
64 } else {
65
66 throw(
67 Alerts.eval(
68 "Slot doesn't exist in Object",
69 "You can only access defined slots"
70 ).culprit( "slot", sf.getName() ).culprit( "object", this ).mishap()
71 );
72 }
73 }
74
75 /**
76 * Returns the SpiceClass this object is an instance of.
77 *
78 * @return the SpiceClass this object is an instance of
79 */
80 public SpiceClass getSpiceClass() {
81 return spiceClass;
82 }
83
84 /**
85 * Initialises the specified slot with the specified value.
86 *
87 * @param sf the slot to initialise
88 * @param value the value to initialise the slot with
89 */
90 public void initialiseSlotValue( final SlotFunction sf, final Object value ) {
91
92
93
94 if ( slots.containsKey( sf ) ) {
95 throw(
96 Alerts.fault(
97 "Slot has been previously defined"
98 ).culprit( "slot", sf.getName() ).culprit( "object", this ).mishap()
99 );
100 } else {
101 slots.insert( sf, value );
102 }
103 }
104
105 /**
106 * Updates the value of the specified slot with the specified value.
107 *
108 * @param sf the slot to update
109 * @param value the new value for the specified slot
110 */
111 public void updateSlotValue( final SlotFunction sf, final Object value ) {
112
113
114
115 if ( slots.containsKey( sf ) ) {
116
117 slots.update( sf, value );
118 } else {
119
120 throw(
121 Alerts.eval(
122 "Slot doesn't exist in Object",
123 "You can only update defined slots"
124 ).culprit( "slot", sf.getName() ).culprit( "object", this ).mishap()
125 );
126 }
127 }
128
129 /**
130 * Returns a string describing this Spice object.
131 *
132 * @return a String describing this Spice object
133 */
134 @Override
135 public String toString() {
136 return "<object " + this.spiceClass.getName() + ">";
137 }
138
139 }