Skip to content

Commit

Permalink
add setBuiltinClass to Environment
Browse files Browse the repository at this point in the history
Added an additional `setBuiltinClass` method to environment to make it easier to add builtin LoxClasses.
  • Loading branch information
danman113 authored Jun 4, 2021
1 parent 9d85b11 commit 309f6a2
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions environment.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ class Environment {
this.map.set(name, typeof func === 'function' ? { call: func } : func)
}

setBuiltinClass(name, klass) {
this.map.set(name, JSClassToLoxClass(klass))
}

assign(token, value) {
if (!this.map.has(token.lexeme)) {
if (this.enclosing) return this.enclosing.assign(token, value)
Expand All @@ -36,3 +40,24 @@ class Environment {
}

module.exports = Environment

// We do all this below the export to avoid a circular dependancy
const { LoxClass } = require('./interpreter')
class FakeInstance {
constructor(call) {
this.call = call
}
bind(instance) {
this.call = this.call.bind(instance)
return this
}
}

const JSClassToLoxClass = klass => {
const methodNames = Object.getOwnPropertyNames(klass.prototype)
const methods = new Map(methodNames.map(name => [name, new FakeInstance(klass.prototype[name])]))
// TODO: Throw an error if user passes in a constructor
if (methods.has('constructor')) methods.delete('constructor')
const newKlass = new LoxClass(klass.name, methods)
return newKlass
}

0 comments on commit 309f6a2

Please sign in to comment.