Skip to content
/ tslox Public

An interpreter of the Lox scripting language, implemented in TypeScript

License

Notifications You must be signed in to change notification settings

zlliang/tslox

Repository files navigation

TSLox

An interpreter of the Lox scripting language, implemented in TypeScript.

Lox is a tiny scripting language described in Bob Nystrom's book Crafting Interpreters. Following Part II of the book, I complete a tree-walk interpreter of Lox using TypeScript, as a writing-an-interpreter-from-scratch exercise.

Going on reading Part III of the book, I also implement the second version of Lox interpreter using C, It is a bytecode virtual machine. See zlliang/clox.

Usage

Clone this repository, and run the CLI as:

$ pnpm tslox # Or `yarn tslox` / `npm run tslox`

For detailed usages, see the help message:

tslox v0.0.0-20211215
Usage:

  tslox [--verbose]            Run tslox REPL (Add '--verbose' to show AST)
  tslox <script> [--verbose]   Run a specified script file (Add '--verbose' to show AST)
  tslox -v, --version          Show version info
  tslox -h, --help             Show this help message

Also, feel free to run examples in the examples directory:

$ pnpm tslox examples/hello-world.lox
Hello, world!

Features

  1. REPL that allows Lox expressions. This is a challenge in Chapter 8 of the book. In REPL mode, one can input zero or more statements (ending with ';') and maybe an expression. The interpreter executes all the statements. If there is an expression, the REPL evaluates and prints its value.

    [tslox]> var a = 3; a + 3
    6
    
    [tslox]> print a / 8;
    0.375
    
    [tslox]> a + 25
    28
    
  2. Verbose mode that prints both ASTs and outputs. In Chapter 5 of the book, a utility class AstPrinter is created to print parsed Lox ASTs as S-expressions. TSLox basically adds all of the visit methods, and shows ASTs alongside script outputs, when the --verbose flag is enabled.

    $ pnpm tslox -- --verbose
    
    [tslox]> fun greet() { return "Hello, world!"; }  print greet();
    [AST]
    (fun greet
      (block
        (return "Hello, world!")))
    (print (call greet))
    
    [Output]
    Hello, world!
    

Disclaimer

Code structures and some implementation details of TSLox are different from the original jlox version. Since I read the book just for learning and exercising, I didn't write any test for TSLox. Bugs may occur. If you find one, please feel free to open an issue! :)

Resources

About

An interpreter of the Lox scripting language, implemented in TypeScript

Topics

Resources

License

Stars

Watchers

Forks