summaryrefslogtreecommitdiff
path: root/src/CoreBindings.kt
blob: d88c95090a22da0f5f010372e6df726e6ed33de1 (plain)
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
package moe.nea.lisp

object CoreBindings {
    val def = LispData.externalRawCall("def") { context, callsite, stackFrame, args ->
        if (args.size != 2) {
            return@externalRawCall context.reportError("Function define expects exactly two arguments", callsite)
        }
        val (name, value) = args
        if (name !is LispAst.Reference) {
            return@externalRawCall context.reportError("Define expects a name as first argument", name)
        }
        if (name.label in stackFrame.variables) {
            return@externalRawCall context.reportError("Cannot redefine value in local context", name)
        }
        return@externalRawCall stackFrame.setValueLocal(name.label, context.resolveValue(stackFrame, value))
    }

    private fun isTruthy(data: LispData): Boolean? {
        if (data == trueValue) return true
        if (data == falseValue) return false
        return null
    }

    val trueValue = LispData.Atom("true")
    val falseValue = LispData.Atom("false")

    val ifFun = LispData.externalRawCall("if") { context, callsite, stackFrame, args ->
        if (args.size != 3) {
            return@externalRawCall context.reportError("if requires 3 arguments", callsite)
        }
        val (cond, ifTrue, ifFalse) = args

        val c = isTruthy(context.resolveValue(stackFrame, cond))
        if (c == null) {
            return@externalRawCall context.reportError("Non boolean value $c used as condition for if", cond)
        }
        if (c) {
            return@externalRawCall context.resolveValue(stackFrame, ifTrue)
        } else {
            return@externalRawCall context.resolveValue(stackFrame, ifFalse)
        }
    }

    val pure = LispData.externalCall("pure") { args, reportError ->
        return@externalCall args.singleOrNull()?.let { value ->
            LispData.externalCall("pure.r") { args, reportError ->
                if (args.isNotEmpty())
                    reportError("Pure function does not expect arguments")
                else
                    value
            }
        } ?: reportError("Function pure expects exactly one argument")
    }

    val lambda = LispData.externalRawCall("lambda") { context, callsite, stackFrame, args ->
        if (args.size != 2) {
            return@externalRawCall context.reportError("Lambda needs exactly 2 arguments", callsite)
        }
        val (argumentNames, body) = args
        if (argumentNames !is LispAst.Parenthesis) {
            return@externalRawCall context.reportError("Lambda has invalid argument declaration", argumentNames)
        }
        val argumentNamesString = argumentNames.items.map {
            val ref = it as? LispAst.Reference
            if (ref == null) {
                return@externalRawCall context.reportError("Lambda has invalid argument declaration", it)
            }
            ref.label
        }
        if (body !is LispAst.Parenthesis) {
            return@externalRawCall context.reportError("Lambda has invalid body declaration", body)
        }
        LispData.createLambda(stackFrame, argumentNamesString, body)
    }

    val defun = LispData.externalRawCall("defun") { context, callSite, stackFrame, lispAsts ->
        if (lispAsts.size != 3) {
            return@externalRawCall context.reportError("Invalid function definition", callSite)
        }
        val (name, args, body) = lispAsts
        if (name !is LispAst.Reference) {
            return@externalRawCall context.reportError("Invalid function definition name", name)
        }
        if (name.label in stackFrame.variables) {
            return@externalRawCall context.reportError("Cannot redefine function in local context", name)
        }
        if (args !is LispAst.Parenthesis) {
            return@externalRawCall context.reportError("Invalid function definition arguments", args)
        }
        val argumentNames = args.items.map {
            val ref = it as? LispAst.Reference
                ?: return@externalRawCall context.reportError("Invalid function definition argument name", it)
            ref.label
        }
        if (body !is LispAst.Parenthesis) {
            return@externalRawCall context.reportError("Invalid function definition body", body)
        }
        return@externalRawCall stackFrame.setValueLocal(
            name.label,
            LispData.createLambda(stackFrame, argumentNames, body, name.label)
        )
    }
    val seq = LispData.externalRawCall("seq") { context, callsite, stackFrame, args ->
        var lastResult: LispData? = null
        for (arg in args) {
            lastResult = context.executeLisp(stackFrame, arg)
        }
        lastResult ?: context.reportError("Seq cannot be invoked with 0 argumens", callsite)
    }

    internal fun stringify(thing: LispData): String {
        return when (thing) {
            is LispData.Atom -> ":${thing.label}"
            is LispData.JavaExecutable -> "<native function ${thing.name}>"
            LispData.LispNil -> "nil"
            is LispData.LispNode -> thing.node.toSource()
            is LispData.LispList -> thing.elements.joinToString(", ", "[", "]") { stringify(it) }
            is LispData.LispString -> thing.string
            is LispData.LispNumber -> thing.value.toString()
            is LispData.LispInterpretedCallable -> "<function ${thing.name ?: "<anonymous>"} ${thing.argNames} ${thing.body.toSource()}>"
        }
    }

    val tostring = LispData.externalCall("tostring") { args, reportError ->
        LispData.LispString(args.joinToString(" ") { stringify(it) })
    }

    val debuglog = LispData.externalCall("debuglog") { args, reportError ->
        println(args.joinToString(" ") { stringify(it) })
        LispData.LispNil
    }
    val add = LispData.externalCall("add") { args, reportError ->
        if (args.size == 0) {
            return@externalCall reportError("Cannot call add without at least 1 argument")
        }
        LispData.LispNumber(args.fold(0.0) { a, b ->
            a + (b as? LispData.LispNumber
                ?: return@externalCall reportError("Unexpected argument $b, expected number")).value
        })
    }
    val sub = LispData.externalCall("sub") { args, reportError ->
        if (args.size == 0) {
            return@externalCall reportError("Cannot call sub without at least 1 argument")
        }
        val c = args.map {
            (it as? LispData.LispNumber
                ?: return@externalCall reportError("Unexpected argument $it, expected number")
                    ).value
        }
        LispData.LispNumber(c.drop(1).fold(c.first()) { a, b ->
            a - b
        })
    }
    val mul = LispData.externalCall("mul") { args, reportError ->
        if (args.size == 0) {
            return@externalCall reportError("Cannot call mul without at least 1 argument")
        }
        LispData.LispNumber(args.fold(1.0) { a, b ->
            a * (b as? LispData.LispNumber
                ?: return@externalCall reportError("Unexpected argument $b, expected number")).value
        })
    }
    val eq = LispData.externalCall("eq") { args, reportError ->
        if (args.size == 0) {
            return@externalCall reportError("Cannot call eq without at least 1 argument")
        }
        LispData.boolean(!args.zipWithNext().any { it.first != it.second })
    }
    val div = LispData.externalCall("div") { args, reportError ->
        if (args.size == 0) {
            return@externalCall reportError("Cannot call div without at least 1 argument")
        }
        val c = args.map {
            (it as? LispData.LispNumber
                ?: return@externalCall reportError("Unexpected argument $it, expected number")
                    ).value
        }
        LispData.LispNumber(c.drop(1).fold(c.first()) { a, b ->
            a / b
        })
    }
    val less = LispData.externalCall("less") { args, reportError ->
        if (args.size != 2) {
            return@externalCall reportError("Cannot call less without exactly 2 arguments")
        }
        val (left, right) = args.map {
            (it as? LispData.LispNumber
                ?: return@externalCall reportError("Unexpected argument $it, expected number")
                    ).value
        }
        LispData.boolean(left < right)
    }
    val import = LispData.externalRawCall("import") { context, callsite, stackFrame, args ->
        if (args.size != 1) {
            return@externalRawCall context.reportError("import needs at least one argument", callsite)
        }
        // TODO: aliased / namespaced imports
        val moduleName = when (val moduleObject = context.resolveValue(stackFrame, args[0])) {
            is LispData.Atom -> moduleObject.label
            is LispData.LispString -> moduleObject.string
            else -> return@externalRawCall context.reportError("import needs a string or atom as argument", callsite)
        }
        context.importModule(moduleName, stackFrame, callsite)
        return@externalRawCall LispData.LispNil
    }

    fun offerArithmeticTo(bindings: StackFrame) {
        bindings.setValueLocal("+", add)
        bindings.setValueLocal("/", div)
        bindings.setValueLocal("*", mul)
        bindings.setValueLocal("-", sub)
        bindings.setValueLocal("lt", less)
        bindings.setValueLocal("=", eq)
    }

    fun offerAllTo(bindings: StackFrame) {
        bindings.setValueLocal("if", ifFun)
        bindings.setValueLocal("nil", LispData.LispNil)
        bindings.setValueLocal("def", def)
        bindings.setValueLocal("tostring", tostring)
        bindings.setValueLocal("pure", pure)
        bindings.setValueLocal("lambda", lambda)
        bindings.setValueLocal("defun", defun)
        bindings.setValueLocal("seq", seq)
        bindings.setValueLocal("import", import)
        bindings.setValueLocal("debuglog", debuglog)
        offerArithmeticTo(bindings)
    }
}