Skip to content
olegkorolPublic

About

A simple language implementation of Lox, written in Python. Includes a lexer, parser and interpreter.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

 

History

55 Commits

Folders and files

Repository files navigation

PyLox

image Image from Crafting Interpreters by Robert Nystrom

This is a language implementation of the Lox programming language, written in Python. It includes:

  • A lexer (aka. scanner)
  • An AST (Abstract Syntax Tree) parser
  • A tree-walk interpreter

The implementation is based on the book Crafting Interpreters by Robert Nystrom and was crafted with the help of the unit tests from the "Build your own Interpreter" challenge by CodeCrafters.

Grammar

Program Structure

program        → declaration* EOF ;

Declarations and Statements

declaration    → funDecl
               | varDecl
               | statement ;

funDecl        → "fun" function ;
function       → IDENTIFIER "(" parameters? ")" block ;
parameters     → IDENTIFIER ( "," IDENTIFIER )* ;

varDecl        → "var" IDENTIFIER ( "=" expression )? ";" ;

statement      → exprStmt
               | forStmt
               | ifStmt
               | printStmt
               | returnStmt
               | whileStmt
               | block ;

block          → "{" declaration* "}" ;
exprStmt       → expression ";" ;
forStmt        → "for" "(" ( varDecl | exprStmt | ";" )
                 expression? ";"
                 expression? ")" statement ;
ifStmt         → "if" "(" expression ")" statement
                 ( "else" statement )? ;
printStmt      → "print" expression ";" ;
returnStmt     → "return" expression? ";" ;
whileStmt      → "while" "(" expression ")" statement ;

Expressions

expression     → assignment ;
assignment     → IDENTIFIER "=" assignment
               | logic_or ;
logic_or       → logic_and ( "or" logic_and )* ;
logic_and      → equality ( "and" equality )* ;
equality       → comparison ( ( "!=" | "==" ) comparison )* ;
comparison     → term ( ( ">" | ">=" | "<" | "<=" ) term )* ;
term           → factor ( ( "-" | "+" ) factor )* ;
factor         → unary ( ( "/" | "*" ) unary )* ;
unary          → ( "!" | "-" ) unary | call ;
call           → primary ( "(" arguments? ")" )* ;
primary        → NUMBER | STRING | "true" | "false" | "nil" | "(" expression ")" | IDENTIFIER ;

arguments      → expression ( "," expression )* ;

Usage

Write your code in e.g. test.lox and run it with:

./lox.sh run test.lox

About

A simple language implementation of Lox, written in Python. Includes a lexer, parser and interpreter.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages