Skip to content
A minimal Python interpreter written in JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
demo
src
.babelrc
.gitignore
LICENSE
README.md
demo.js
grammar.txt
package-lock.json
package.json
webpack.config.js

README.md

PyJS

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.

Usage

PyJS can be installed using NPM or Yarn:

$ npm install yzyzsun/PyJS
$ yarn add yzyzsun/PyJS

Then you can use ./node_modules/.bin/PyJS to interpret Python code file, 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.)

Specification

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.

Hierarchy

  • src/:
    • parser.jison: The grammar file used by Jison
    • parser.js: The LALR(1) parser generated by Jison
    • interpreter.js: The main part of interpretation
    • object.js: Python object model
    • builtin.js: Python built-in functions
    • error.js: Error definitions used by interpreter
    • cli.js: Command line interface
  • package.json: NPM configuration file
  • package-lock.json: NPM lock file
  • webpack.config.js: Webpack configuration file, used to bundle scripts and stylesheets into demo/bundle.js
  • demo.js: Entry point for webpack
  • .babelrc: Babel configuration file, used to transcompile ES2015+ to ES5

Demo

http://projects.yzyzsun.me/pyjs/

You can’t perform that action at this time.