6 releases

0.3.1 Apr 6, 2024
0.3.0 Aug 29, 2023
0.2.0 Jan 11, 2023
0.1.2 Jun 21, 2020
0.1.0 Jul 7, 2019

#30 in Programming languages

Download history 508/week @ 2023-12-23 436/week @ 2023-12-30 754/week @ 2024-01-06 688/week @ 2024-01-13 816/week @ 2024-01-20 725/week @ 2024-01-27 716/week @ 2024-02-03 741/week @ 2024-02-10 671/week @ 2024-02-17 618/week @ 2024-02-24 695/week @ 2024-03-02 1919/week @ 2024-03-09 803/week @ 2024-03-16 544/week @ 2024-03-23 556/week @ 2024-03-30 720/week @ 2024-04-06

2,769 downloads per month
Used in 24 crates (17 directly)

MIT and LGPL-3.0-only

3MB
79K SLoC

RustPython/parser

This directory has the code for python lexing, parsing and generating Abstract Syntax Trees (AST).

The steps are:

  • Lexical analysis: splits the source code into tokens.
  • Parsing and generating the AST: transforms those tokens into an AST. Uses LALRPOP, a Rust parser generator framework.

This crate is published on https://docs.rs/rustpython-parser.

We wrote a blog post with screenshots and an explanation to help you understand the steps by seeing them in action.

For more information on LALRPOP, here is a link to the LALRPOP book.

There is a readme in the src folder with the details of each file.

Directory content

build.rs: The build script. Cargo.toml: The config file.

The src directory has:

lib.rs
This is the crate's root.

lexer.rs
This module takes care of lexing python source text. This means source code is translated into separate tokens.

parser.rs
A python parsing module. Use this module to parse python code into an AST. There are three ways to parse python code. You could parse a whole program, a single statement, or a single expression.

ast.rs
Implements abstract syntax tree (AST) nodes for the python language. Roughly equivalent to the python AST.

python.lalrpop
Python grammar.

token.rs
Different token definitions. Loosely based on token.h from CPython source.

errors.rs
Define internal parse error types. The goal is to provide a matching and a safe error API, masking errors from LALR.

fstring.rs
Format strings.

function.rs
Collection of functions for parsing parameters, arguments.

location.rs
Datatypes to support source location information.

mode.rs
Execution mode check. Allowed modes are exec, eval or single.

How to use

For example, one could do this:

  use rustpython_parser::{Parse, ast};
  let python_source = "print('Hello world')";
  let python_statements = ast::Suite::parse(python_source).unwrap();  // statements
  let python_expr = ast::Expr::parse(python_source).unwrap();  // or expr

Dependencies

~10MB
~181K SLoC