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
|
package moe.nea.lisp.bind
import moe.nea.lisp.*
import java.lang.invoke.MethodHandles
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.lang.reflect.Parameter
typealias ObjectMapper = (AutoBinder.ParameterRemappingContext) -> (Any?)
class AutoBinder {
companion object {
val Parameter.effectiveType get() = if (this.isVarArgs) this.type.componentType else this.type
}
private fun mapLispData(parameter: Parameter): ObjectMapper? {
if (LispData::class.java.isAssignableFrom(parameter.effectiveType)) return {
parameter.effectiveType.cast(
it.getOne()
)
}
return null
}
private fun mapForeignObject(parameter: Parameter): ObjectMapper? {
parameter.getAnnotation(UnmapForeignObject::class.java) ?: return null
return {
when (val x = it.getOne()) {
is LispData.ForeignObject<*> -> {
parameter.effectiveType.cast(x.obj)
}
else -> {
it.errorReporter.reportError("$x needs to be of type")
null
}
}
}
}
private fun mapErrorReporter(parameter: Parameter): ObjectMapper? {
if (ErrorReporter::class.java.isAssignableFrom(parameter.effectiveType)) return { it.errorReporter }
return null
}
private fun mapString(parameter: Parameter): ObjectMapper? {
if (String::class.java == parameter.effectiveType) return {
when (val x = it.getOne()) {
is LispData.LispString -> x.string
is LispData.Atom -> x.label
else -> null.also { _ -> it.errorReporter.reportError("Could not coerce $x to string") }
}
}
return null
}
private fun mapBoolean(parameter: Parameter): ObjectMapper? {
if (Boolean::class.java.isAssignableFrom(parameter.effectiveType)) return {
val x = it.getOne()
val y = CoreBindings.isTruthy(x)
if (y == null) {
it.errorReporter.reportError("Could not coerce $x to a boolean")
}
y
}
return null
}
private fun mapAST(parameter: Parameter): ObjectMapper? {
if (LispAst::class.java.isAssignableFrom(parameter.effectiveType)) return {
parameter.effectiveType.cast(
it.getOneNode()
)
}
return null
}
private fun mapNumber(parameter: Parameter): ObjectMapper? {
if (Double::class.java.isAssignableFrom(parameter.effectiveType)) return {
when (val x = it.getOne()) {
is LispData.LispNumber -> x.value
else -> null.also { _ -> it.errorReporter.reportError("Could not coerce $x to number") }
}
}
if (Float::class.java.isAssignableFrom(parameter.effectiveType)) return {
when (val x = it.getOne()) {
is LispData.LispNumber -> x.value.toFloat()
else -> null.also { _ -> it.errorReporter.reportError("Could not coerce $x to number") }
}
}
if (Int::class.java.isAssignableFrom(parameter.effectiveType)) return {
when (val x = it.getOne()) {
is LispData.LispNumber -> x.value.toInt()
else -> null.also { _ -> it.errorReporter.reportError("Could not coerce $x to number") }
}
}
if (Long::class.java.isAssignableFrom(parameter.effectiveType)) return {
when (val x = it.getOne()) {
is LispData.LispNumber -> x.value.toLong()
else -> null.also { _ -> it.errorReporter.reportError("Could not coerce $x to number") }
}
}
return null
}
private fun mapStackFrame(parameter: Parameter): ObjectMapper? {
if (parameter.effectiveType == StackFrame::class.java) return {
it.stackFrame
}
if (parameter.effectiveType == LispExecutionContext::class.java) return {
it.context
}
return null
}
val objectMappers = mutableListOf<((Parameter) -> ObjectMapper?)>(
::mapLispData,
::mapErrorReporter,
::mapNumber,
::mapString,
::mapBoolean,
::mapAST,
::mapForeignObject,
::mapStackFrame,
)
fun generateInstanceBindings(obj: Any): Map<String, LispData> {
val bindings = mutableMapOf<String, LispData>()
for (method in obj.javaClass.methods) {
val annotation = method.getAnnotation(LispBinding::class.java) ?: continue
require(LispParser.isValidIdentifier(annotation.name))
bindings[annotation.name] = wrapMethod(obj, annotation.name, method)
}
// TODO: field bindings
return bindings
}
open fun makeVarArgMapper(
parameter: Parameter,
baseMapper: ObjectMapper
): ObjectMapper? {
return {
val l = buildList {
while (it.hasMore())
add(baseMapper(it)!!)
}
val a = java.lang.reflect.Array.newInstance(parameter.type.componentType, l.size) as Array<Any>
l.withIndex().forEach { a[it.index] = it.value }
a
}
}
private val lookup = MethodHandles.publicLookup()
data class ParameterRemappingContext(
val getOne: () -> LispData,
val getOneNode: () -> LispAst.LispNode,
val hasMore: () -> Boolean,
val errorReporter: ErrorReporter,
val stackFrame: StackFrame,
val context: LispExecutionContext,
val callsite: LispAst.LispNode,
val args: List<LispAst.LispNode>,
)
fun wrapMethod(obj: Any, name: String, method: Method): LispData.LispExecutable {
var mh = lookup.unreflect(method)
if (method.modifiers and Modifier.STATIC == 0) {
mh = mh.bindTo(obj)
}
val objectMappers = method.parameters.map { param ->
val baseMapper = objectMappers.firstNotNullOfOrNull { it.invoke(param) }
?: error("Could not find object mapper for parameter $param")
if (param.isVarArgs) {
makeVarArgMapper(param, baseMapper)
?: error("Could not transform object mapper to vararg object mapper")
} else
baseMapper
}
return LispData.externalRawCall(name) { context: LispExecutionContext, callsite: LispAst.LispNode, stackFrame: StackFrame, args: List<LispAst.LispNode> ->
val e = object : ErrorReporter {
override fun reportError(string: String): LispData {
return stackFrame.reportError(string, callsite)
}
}
try {
val iterator = args.iterator()
val prc = ParameterRemappingContext(
{ context.resolveValue(stackFrame, iterator.next()) },
{ iterator.next() },
{ iterator.hasNext() },
e,
stackFrame,
context,
callsite,
args
)
val p = objectMappers.map {
it.invoke(prc)
?: return@externalRawCall LispData.LispNil
}
if (iterator.hasNext()) return@externalRawCall e.reportError("Too many arguments")
val r = mh.invokeWithArguments(p)
if (method.returnType == Void.TYPE || method.returnType == Unit::class.java)
return@externalRawCall LispData.LispNil
r as LispData
} catch (x: Exception) {
e.reportError("$name threw an exception", x)
}
}
}
fun bindTo(obj: Any, frame: StackFrame) {
frame.variables.putAll(generateInstanceBindings(obj))
}
}
|