-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
ObjectFetcher.java
443 lines (400 loc) · 19.4 KB
/
ObjectFetcher.java
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package com.denizenscript.denizencore.objects;
import com.denizenscript.denizencore.objects.core.*;
import com.denizenscript.denizencore.tags.CoreObjectTags;
import com.denizenscript.denizencore.tags.ObjectTagProcessor;
import com.denizenscript.denizencore.tags.TagManager;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizencore.tags.TagContext;
import com.denizenscript.denizencore.utilities.debugging.DebugInternals;
import java.lang.invoke.CallSite;
import java.lang.invoke.LambdaMetafactory;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.util.*;
public class ObjectFetcher {
public static Map<String, ObjectType<? extends ObjectTag>> objectsByPrefix = new HashMap<>();
public static Map<String, ObjectType<? extends ObjectTag>> objectsByName = new HashMap<>();
public static Map<Class<? extends ObjectTag>, ObjectType<? extends ObjectTag>> objectsByClass = new HashMap<>();
public static Map<Class<? extends ObjectTag>, List<Class<? extends ObjectTag>>> customSubtypeList = new HashMap<>();
public static HashSet<Class<? extends ObjectTag>> realObjectClassSet = new HashSet<>();
public static <T extends ObjectTag> ObjectType<T> getType(Class<T> type) {
return (ObjectType<T>) objectsByClass.get(type);
}
private static ArrayList<Class<? extends ObjectTag>> createList(Class<? extends ObjectTag> clazz) {
ArrayList<Class<? extends ObjectTag>> classes = new ArrayList<>();
classes.add(clazz);
classes.add(ElementTag.class);
return classes;
}
public static void registerCrossType(Class<? extends ObjectTag> a, Class<? extends ObjectTag> b) {
List<Class<? extends ObjectTag>> listA = customSubtypeList.computeIfAbsent(a, ObjectFetcher::createList);
List<Class<? extends ObjectTag>> listB = customSubtypeList.computeIfAbsent(b, ObjectFetcher::createList);
listA.add(b);
listB.add(a);
}
public static Collection<Class<? extends ObjectTag>> getAllApplicableSubTypesFor(Class<? extends ObjectTag> type) {
if (type == ObjectTag.class) {
return realObjectClassSet;
}
List<Class<? extends ObjectTag>> customSet = customSubtypeList.get(type);
if (customSet != null) {
return customSet;
}
if (type == ElementTag.class) {
return Collections.singleton(ElementTag.class);
}
return Arrays.asList(type, ElementTag.class);
}
public static ObjectType<BinaryTag> TYPE_BINARY;
public static ObjectType<CustomObjectTag> TYPE_CUSTOM;
public static ObjectType<DurationTag> TYPE_DURATION;
public static ObjectType<ElementTag> TYPE_ELEMENT;
public static ObjectType<JavaReflectedObjectTag> TYPE_REFLECTEDOBJECT;
public static ObjectType<ListTag> TYPE_LIST;
public static ObjectType<MapTag> TYPE_MAP;
public static ObjectType<QueueTag> TYPE_QUEUE;
public static ObjectType<ScriptTag> TYPE_SCRIPT;
public static ObjectType<SecretTag> TYPE_SECRET;
public static ObjectType<TimeTag> TYPE_TIME;
public static void registerCoreObjects() {
// <--[tag]
// @attribute <binary[<binary>]>
// @returns BinaryTag
// @description
// Returns a BinaryTag constructed from the input binary data in hexadecimal format.
// Refer to <@link objecttype BinaryTag>.
// -->
TYPE_BINARY = registerWithObjectFetcher(BinaryTag.class, BinaryTag.tagProcessor).setAsNOtherCode().setCanConvertStatic().generateBaseTag(); // binary@
// <--[tag]
// @attribute <custom_object[<custom-object>]>
// @returns CustomObjectTag
// @description
// Returns a custom object constructed from the input value.
// Refer to <@link ObjectType CustomObjectTag>.
// -->
TYPE_CUSTOM = registerWithObjectFetcher(CustomObjectTag.class, CustomObjectTag.tagProcessor).setAsNOtherCode().generateBaseTag(); // custom@
// <--[tag]
// @attribute <duration[<duration>]>
// @returns DurationTag
// @description
// Returns a duration object constructed from the input value.
// Refer to <@link ObjectType DurationTag>.
// -->
TYPE_DURATION = registerWithObjectFetcher(DurationTag.class, DurationTag.tagProcessor).setAsNOtherCode().setCanConvertStatic().generateBaseTag(); // d@
// <--[tag]
// @attribute <element[<element>]>
// @returns ElementTag
// @description
// Returns an element constructed from the input value.
// Refer to <@link objecttype ElementTag>.
// -->
TYPE_ELEMENT = registerWithObjectFetcher(ElementTag.class, ElementTag.tagProcessor).setCanConvertStatic().generateBaseTag(); // el@
TYPE_ELEMENT.typeChecker = ObjectType.TypeComparisonRunnable.trueAlways;
TYPE_ELEMENT.typeConverter = (obj, c) -> obj.asElement();
// <--[tag]
// @attribute <reflected[<reflected-tag>]>
// @returns JavaReflectedObjectTag
// @description
// Returns a JavaReflectedObjectTag constructed from the input reference ID lookup.
// Refer to <@link objecttype JavaReflectedObjectTag>.
// -->
TYPE_REFLECTEDOBJECT = registerWithObjectFetcher(JavaReflectedObjectTag.class, JavaReflectedObjectTag.tagProcessor).generateBaseTag(); // reflected@
// Tag generated externally as input is optional
TYPE_LIST = registerWithObjectFetcher(ListTag.class, ListTag.tagProcessor).setCanConvertStatic(); // li@
TYPE_LIST.typeChecker = ObjectType.TypeComparisonRunnable.trueAlways;
TYPE_LIST.typeConverter = ListTag::getListFor;
// Tag generated externally as input is optional
TYPE_MAP = registerWithObjectFetcher(MapTag.class, MapTag.tagProcessor).setCanConvertStatic(); // map@
TYPE_MAP.typeConverter = MapTag::getMapFor;
TYPE_MAP.typeChecker = (inp) -> {
if (inp == null) {
return false;
}
if (inp instanceof MapTag) {
return true;
}
if (!(inp instanceof ElementTag)) {
return false;
}
String simple = inp.toString();
if (simple.startsWith("map@")) {
return true;
}
if (simple.startsWith("[") && simple.endsWith("]") && simple.contains("=")) {
return true;
}
return false;
};
// Tag generated externally as input is optional
TYPE_QUEUE = registerWithObjectFetcher(QueueTag.class, QueueTag.tagProcessor).setAsNOtherCode(); // q@
// Tag generated externally as input is optional
TYPE_SCRIPT = registerWithObjectFetcher(ScriptTag.class, ScriptTag.tagProcessor).setAsNOtherCode(); // s@
// <--[tag]
// @attribute <secret[<secret>]>
// @returns SecretTag
// @description
// Returns a SecretTag object constructed from the input value.
// Refer to <@link ObjectType SecretTag>.
// @Example
// - webget <secret[my_secret_url]> "post:Message to secret address!"
// -->
TYPE_SECRET = registerWithObjectFetcher(SecretTag.class, SecretTag.tagProcessor).setAsNOtherCode().setCanConvertStatic().generateBaseTag(); // secret@
// <--[tag]
// @attribute <time[<time>]>
// @returns TimeTag
// @description
// Returns a time object constructed from the input value.
// Refer to <@link ObjectType TimeTag>.
// -->
TYPE_TIME = registerWithObjectFetcher(TimeTag.class, TimeTag.tagProcessor).setAsNOtherCode().setCanConvertStatic().generateBaseTag(); // time@
}
public static ObjectType.MatchesInterface getMatchesFor(Class clazz) {
try {
final MethodHandles.Lookup lookup = MethodHandles.lookup();
CallSite site = LambdaMetafactory.metafactory(lookup, "matches", // MatchesInterface#matches
MethodType.methodType(ObjectType.MatchesInterface.class), // Signature of invoke method
MethodType.methodType(Boolean.class, String.class).unwrap(), // signature of MatchesInterface#matches
lookup.findStatic(clazz, "matches", MethodType.methodType(Boolean.class, String.class).unwrap()), // signature of original matches method
MethodType.methodType(Boolean.class, String.class).unwrap()); // Signature of original matches again
return (ObjectType.MatchesInterface) site.getTarget().invoke();
}
catch (Throwable ex) {
System.err.println("Failed to get matches for " + clazz.getCanonicalName());
ex.printStackTrace();
Debug.echoError(ex);
return null;
}
}
public static ObjectType.ValueOfInterface getValueOfFor(Class clazz) {
try {
final MethodHandles.Lookup lookup = MethodHandles.lookup();
CallSite site = LambdaMetafactory.metafactory(lookup, "valueOf", // ValueOfInterface#valueOf
MethodType.methodType(ObjectType.ValueOfInterface.class), // Signature of invoke method
MethodType.methodType(ObjectTag.class, String.class, TagContext.class), // signature of ValueOfInterface#valueOf
lookup.findStatic(clazz, "valueOf", MethodType.methodType(clazz, String.class, TagContext.class)), // signature of original valueOf method
MethodType.methodType(clazz, String.class, TagContext.class)); // Signature of original valueOf again
return (ObjectType.ValueOfInterface) site.getTarget().invoke();
}
catch (Throwable ex) {
System.err.println("Failed to get valueOf for " + clazz.getCanonicalName());
ex.printStackTrace();
Debug.echoError(ex);
return null;
}
}
@Deprecated
public static void registerWithObjectFetcher(Class<? extends ObjectTag> objectTag) {
registerWithObjectFetcher(objectTag, null);
}
public static <T extends ObjectTag> ObjectType<T> registerWithObjectFetcher(Class<T> objectTag, ObjectTagProcessor<T> processor) {
String className = DebugInternals.getClassNameOpti(objectTag);
String shortName = null;
if (className.endsWith("Tag")) {
shortName = className.substring(0, className.length() - "Tag".length());
}
return registerWithObjectFetcher(objectTag, processor, shortName, className);
}
public static <T extends ObjectTag> ObjectType<T> registerWithObjectFetcher(Class<T> objectTag, ObjectTagProcessor<T> processor, String shortName, String longName) {
ObjectType<T> newType = new ObjectType<>();
newType.clazz = objectTag;
if (processor != null) {
processor.type = objectTag;
CoreObjectTags.generateCoreTags(processor);
newType.tagProcessor = processor;
}
newType.longName = longName;
newType.shortName = shortName;
newType.isAdjustable = Adjustable.class.isAssignableFrom(objectTag);
objectsByClass.put(objectTag, newType);
realObjectClassSet.add(objectTag);
try {
Method valueOfMethod = objectTag.getMethod("valueOf", String.class, TagContext.class);
if (valueOfMethod.isAnnotationPresent(Fetchable.class)) {
String identifier = valueOfMethod.getAnnotation(Fetchable.class).value();
objectsByPrefix.put(CoreUtilities.toLowerCase(identifier.trim()), newType);
objectsByName.put(CoreUtilities.toLowerCase(longName), newType);
if (shortName != null) {
objectsByName.put(CoreUtilities.toLowerCase(shortName), newType);
}
newType.prefix = identifier;
}
else {
Debug.echoError("Type '" + DebugInternals.getClassNameOpti(objectTag) + "' registered as an object type, but doesn't have a fetcher prefix.");
}
newType.matches = getMatchesFor(objectTag);
newType.valueOf = getValueOfFor(objectTag);
for (Method registerMethod : objectTag.getDeclaredMethods()) {
if ((registerMethod.getName().equals("register") || registerMethod.getName().equals("registerTags")) && registerMethod.getParameterCount() == 0) {
registerMethod.invoke(null);
break;
}
}
}
catch (Throwable ex) {
Debug.echoError("Failed to initialize an object type(" + DebugInternals.getClassNameOpti(objectTag) + "): ");
Debug.echoError(ex);
}
return newType;
}
public static boolean canFetch(String id) {
return objectsByPrefix.containsKey(CoreUtilities.toLowerCase(id));
}
public static boolean isObjectWithProperties(String input) {
return input.indexOf('[') != -1 && input.lastIndexOf(']') == input.length() - 1;
}
public static boolean checkMatch(Class<? extends ObjectTag> dClass, String value) {
return checkMatch(getType(dClass), value);
}
public static boolean checkMatch(ObjectType<? extends ObjectTag> objType, String value) {
if (value == null || objType == null) {
return false;
}
int firstBracket = value.indexOf('[');
if (firstBracket != -1 && value.lastIndexOf(']') == value.length() - 1) {
value = value.substring(0, firstBracket);
}
try {
return objType.matches.matches(value);
}
catch (Exception e) {
Debug.echoError(e);
}
return false;
}
public static List<String> separateProperties(String input) {
if (!isObjectWithProperties(input)) {
return null;
}
ArrayList<String> output = new ArrayList<>(input.length() / 7);
int start = 0;
boolean needObject = true;
int brackets = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '[' && needObject) {
needObject = false;
output.add(input.substring(start, i));
start = i + 1;
}
else if (input.charAt(i) == '[') {
brackets++;
}
else if (input.charAt(i) == ']' && brackets > 0) {
brackets--;
}
else if ((input.charAt(i) == ';' || input.charAt(i) == ']') && brackets == 0) {
output.add((input.substring(start, i)));
start = i + 1;
}
}
return output;
}
public static <T extends ObjectTag> T getObjectFrom(Class<T> dClass, String value, TagContext context) {
if (dClass == ObjectTag.class) {
return (T) pickObjectFor(value, context);
}
return getObjectFrom(getType(dClass), value, context);
}
public static <T extends ObjectTag> T getObjectFromWithProperties(Class<T> dClass, String value, TagContext context) {
return getObjectFromWithProperties(getType(dClass), value, context);
}
public static String partialUnescape(String description) {
if (description.indexOf('&') != -1) {
description = CoreUtilities.replace(description, "&sc", ";");
description = CoreUtilities.replace(description, "&lb", "[");
description = CoreUtilities.replace(description, "&rb", "]");
description = CoreUtilities.replace(description, "&eq", "=");
description = CoreUtilities.replace(description, "&", "&");
}
return description;
}
public static String unescapeProperty(String description) {
if (description.indexOf('&') == -1) {
return description;
}
int openBracket = description.indexOf('[');
if (openBracket == -1) {
return partialUnescape(description);
}
int length = description.length();
StringBuilder result = new StringBuilder(length);
int start = 0;
int brackets = 0;
for (int i = openBracket; i < length; i++) {
char c = description.charAt(i);
if (c == '[') {
brackets++;
if (brackets == 1) {
result.append(partialUnescape(description.substring(start, i)));
start = i;
}
}
else if (c == ']') {
brackets--;
if (brackets == 0) {
result.append(description, start, i);
start = i;
i = description.indexOf('[', start) - 1;
if (i < 0) {
break;
}
}
}
}
result.append(partialUnescape(description.substring(start)));
return result.toString();
}
public static void applyPropertySet(Adjustable object, TagContext context, List<String> properties) {
for (int i = 1; i < properties.size(); i++) {
List<String> data = CoreUtilities.split(properties.get(i), '=', 2);
if (data.size() != 2) {
Debug.echoError("Invalid property string '" + properties.get(i) + "'!");
continue;
}
String description = unescapeProperty(data.get(1));
object.safeApplyProperty(new Mechanism(data.get(0), new ElementTag(description), context));
}
}
public static <T extends ObjectTag> T getObjectFrom(ObjectType<T> type, String value, TagContext context) {
try {
return type.valueOf.valueOf(value, context);
}
catch (Exception e) {
Debug.echoError(e);
}
return null;
}
public static <T extends ObjectTag> T getObjectFromWithProperties(ObjectType<T> type, String value, TagContext context) {
try {
List<String> matches = separateProperties(value);
boolean matched = matches != null && type.isAdjustable;
T gotten = type.valueOf.valueOf(matched ? matches.get(0) : value, context);
if (gotten != null && matched) {
applyPropertySet((Adjustable) gotten, context, matches);
gotten = (T) gotten.fixAfterProperties();
}
return gotten;
}
catch (Exception e) {
Debug.echoError(e);
}
return null;
}
public static ObjectTag pickObjectFor(String value, TagContext context) {
if (value == null) {
return null;
}
if (CoreUtilities.contains(value, '@')) {
String type = value.split("@", 2)[0];
ObjectType<? extends ObjectTag> toFetch = objectsByPrefix.get(type);
if (toFetch != null && (toFetch.canConvertStatic || !TagManager.isStaticParsing)) {
ObjectTag fetched = getObjectFrom(toFetch, value, context);
if (fetched != null) {
return fetched;
}
}
}
return new ElementTag(value);
}
}