Skip to content

Commit

Permalink
A few refinements and comments to add clarity.
Browse files Browse the repository at this point in the history
  • Loading branch information
quephird committed Mar 10, 2024
1 parent 8526593 commit 2e8ce09
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 9 deletions.
13 changes: 7 additions & 6 deletions slox/Interpreter.swift
Expand Up @@ -125,12 +125,13 @@ class Interpreter {
staticMethodImpls[nameToken.lexeme] = staticMethodImpl
}

let metaclass = LoxClass(name: "\(nameToken.lexeme) metaclass" ,
methods: staticMethodImpls,
metaclass: nil)
let newClass = LoxClass(name: nameToken.lexeme,
methods: methodImpls,
metaclass: metaclass)
let newClass = LoxClass(name: nameToken.lexeme, methods: methodImpls)
if !staticMethodImpls.isEmpty {
// NOTA BENE: This assigns the static methods to the metaclass,
// which is lazily created in `LoxInstance`
newClass.klass.methods = staticMethodImpls
}

try environment.assignAtDepth(name: nameToken.lexeme, value: .instance(newClass), depth: 0)
}

Expand Down
5 changes: 3 additions & 2 deletions slox/LoxClass.swift
Expand Up @@ -16,10 +16,11 @@ class LoxClass: LoxInstance, LoxCallable {
}
var methods: [String: UserDefinedFunction]

init(name: String, methods: [String: UserDefinedFunction], metaclass: LoxClass?) {
init(name: String, methods: [String: UserDefinedFunction]) {
self.name = name
self.methods = methods
super.init(klass: metaclass)

super.init(klass: nil)
}

static func == (lhs: LoxClass, rhs: LoxClass) -> Bool {
Expand Down
5 changes: 4 additions & 1 deletion slox/LoxInstance.swift
Expand Up @@ -19,12 +19,15 @@ class LoxInstance: Equatable {
if _klass == nil {
// Only metaclasses should ever have a `nil` value for `_klass`
let selfClass = self as! LoxClass
_klass = LoxClass(name: "\(selfClass.name) metaclass", methods: [:], metaclass: nil)
_klass = LoxClass(name: "\(selfClass.name) metaclass", methods: [:])
}
return _klass!
}
var properties: [String: LoxValue] = [:]

/// - Parameter klass: The class this instance belongs to.
/// Use `nil` if this instance *is* a class; the `klass` property
/// will then instantiate a metaclass for it on demand.
init(klass: LoxClass?) {
self._klass = klass
}
Expand Down

0 comments on commit 2e8ce09

Please sign in to comment.