Skip to content

noahpy/python-interpreter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

57 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Python Interpreter / Transpiler in OCaml

In order to learn OCaml (and more of Python), I chose this as my project. Still WIP. Lexes, parses, and evaluates a subset of Python including arithmetic, variables, lists, dicts, functions, and basic stdlib. It also supports higher-order functions and lazily evaluates expressions. Currently pass-by-copy, without references for data structures. To get a feel of what it can interpret, have a look at example.py.

Useage

To build, run:

dune build

To run a Python file, run:

dune exec python-interpreter test.py

If no arguments are provided, the interpreter will read from stdin:

cat test.py | dune exec python-interpreter

You can also directly invoke the generated binary in _build/install/default/bin/python-interpreter.

To run tests, run:

dune runtest

Tests use ppx_expect inline expect tests. Test files live in test/.

Architecture

The interpreter pipeline: Source → Lexer (ocamllex) → Parser (menhir) → AST → Evaluator.
The lexer and parser are generated by ocamllex and menhir respectively.

Implemented types

  • int, float, str, bool, None
  • list, dict

Implemented statements

  • assignment, function definition, sole expression
  • if, elif, else
  • for, while
  • pass, return

Implemented Built-in Functions

  • print, input
  • range, len
  • int, float, bool, str, list
  • binary operators: +, -, *, /, %, ==, !=, >, <, >=, <=, and, or, in, not not in
  • list and dictionary access: x[i], x[i]=y
  • list and string slicing: x[i:j], x[i:j:k], etc.
  • math utils: abs, pow, sqrt, min, max, sum

About

My small python interpreter / transpiler in Ocaml. Still WIP.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages