Python meta-circular evaluator

1.1k views Asked by At

It's not uncommon for an intro programming class to write a Lisp metacircular evaluator. Has there been any attempt at doing this for Python?

Yes, I know that Lisp's structure and syntax lends itself nicely to a metacircular evaluator, etc etc. Python will most likely be more difficult. I am just curious as to whether such an attempt has been made.

2

There are 2 answers

0
Cees Timmerman On

I think i wrote one here:

"""
Metacircular Python interpreter with macro feature.
By Cees Timmerman, 14aug13.
"""

import re
re_macros = re.compile("^#define (\S+) ([^\r\n]+)", re.MULTILINE)

def meta_python_exec(code):
    # Optional meta feature.
    macros = re_macros.findall(code)
    code = re_macros.sub("", code)
    for m in macros:
        code = code.replace(m[0], m[1])

    # Run the code.
    exec(code)

if __name__ == "__main__":
    #code = open("metacircular_overflow.py", "r").read()  # Causes a stack overflow in Python 3.2.3, but simply raises "RuntimeError: maximum recursion depth exceeded while calling a Python object" in Python 2.7.3.
    code = "#define 1 2\r\nprint(1 + 1)"
    meta_python_exec(code)
0
orftz On

For those who don't know what a meta-circular evaluator is, it is an interpreter which is written in the language to be interpreted. For example: a Lisp interpreter written in Lisp, or in our case, a Python interpreter written in Python. For more information, read this chapter from SICP.

As JBernardo said, PyPy is one. However, PyPy's Python interpreter, the meta-circular evaluator that is, is implemented in a statically typed subset of Python called RPython.

You'll be pleased to know that, as of the 1.5 release, PyPy is fully compliant with the official Python 2.7 specification. Even more so: PyPy nearly always beats Python in performance benchmarks.

For more information see PyPy docs and PyPy extra docs.