1 package io.jawk.ext;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 import java.io.IOException;
26 import java.io.ObjectInputStream;
27 import java.io.Serializable;
28 import java.lang.annotation.Annotation;
29 import java.lang.reflect.Array;
30 import java.lang.reflect.InvocationTargetException;
31 import java.lang.reflect.Method;
32 import java.lang.reflect.Parameter;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Objects;
38
39 import io.jawk.ext.annotations.JawkAssocArray;
40 import io.jawk.ext.annotations.JawkFunction;
41 import io.jawk.ext.annotations.JawkOptional;
42 import io.jawk.ext.annotations.JawkRawValue;
43 import io.jawk.ext.annotations.JawkRegexp;
44 import io.jawk.jrt.AssocArray;
45 import io.jawk.jrt.IllegalAwkArgumentException;
46
47
48
49
50 public final class ExtensionFunction implements Serializable {
51
52 private static final long serialVersionUID = 1L;
53
54
55 private final String keyword;
56
57
58 private final Class<? extends AbstractExtension> declaringType;
59
60
61 private final String methodName;
62
63
64 private final Class<?>[] parameterTypes;
65 private transient Method method;
66
67
68 private final boolean[] assocArrayParameters;
69
70
71 private final boolean varArgs;
72
73
74 private final int mandatoryParameterCount;
75
76
77 private final boolean varArgAssocArray;
78
79
80
81
82
83
84
85 private transient int[] rawValueParameterIndexes;
86
87
88 private transient int[] regexpParameterIndexes;
89
90 ExtensionFunction(String keywordParam, Method methodParam) {
91 this.keyword = validateKeyword(keywordParam, methodParam);
92 this.declaringType = resolveDeclaringType(methodParam);
93 this.methodName = methodParam.getName();
94 this.parameterTypes = methodParam.getParameterTypes();
95 this.method = prepareMethod(methodParam);
96 this.varArgs = methodParam.isVarArgs();
97 this.assocArrayParameters = inspectParameters(methodParam, methodParam.getParameters());
98 int optionalCount = scanOptionalParameterCount(methodParam, methodParam.getParameters());
99 this.mandatoryParameterCount = varArgs ?
100 assocArrayParameters.length - 1 :
101 assocArrayParameters.length - optionalCount;
102 this.varArgAssocArray = varArgs && assocArrayParameters[assocArrayParameters.length - 1];
103 computeAnnotationMetadata(methodParam);
104 }
105
106
107
108
109
110
111
112 private void computeAnnotationMetadata(Method methodParam) {
113 this.rawValueParameterIndexes = scanObjectParameterIndexes(
114 methodParam,
115 methodParam.getParameters(),
116 JawkRawValue.class);
117 this.regexpParameterIndexes = scanObjectParameterIndexes(
118 methodParam,
119 methodParam.getParameters(),
120 JawkRegexp.class);
121 }
122
123
124
125
126
127
128 private static int scanOptionalParameterCount(Method methodParam, Parameter[] parameters) {
129 int optionalCount = 0;
130 for (Parameter parameter : parameters) {
131 if (parameter.isAnnotationPresent(JawkOptional.class)) {
132 if (methodParam.isVarArgs()) {
133 throw new IllegalStateException(
134 "@" + JawkOptional.class.getSimpleName() + " cannot be combined with varargs: "
135 + methodParam.toGenericString());
136 }
137 optionalCount++;
138 } else if (optionalCount > 0) {
139 throw new IllegalStateException(
140 "@" + JawkOptional.class.getSimpleName() + " parameters must be trailing: "
141 + methodParam.toGenericString());
142 }
143 }
144 return optionalCount;
145 }
146
147 private static String validateKeyword(String keyword, Method method) {
148 Objects.requireNonNull(method, "method");
149 if (keyword == null || keyword.trim().isEmpty()) {
150 throw new IllegalStateException(
151 "@" + JawkFunction.class.getSimpleName() + " on " + method + " must declare a non-empty name");
152 }
153 return keyword;
154 }
155
156 private static Class<? extends AbstractExtension> resolveDeclaringType(Method method) {
157 Class<?> declaringClass = method.getDeclaringClass();
158 if (!AbstractExtension.class.isAssignableFrom(declaringClass)) {
159 throw new IllegalStateException(
160 "@" + JawkFunction.class.getSimpleName() + " must be declared on a subclass of "
161 + AbstractExtension.class.getName() + ": " + method);
162 }
163 @SuppressWarnings("unchecked")
164 Class<? extends AbstractExtension> type = (Class<? extends AbstractExtension>) declaringClass;
165 return type;
166 }
167
168 private static Method prepareMethod(Method method) {
169 if (java.lang.reflect.Modifier.isStatic(method.getModifiers())) {
170 throw new IllegalStateException(
171 "@" + JawkFunction.class.getSimpleName() + " does not support static methods: " + method.toGenericString());
172 }
173 method.setAccessible(true);
174 return method;
175 }
176
177
178
179
180
181
182 private static int[] scanObjectParameterIndexes(
183 Method methodParam,
184 Parameter[] parameters,
185 Class<? extends Annotation> annotationType) {
186 int count = 0;
187 int[] indexes = new int[parameters.length];
188 for (int idx = 0; idx < parameters.length; idx++) {
189 Parameter parameter = parameters[idx];
190 if (!parameter.isAnnotationPresent(annotationType)) {
191 continue;
192 }
193 if (parameter.isVarArgs() || parameter.getType() != Object.class) {
194 throw new IllegalStateException(
195 "Parameter " + idx + " of " + methodParam + " annotated with @" + annotationType.getSimpleName()
196 + " must be a non-vararg " + Object.class.getName());
197 }
198 indexes[count++] = idx;
199 }
200 return Arrays.copyOf(indexes, count);
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 private boolean[] inspectParameters(Method methodParam, Parameter[] parameters) {
234 boolean[] assoc = new boolean[parameters.length];
235 for (int idx = 0; idx < parameters.length; idx++) {
236 Parameter parameter = parameters[idx];
237 if (parameter.isAnnotationPresent(JawkAssocArray.class)) {
238 Class<?> parameterType = parameter.getType();
239 if (parameter.isVarArgs()) {
240 parameterType = parameterType.getComponentType();
241 }
242 if (!Map.class.isAssignableFrom(parameterType) || !parameterType.isAssignableFrom(AssocArray.class)) {
243 throw new IllegalStateException(
244 "Parameter " + idx + " of " + methodParam + " annotated with @" + JawkAssocArray.class.getSimpleName()
245 + " must accept " + AssocArray.class.getName() + " instances via " + Map.class.getName());
246 }
247 assoc[idx] = true;
248 }
249 }
250 return assoc;
251 }
252
253
254
255
256
257
258
259
260 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
261 in.defaultReadObject();
262 try {
263 Method resolved = declaringType.getDeclaredMethod(methodName, parameterTypes);
264 this.method = prepareMethod(resolved);
265 computeAnnotationMetadata(resolved);
266 } catch (NoSuchMethodException ex) {
267 throw new IllegalStateException(
268 "Unable to rehydrate extension method '" + methodName + "' on type " + declaringType.getName(),
269 ex);
270 }
271 }
272
273
274
275
276
277
278 public String getKeyword() {
279 return keyword;
280 }
281
282
283
284
285
286
287 public Class<? extends AbstractExtension> getDeclaringType() {
288 return declaringType;
289 }
290
291
292
293
294
295
296 public String getExtensionClassName() {
297 return declaringType.getName();
298 }
299
300
301
302
303
304
305 public int getArity() {
306 return mandatoryParameterCount;
307 }
308
309
310
311
312
313
314
315
316
317 public boolean expectsAssocArray(int index) {
318 if (index < 0 || index >= assocArrayParameters.length) {
319 throw new IndexOutOfBoundsException("Parameter index out of range: " + index);
320 }
321 return assocArrayParameters[index];
322 }
323
324
325
326
327
328
329
330
331
332 public int[] collectAssocArrayIndexes(int argCount) {
333 verifyArgCount(argCount);
334 List<Integer> indexes = new ArrayList<Integer>();
335 int upperBound = Math.min(argCount, declaredParameterUpperBound());
336 for (int idx = 0; idx < upperBound; idx++) {
337 if (assocArrayParameters[idx]) {
338 indexes.add(Integer.valueOf(idx));
339 }
340 }
341 if (varArgs && varArgAssocArray) {
342 for (int idx = mandatoryParameterCount; idx < argCount; idx++) {
343 indexes.add(Integer.valueOf(idx));
344 }
345 }
346 int[] result = new int[indexes.size()];
347 for (int idx = 0; idx < indexes.size(); idx++) {
348 result[idx] = indexes.get(idx).intValue();
349 }
350 return result;
351 }
352
353
354 private int declaredParameterUpperBound() {
355 return varArgs ? mandatoryParameterCount : parameterTypes.length;
356 }
357
358
359
360
361
362
363
364
365 public int[] collectRawValueIndexes(int argCount) {
366 verifyArgCount(argCount);
367 return Arrays.stream(rawValueParameterIndexes).filter(idx -> idx < argCount).toArray();
368 }
369
370
371
372
373
374
375
376
377 public int[] collectRegexpIndexes(int argCount) {
378 verifyArgCount(argCount);
379 return Arrays.stream(regexpParameterIndexes).filter(idx -> idx < argCount).toArray();
380 }
381
382
383
384
385
386
387
388
389
390
391 public Object invoke(AbstractExtension target, Object[] args) {
392 Objects.requireNonNull(target, "target");
393 if (!declaringType.isInstance(target)) {
394 throw new IllegalArgumentException(
395 "Extension instance " + target.getClass().getName() + " is not compatible with " + declaringType.getName());
396 }
397 int argCount = args == null ? 0 : args.length;
398 verifyArgCount(argCount);
399 enforceAssocArrayParameters(args);
400 Object[] invocationArgs = prepareArguments(args);
401 try {
402 return method.invoke(target, invocationArgs);
403 } catch (IllegalAccessException ex) {
404 throw new IllegalStateException("Unable to access extension function method for keyword '" + keyword + "'", ex);
405 } catch (InvocationTargetException ex) {
406 Throwable cause = ex.getCause();
407 if (cause instanceof RuntimeException) {
408 throw (RuntimeException) cause;
409 }
410 if (cause instanceof Error) {
411 throw (Error) cause;
412 }
413 throw new IllegalStateException("Invocation of extension function '" + keyword + "' failed", cause);
414 }
415 }
416
417 private Object[] prepareArguments(Object[] args) {
418 int argCount = args == null ? 0 : args.length;
419 if (!varArgs) {
420
421 Object[] invocationArgs = new Object[parameterTypes.length];
422 if (argCount > 0) {
423 System.arraycopy(args, 0, invocationArgs, 0, argCount);
424 }
425 return invocationArgs;
426 }
427 if (argCount == 0) {
428 return new Object[] { Array.newInstance(parameterTypes[parameterTypes.length - 1].getComponentType(), 0) };
429 }
430 Object[] invocationArgs = new Object[mandatoryParameterCount + 1];
431 for (int idx = 0; idx < mandatoryParameterCount; idx++) {
432 invocationArgs[idx] = args[idx];
433 }
434 int varArgCount = argCount - mandatoryParameterCount;
435 Class<?> componentType = parameterTypes[parameterTypes.length - 1].getComponentType();
436 Object varArgArray = Array.newInstance(componentType, varArgCount);
437 for (int idx = 0; idx < varArgCount; idx++) {
438 Array.set(varArgArray, idx, args[mandatoryParameterCount + idx]);
439 }
440 invocationArgs[mandatoryParameterCount] = varArgArray;
441 return invocationArgs;
442 }
443
444
445
446
447
448
449
450
451 public void verifyArgCount(int argCount) {
452 if (!varArgs) {
453 int maxCount = parameterTypes.length;
454 if (argCount < mandatoryParameterCount || argCount > maxCount) {
455 String expected = mandatoryParameterCount == maxCount ?
456 String.valueOf(maxCount) :
457 mandatoryParameterCount + " to " + maxCount;
458 throw new IllegalAwkArgumentException(
459 "Extension function '" + keyword + "' expects " + expected + " argument(s), not " + argCount);
460 }
461 return;
462 }
463 if (argCount < mandatoryParameterCount) {
464 throw new IllegalAwkArgumentException(
465 "Extension function '" + keyword + "' expects " + getArity() + " argument(s), not " + argCount);
466 }
467 }
468
469 private void enforceAssocArrayParameters(Object[] args) {
470 if (args == null) {
471 return;
472 }
473 int argCount = args.length;
474 int upperBound = Math.min(argCount, declaredParameterUpperBound());
475 for (int idx = 0; idx < upperBound; idx++) {
476 if (assocArrayParameters[idx]) {
477 requireAssocArray(idx, args[idx]);
478 }
479 }
480 if (varArgs && varArgAssocArray) {
481 for (int idx = mandatoryParameterCount; idx < argCount; idx++) {
482 requireAssocArray(idx, args[idx]);
483 }
484 }
485 }
486
487 private void requireAssocArray(int idx, Object arg) {
488 if (!(arg instanceof Map)) {
489 throw new IllegalAwkArgumentException(
490 "Argument " + idx + " passed to extension function '" + keyword + "' must be an associative array");
491 }
492 }
493 }