Permalink
Browse files

Brainstorm about unifying the implementation of classes and closures.

Also update opy/README.md
  • Loading branch information...
Andy Chu
Andy Chu committed Apr 10, 2018
1 parent f43b091 commit b09a27bf4c9d2da81f21dea0cacdbe5d6fa62ed7
Showing with 82 additions and 1 deletion.
  1. +4 −1 opy/README.md
  2. +3 −0 opy/byterun/pyvm2.py
  3. +75 −0 opy/gold/class_vs_closure.py
View
@@ -20,7 +20,8 @@ Very Rough Outline of Future Plans
(Tree shaking).
- Produce a statically typed AST.
- Add type annotations for functions/constructors, possibly with `.pyi` files
generated by tests.
generated by tests. NOTE: Dropbox's [pyannotate][] has some restrictions
related to the `sys.setprofile()` hook. `byterun` might be better!
- Add type annotations for class members. Possibly with something like
[attrs](http://www.attrs.org/en/stable/)?
- Add type inference for local variables.
@@ -40,6 +41,8 @@ Also:
`re2c`.
- Copy the stuff we use out of `posixmodule.c`, `pwdmodule.c`, etc.
[pyannotate]: http://mypy-lang.blogspot.com/2017/11/dropbox-releases-pyannotate-auto.html
Getting started
---------------
View
@@ -162,7 +162,10 @@ def make_frame(self, code, callargs={}, f_globals=None, f_locals=None):
def resume_frame(self, frame):
"""Called by Generator."""
frame.f_back = self.frame
# NOTE: Could raise exceptions!
val = self.run_frame(frame)
frame.f_back = None
return val
@@ -0,0 +1,75 @@
#!/usr/bin/python
"""
class_vs_closure.py
TODO: These should be implemented the same way in the interpreter loop?
Closure is implemented with:
- pyobj.Function.func_closure
Class is implemented with type(), and then the constructor creates a namespace
with __dict__ and so forth. Access through 'self'. LOAD_FAST self, where self
is a local variable.
There was one language that made it explicit. Skew lanaguage?
# {} is for static language of types/data. : is for language of
# code/algorithms.
class Adder1 {
init(self.amount): # auto-init
pass
call(x):
return x + self.amount
}
func Adder2(amount) {
return func(x) { # function literal
# outer means that the variable is captured lexically?
return x + outer::amount
}
}
# Shortcut
class Adder1 is Object (self.amount Int) {
call(x Int):
return x + self.amount
}
"""
import sys
class Adder1(object):
def __init__(self, amount):
self.amount = amount
def __call__(self, x):
return x + self.amount
# This one uses a LOAD_CLOSURE bytecode; the other one doesn't.
def Adder2(amount):
def anon(x):
return x + amount
return anon
def main(argv):
a1 = Adder1(1)
a2 = Adder2(1)
print(a1(42))
print(a2(42))
if __name__ == '__main__':
try:
main(sys.argv)
except RuntimeError as e:
print >>sys.stderr, 'FATAL: %s' % e
sys.exit(1)

0 comments on commit b09a27b

Please sign in to comment.