/
LoxClass.swift
50 lines (40 loc) · 1.23 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
//
// 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.params.count
}
return 0
}
var methods: [String: UserDefinedFunction]
init(name: String, superclass: LoxClass?, methods: [String: UserDefinedFunction]) {
self.name = name
self.superclass = superclass
self.methods = methods
super.init(klass: nil)
}
static func == (lhs: LoxClass, rhs: LoxClass) -> Bool {
return lhs === rhs
}
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 = LoxInstance(klass: self)
if let initializer = methods["init"] {
let boundInit = initializer.bind(instance: newInstance)
let _ = try boundInit.call(interpreter: interpreter, args: args)
}
return .instance(newInstance)
}
}