/
NativeFunction.swift
84 lines (70 loc) · 2.33 KB
/
NativeFunction.swift
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
//
// NativeFunction.swift
// slox
//
// Created by Danielle Kefford on 3/2/24.
//
import Foundation
enum NativeFunction: LoxCallable, Equatable, CaseIterable {
case clock
case appendNative
case deleteAtNative
case removeValueNative
case keysNative
case valuesNative
var arity: Int {
switch self {
case .clock:
return 0
case .appendNative:
return 2
case .deleteAtNative:
return 2
case .removeValueNative:
return 2
case .keysNative:
return 1
case .valuesNative:
return 1
}
}
func call(interpreter: Interpreter, args: [LoxValue]) throws -> LoxValue {
switch self {
case .clock:
return .double(Date().timeIntervalSince1970)
case .appendNative:
guard case .instance(let loxList as LoxList) = args[0] else {
throw RuntimeError.notAListOrDictionary
}
let element = args[1]
loxList.elements.append(element)
return .nil
case .deleteAtNative:
guard case .instance(let loxList as LoxList) = args[0] else {
throw RuntimeError.notAListOrDictionary
}
guard case .int(let index) = args[1] else {
throw RuntimeError.indexMustBeAnInteger
}
return loxList.elements.remove(at: Int(index))
case .removeValueNative:
guard case .instance(let loxDictionary as LoxDictionary) = args[0] else {
throw RuntimeError.notAListOrDictionary
}
let key = args[1]
return loxDictionary.kvPairs.removeValue(forKey: key) ?? .nil
case .keysNative:
guard case .instance(let loxDictionary as LoxDictionary) = args[0] else {
throw RuntimeError.notAListOrDictionary
}
let keys = Array(loxDictionary.kvPairs.keys)
return try! interpreter.makeList(elements: keys)
case .valuesNative:
guard case .instance(let loxDictionary as LoxDictionary) = args[0] else {
throw RuntimeError.notAListOrDictionary
}
let values = Array(loxDictionary.kvPairs.values)
return try! interpreter.makeList(elements: values)
}
}
}