Skip to content
/ PyJS Public

A minimal Python interpreter written in JavaScript

License

Notifications You must be signed in to change notification settings

yzyzsun/PyJS

Repository files navigation

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 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.)

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://dev.yzsun.me/pyjs/

About

A minimal Python interpreter written in JavaScript

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published