-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathStructure.cs
More file actions
386 lines (342 loc) · 15.7 KB
/
Copy pathStructure.cs
File metadata and controls
386 lines (342 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using kOS.Safe.Encapsulation.Suffixes;
using kOS.Safe.Exceptions;
using kOS.Safe.Utilities;
using kOS.Safe.Serialization;
namespace kOS.Safe.Encapsulation
{
[KOSNomenclature("Structure")]
public abstract class Structure : ISuffixed
{
private static readonly IDictionary<Type,IDictionary<string, ISuffix>> globalSuffixes;
private readonly IDictionary<string, ISuffix> instanceSuffixes;
private static readonly object globalSuffixLock = new object();
private bool needToInitializeSuffixes = true;
private List<Action> initializeSuffixCallbacks = new List<Action>();
static Structure()
{
globalSuffixes = new Dictionary<Type, IDictionary<string, ISuffix>>();
}
protected Structure()
{
instanceSuffixes = new Dictionary<string, ISuffix>(StringComparer.OrdinalIgnoreCase);
RegisterInitializer(InitializeInstanceSuffixes);
}
protected void RegisterInitializer(Action callback)
{
if (!initializeSuffixCallbacks.Contains(callback))
{
initializeSuffixCallbacks.Add(callback);
}
}
private void callInitializeSuffixes()
{
if (needToInitializeSuffixes)
{
foreach (var callback in initializeSuffixCallbacks)
{
callback.Invoke();
}
needToInitializeSuffixes = false;
}
}
public string KOSName { get { return KOSNomenclature.GetKOSName(GetType()); } }
private void InitializeInstanceSuffixes()
{
// Need to choose what sort of naming scheme to return before
// enabling this one:
// AddSuffix("TYPENAME", new NoArgsSuffix<StringValue>(() => GetType().ToString()));
AddSuffix("TOSTRING", new NoArgsSuffix<StringValue>(() => ToString()));
AddSuffix("HASSUFFIX", new OneArgsSuffix<BooleanValue, StringValue>(HasSuffix));
AddSuffix("SUFFIXNAMES", new NoArgsSuffix<ListValue<StringValue>>(GetSuffixNames));
AddSuffix("ISSERIALIZABLE", new NoArgsSuffix<BooleanValue>(() => this is SerializableStructure));
AddSuffix("TYPENAME", new NoArgsSuffix<StringValue>(() => new StringValue(KOSName)));
AddSuffix("ISTYPE", new OneArgsSuffix<BooleanValue,StringValue>(GetKOSIsType));
AddSuffix("INHERITANCE", new NoArgsSuffix<StringValue>(GetKOSInheritance));
}
protected void AddSuffix(string suffixName, ISuffix suffixToAdd)
{
AddSuffix(new[]{suffixName}, suffixToAdd);
}
protected void AddSuffix(IEnumerable<string> suffixNames, ISuffix suffixToAdd)
{
foreach (var suffixName in suffixNames)
{
if (instanceSuffixes.ContainsKey(suffixName))
{
instanceSuffixes[suffixName] = suffixToAdd;
}
else
{
instanceSuffixes.Add(suffixName, suffixToAdd);
}
}
}
protected static void AddGlobalSuffix<T>(string suffixName, ISuffix suffixToAdd)
{
AddGlobalSuffix<T>(new[]{suffixName}, suffixToAdd);
}
protected static void AddGlobalSuffix<T>(IEnumerable<string> suffixNames, ISuffix suffixToAdd)
{
var type = typeof (T);
var typeSuffixes = GetStaticSuffixesForType(type);
foreach (var suffixName in suffixNames)
{
if (typeSuffixes.ContainsKey(suffixName))
{
typeSuffixes[suffixName] = suffixToAdd;
}
else
{
typeSuffixes.Add(suffixName, suffixToAdd);
}
}
lock (globalSuffixLock)
{
globalSuffixes[type] = typeSuffixes;
}
}
private static IDictionary<string, ISuffix> GetStaticSuffixesForType(Type currentType)
{
lock (globalSuffixLock)
{
IDictionary<string, ISuffix> typeSuffixes;
if (globalSuffixes.TryGetValue(currentType, out typeSuffixes))
{
return typeSuffixes;
}
return new Dictionary<string, ISuffix>(StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// Set a suffix of this structure that has suffixName to the given value.
/// If failOkay is false then it will throw exception if it fails to find the suffix.
/// If failOkay is true then it will continue happily if it fails to find the suffix.
/// </summary>
/// <param name="suffixName"></param>
/// <param name="value"></param>
/// <param name="failOkay"></param>
/// <returns>false if failOkay was true and it failed to find the suffix</returns>
public virtual bool SetSuffix(string suffixName, object value, bool failOkay = false)
{
callInitializeSuffixes();
var suffixes = GetStaticSuffixesForType(GetType());
if (!ProcessSetSuffix(suffixes, suffixName, value, failOkay))
{
return ProcessSetSuffix(instanceSuffixes, suffixName, value, failOkay);
}
return false;
}
private bool ProcessSetSuffix(IDictionary<string, ISuffix> suffixes, string suffixName, object value, bool failOkay = false)
{
ISuffix suffix;
if (suffixes.TryGetValue(suffixName, out suffix))
{
var settable = suffix as ISetSuffix;
if (settable != null)
{
settable.Set(value);
return true;
}
if (failOkay)
return false;
else
throw new KOSSuffixUseException("set", suffixName, this);
}
return false;
}
/// <summary>
/// Get the suffix with this name, or if it fails to find it, then either
/// throw exception or merely return null. (Will return null only if failOkay is true).
/// </summary>
/// <param name="suffixName"></param>
/// <param name="failOkay"></param>
/// <returns></returns>
public virtual ISuffixResult GetSuffix(string suffixName, bool failOkay = false)
{
callInitializeSuffixes();
ISuffix suffix;
if (instanceSuffixes.TryGetValue(suffixName, out suffix))
{
return suffix.Get();
}
var suffixes = GetStaticSuffixesForType(GetType());
if (!suffixes.TryGetValue(suffixName, out suffix))
{
if (failOkay)
return null;
else
throw new KOSSuffixUseException("get",suffixName,this);
}
return suffix.Get();
}
public virtual BooleanValue HasSuffix(StringValue suffixName)
{
callInitializeSuffixes();
if (instanceSuffixes.ContainsKey(suffixName.ToString()))
return true;
if (GetStaticSuffixesForType(GetType()).ContainsKey(suffixName.ToString()))
return true;
return false;
}
public virtual ListValue<StringValue> GetSuffixNames()
{
callInitializeSuffixes();
List<StringValue> names = new List<StringValue>();
names.AddRange(instanceSuffixes.Keys.Select(item => (StringValue)item));
names.AddRange(GetStaticSuffixesForType(GetType()).Keys.Select(item => (StringValue)item));
// Return the list alphabetized by suffix name. The key lookups above, since they're coming
// from a hashed dictionary, won't be in any predictable ordering:
return new ListValue<StringValue>(names.OrderBy(item => item.ToString()));
}
public virtual BooleanValue GetKOSIsType(StringValue queryTypeName)
{
// We can't use Reflection's IsAssignableFrom because of the annoying way Generics work under Reflection.
for (Type t = GetType() ; t != null ; t = t.BaseType)
{
// Our KOSNomenclature mapping can't store a Dictionary mapping for all
// the new generics types that get made on the fly and weren't present when the static constructor was made.
// So instead we ask Reflection to get the base from which it came so we can look that up instead.
if (t.IsGenericType)
t = t.GetGenericTypeDefinition();
if (KOSNomenclature.HasKOSName(t))
{
string kOSname = KOSNomenclature.GetKOSName(t);
if (kOSname == queryTypeName)
return true;
if (t == typeof(Structure))
break; // don't bother walking further up - there won't be any more KOS types above this.
}
}
return false;
}
public virtual StringValue GetKOSInheritance()
{
StringBuilder sb = new StringBuilder();
string prevKosName = "";
for (Type t = GetType() ; t != null ; t = t.BaseType)
{
// Our KOSNomenclature mapping can't store a Dictionary mapping for all
// the new generics types that get made on the fly and weren't present when the static constructor was made.
// So instead we ask Reflection to get the base from which it came so we can look that up instead.
if (t.IsGenericType)
t = t.GetGenericTypeDefinition();
if (KOSNomenclature.HasKOSName(t))
{
string kOSname = KOSNomenclature.GetKOSName(t);
if (kOSname != prevKosName) // skip extra iterations where we mash parent C# types and child C# types into the same KOS type.
{
if (prevKosName != "")
sb.Append(" derived from ");
sb.Append(kOSname);
}
prevKosName = kOSname;
if (t == typeof(Structure))
break; // don't bother walking further up - there won't be any more KOS types above this.
}
}
return sb.ToString();
}
public override string ToString()
{
return KOSNomenclature.GetKOSName(GetType()) + ": \"\""; // print as the KOSNomenclature string name, will look like: Structure: ""
}
/// <summary>
/// Attempt to convert the given object into a kOS encapsulation type (something
/// derived from kOS.Safe.Encapsulation.Structure), returning that instead.
/// This never throws exception or complains in any way if the conversion cannot happen.
/// Insted in that case it just silently ignores the request and returns the original object
/// reference unchanged. Thus it is safe to call it "just in case", even in places where it won't
/// always be necessary, or have an effect at all. You should use in anywhere you need to
/// ensure that a value a user's script might see on the stack or in a script variable is properly
/// wrapped in a kOS Structure, and not just a raw primitive like int or double.
/// </summary>
/// <param name="value">value to convert</param>
/// <returns>new converted value, or original value if conversion couldn't happen or was unnecesary</returns>
public static object FromPrimitive(object value)
{
if (value == null)
return value; // If a null exists, let it pass through so it will bomb elsewhere, not here in FromPrimitive() where the exception message would be obtuse.
if (value is Structure)
return value; // Conversion is unnecessary - it's already a Structure.
var convert = value as IConvertible;
if (convert == null)
return value; // Conversion isn't even theoretically possible.
TypeCode code = convert.GetTypeCode();
switch (code)
{
case TypeCode.Boolean:
return new BooleanValue(Convert.ToBoolean(convert));
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return ScalarValue.Create(Convert.ToDouble(convert));
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return ScalarValue.Create(Convert.ToInt32(convert));
case TypeCode.String:
return new StringValue(Convert.ToString(convert, CultureInfo.CurrentCulture));
default:
break;
}
return value; // Conversion is one this method didn't implement.
}
/// <summary>
/// This is identical to FromPrimitive, except that it WILL throw an exception
/// if it was unable to guarantee that the result became (or already was) a kOS Structure.
/// </summary>
/// <param name="value">value to convert</param>
/// <returns>value after conversion, or original value if conversion unnecessary</returns>
public static Structure FromPrimitiveWithAssert(object value)
{
object convertedVal = FromPrimitive(value);
Structure returnValue = convertedVal as Structure;
if (returnValue == null)
throw new KOSException(
string.Format("Internal Error. Contact the kOS developers with the phrase 'impossible FromPrimitiveWithAssert({0}) was attempted'.\nAlso include the output log if you can.",
value == null ? "<null>" : value.GetType().ToString()));
return returnValue;
}
public static object ToPrimitive(object value)
{
var primitive = value as PrimitiveStructure;
if (primitive != null)
{
return primitive.ToPrimitive();
}
return value;
}
/// <summary>
/// A wrapper around Structure.ToString() that will indent the ToString() output
/// to the desired indent level.
/// </summary>
public virtual string ToStringIndented(int level)
{
if (level >= TerminalFormatter.MAX_INDENT_LEVEL)
return "<<TOSTRING REFUSES TO RECURSE DEEPER THAN NESTING LEVEL " + level + ">>";
StringBuilder returnVal = new StringBuilder();
string[] lines = ToString().Split('\n');
string pad = "";
if (lines.Count() > 1)
{
pad = String.Empty.PadRight(level * TerminalFormatter.INDENT_SPACES, ' ');
returnVal.Append("\n");
}
foreach (string line in lines)
{
returnVal.AppendFormat("{0}{1}", pad, line);
}
return returnVal.ToString();
}
}
}