-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoxList.swift
78 lines (65 loc) · 2.04 KB
/
LoxList.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
//
// LoxList.swift
// slox
//
// Created by Danielle Kefford on 3/12/24.
//
class LoxList: LoxInstance {
var elements: [LoxValue]
private class AppendImpl: LoxCallable {
var arity: Int = 1
var listInstance: LoxList
init(listInstance: LoxList) {
self.listInstance = listInstance
}
func call(interpreter: Interpreter, args: [LoxValue]) throws -> LoxValue {
let element = args[0]
self.listInstance.elements.append(element)
return .nil
}
}
private class DeleteAtImpl: LoxCallable {
var arity: Int = 1
var listInstance: LoxList
init(listInstance: LoxList) {
self.listInstance = listInstance
}
func call(interpreter: Interpreter, args: [LoxValue]) throws -> LoxValue {
guard case .number(let index) = args[0] else {
throw RuntimeError.indexMustBeANumber
}
return self.listInstance.elements.remove(at: Int(index))
}
}
init(elements: [LoxValue]) {
self.elements = elements
super.init(klass: nil)
}
override func get(propertyName: String) throws -> LoxValue {
switch propertyName {
case "count":
return .number(Double(elements.count))
case "append":
return .callable(AppendImpl(listInstance: self))
case "deleteAt":
return .callable(DeleteAtImpl(listInstance: self))
default:
throw RuntimeError.undefinedProperty(propertyName)
}
}
override func set(propertyName: String, propertyValue: LoxValue) throws {
throw RuntimeError.onlyInstancesHaveProperties
}
static func == (lhs: LoxList, rhs: LoxList) -> Bool {
return lhs.elements == rhs.elements
}
// TODO: Need to think about how to handle invalid indices!!!
subscript(index: Int) -> LoxValue {
get {
return elements[index]
}
set(newValue) {
elements[index] = newValue
}
}
}