A minimal Python interpreter written in JavaScript.
This is my project for the course Principles of Programming Languages at Zhejiang University. Do not use it for serious business.
PyJS can be installed using NPM or Yarn:
$ npm install yzyzsun/PyJS
$ yarn add yzyzsun/PyJS
Then you can use npx PyJS test.py
to interpret Python code, which will also generate a Lisp-like syntax tree file in the same directory. You can access the interpreter programmatically from CommonJS module too:
const interpreter = require('PyJS').interpreter;
const source = require('fs').readFileSync('test.py', 'utf8');
interpreter.interpret(source);
There is also a pre-built demo page at demo/index.html
. You can use npm run build
to re-build demo/bundle.js
. (Remember to install dev dependencies before that.)
PyJS accepts a simplified version of Python 3, which includes the novel features of Python such as indentation levels, __*__
methods, LGB scoping rules, etc. It is designed to mimic the behavior of CPython as closely as possible but now there are still many subtle differences between them.
Its supported built-in types include int
, float
, bool
, str
, list
, dict
, set
, object
and NoneType
, together with special types like function
and type
. Arithmetic, bitwise and boolean operations, comparisons and conditional expressions (a.k.a. ternary operator) work and their corresponding methods will be respected. For example, the floor division operator //
will call __floordiv__()
internally. Simple statements including assignments, pass
, del
, return
, break
, continue
and compound statements including if-elif-else
, while
, for
, function and class definitions are also accepted.
For a detailed specification, see grammar.txt.
src/
:parser.jison
: The grammar file used by Jisonparser.js
: The LALR(1) parser generated by Jisoninterpreter.js
: The main part of interpretationobject.js
: Python object modelbuiltin.js
: Python built-in functionserror.js
: Error definitions used by interpretercli.js
: Command line interface
package.json
: NPM configuration filepackage-lock.json
: NPM lock filewebpack.config.js
: Webpack configuration file, used to bundle scripts and stylesheets intodemo/bundle.js
demo.js
: Entry point for webpack.babelrc
: Babel configuration file, used to transcompile ES2015+ to ES5