/
LoxClass.swift
63 lines (52 loc) · 1.54 KB
/
LoxClass.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
//
// LoxClass.swift
// slox
//
// Created by Danielle Kefford on 3/4/24.
//
class LoxClass: LoxInstance, LoxCallable {
var name: String
var superclass: LoxClass?
var arity: Int {
if let initializer = methods["init"] {
return initializer.arity
}
return 0
}
var methods: [String: UserDefinedFunction]
var instanceType: LoxInstance.Type {
if self.name == "List" {
LoxList.self
} else if self.name == "Dictionary" {
LoxDictionary.self
} else {
LoxInstance.self
}
}
convenience init(name: String, superclass: LoxClass?, methods: [String: UserDefinedFunction]) {
self.init(klass: nil)
self.name = name
self.superclass = superclass
self.methods = methods
}
required init(klass: LoxClass?) {
self.name = "(anonymous)"
self.superclass = nil
self.methods = [:]
super.init(klass: klass)
}
func findMethod(name: String) -> UserDefinedFunction? {
if let method = methods[name] {
return method
}
return superclass?.findMethod(name: name)
}
func call(interpreter: Interpreter, args: [LoxValue]) throws -> LoxValue {
let newInstance = instanceType.init(klass: self)
if let initializer = methods["init"] {
let boundInit = initializer.bind(instance: newInstance)
let _ = try boundInit.call(interpreter: interpreter, args: args)
}
return .instance(newInstance)
}
}