aboutsummaryrefslogtreecommitdiff
path: root/src/eval-env/builtins.ts
blob: 1ded638457ebfec0875040a077459f365dd3be7e (plain) (blame)
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
import { SyntaxKind, Type } from 'ts-morph'
import { Ctx } from '../types'
import { evalList } from '../util'

const applyFunc = (ctx: Ctx, fn: Type | undefined, val: string): Type => {
  const resultType = (() => {
    const baseTypes = fn?.getBaseTypes().flatMap(t => t.getSymbol()?.getName())

    if (baseTypes?.includes('Kind1')) {
      const [_, resultNode] = ctx.createResult(
        `(${ctx.typeToString(fn)} & { input: ${val} })['return']`
      )
      return resultNode
        ?.getType()
        .getProperty('output')
        ?.getTypeAtLocation(resultNode)
    } else {
      const [_key, resultNode] = ctx.createResult(`ReturnType<${ctx.typeToString(fn)}>`)

      const resValueNode = resultNode
        ?.asKind(SyntaxKind.PropertySignature)
        ?.getChildAtIndexIfKind(2, SyntaxKind.TypeLiteral)
        ?.getProperty('output')
        ?.getChildAtIndexIfKind(2, SyntaxKind.TypeReference)

      const functionNode = resValueNode
        ?.getChildAtIndexIfKind(1, SyntaxKind.SyntaxList)
        ?.getFirstChildIfKind(SyntaxKind.FunctionType)

      if (functionNode) {
        const typeParameters = functionNode.getTypeParameters() ?? []

        if (typeParameters.length > 0) {
          const constraint = typeParameters[0]?.getConstraint()
          if (constraint) {
            constraint?.replaceWithText(val)
          } else {
            typeParameters[0]?.setConstraint(val)
          }
        }

        return resValueNode?.getType()
      }
    }

    return undefined
  })()

  // TODO: Cleanup unwanted result node values

  if (!resultType) {
    throw new Error('Fuck shit')
  }

  return resultType
}

export default (ctx: Ctx, args: Type[]) => ({
  SetEvalEnvironment: async () => {
    ctx.setEnv(ctx.getTypeValue(args[0]))
    return []
  },

  DefineEffect: async () => {
    const [nameTyp, exprTyp] = args
    const name = nameTyp?.getLiteralValue() as string
    const exprStr = exprTyp?.getLiteralValue() as string

    ctx.addCustomEffect(name, exprStr)
    return []
  },

  CreateRef: async () => {
    const val = ctx.typeToString(args[0])
    const refKey = ctx.createRef(val)
    const [resultKey, _] = ctx.createResult(JSON.stringify(refKey))
    return [resultKey]
  },

  GetRef: async () => {
    const refKey = ctx.getTypeValue(args[0])
    const val = ctx.getRef(refKey)
    if (!val) throw new Error('Ref has been deleted')
    const [resultKey, _] = ctx.createResult(val)
    return [resultKey]
  },

  SetRef: async () => {
    const [keyTy, valTyp] = args
    ctx.setRef(ctx.getTypeValue(keyTy), ctx.typeToString(valTyp))
    return []
  },

  DeleteRef: async () => {
    ctx.deleteRef(ctx.getTypeValue(args[0]))
    return []
  },

  Pure: async () => {
    const [valTyp] = args
    const [resultKey, _] = ctx.createResult(ctx.typeToString(valTyp))
    return [resultKey]
  },

  Print: async () => {
    console.log(...args.map(ctx.typeToString))
    return []
  },

  PutString: async () => {
    const [strinTyp] = args
    const typString = ctx.getTypeValue(strinTyp) ?? ctx.typeToString(strinTyp)
    process.stdout.write(typString)
    return []
  },

  Debug: async () => {
    const [labelTyp, valueTyp] = args
    const label = ctx.getTypeValue(labelTyp)
    const value = ctx.typeToString(valueTyp)
    console.log(label, value)
    const [resultKey, _] = ctx.createResult(JSON.stringify(value))
    return [resultKey]
  },

  Bind: ctx.withScope(async () => {
    const [inputTyp, chainToKind] = args
    const [resultKey] = inputTyp ? await ctx.evaluateType(ctx, inputTyp) : []

    // TODO: Handle resultKey undefined case

    const resultType =
      applyFunc(ctx, chainToKind, `(${ctx.getResultExpr(resultKey)})['output']`)
    return ctx.evaluateType(ctx, resultType)
  }),

  BindTo: async () => {
    const [labelTyp, effTyp] = args
    const label = ctx.getTypeValue(labelTyp)
    const [resultKey] = effTyp ? await ctx.evaluateType(ctx, effTyp) : []
    if (resultKey) {
      ctx.addToScope(label, resultKey)
      return [resultKey]
    }
    return []
  },

  Label: async () => {
    const label = ctx.getTypeValue(args[0])
    const value = ctx.getKeyInScope(label)
    if (!value) {
      throw new Error(`Label "${label}" not found`)
    }
    return [value]
  },

  Try: async () => {
    const [effTyp, catchK] = args

    try {
      if (!effTyp) throw new Error('wow')
      return await ctx.evaluateType(ctx, effTyp)
    } catch (e) {
      const error = JSON.stringify((e as any)?.message ?? e)
      const resultType = applyFunc(ctx, catchK, error)
      return ctx.evaluateType(ctx, resultType)
    }
  },

  Throw: async () => {
    throw args[0] && ctx.getTypeValue(args[0])
  },

  JsExpr: async () => {
    const [exprTyp] = args
    const exprStr = ctx.getTypeValue(exprTyp)
    const result = eval(`JSON.stringify(${exprStr})`)
    const [resultKey, _] = ctx.createResult(`${result}`)
    return [resultKey]
  },

  Seq: async () => {
    const [effectTyps] = args
    const effectResults = await evalList(
      ctx,
      effectTyps?.getTupleElements() ?? []
    )
    const [resultKey, _] = ctx.createResult(`[
        ${effectResults.map(ctx.getResultExpr).join(', ')}
      ]`)
    return [resultKey]
  },

  Do: ctx.withScope(async () => {
    const [effectTyps] = args
    const effectResults = await evalList(
      ctx,
      effectTyps?.getTupleElements() ?? []
    )
    // TODO: Use last type's result instead of last result key
    const lastResKey = effectResults[effectResults.length - 1]
    const [resultKey, _] = ctx.createResult(
      `(${ctx.getResultExpr(lastResKey)})['output']`
    )
    return [resultKey]
  }),
})