|
| 1 | +# RustPython/parser |
| 2 | + |
| 3 | +This directory has the code for python lexing, parsing and generating Abstract Syntax Trees (AST). |
| 4 | + |
| 5 | +The steps are: |
| 6 | +- Lexical analysis: splits the source code into tokens. |
| 7 | +- Parsing and generating the AST: transforms those tokens into an AST. Uses `LALRPOP`, a Rust parser generator framework. |
| 8 | + |
| 9 | +This crate is published on [https://docs.rs/rustpython-parser](https://docs.rs/rustpython-parser). |
| 10 | + |
| 11 | +We wrote [a blog post](https://rustpython.github.io/featured/2020/03/11/thing-explainer-parser.html) with screenshots and an explanation to help you understand the steps by seeing them in action. |
| 12 | + |
| 13 | +For more information on LALRPOP, here is a link to the [LALRPOP book](https://github.com/lalrpop/lalrpop). |
| 14 | + |
| 15 | +There is a readme in the `src` folder with the details of each file. |
| 16 | + |
| 17 | + |
| 18 | +## Directory content |
| 19 | + |
| 20 | +`build.rs`: The build script. |
| 21 | +`Cargo.toml`: The config file. |
| 22 | + |
| 23 | +The `src` directory has: |
| 24 | + |
| 25 | +**lib.rs** |
| 26 | +This is the crate's root. |
| 27 | + |
| 28 | +**lexer.rs** |
| 29 | +This module takes care of lexing python source text. This means source code is translated into separate tokens. |
| 30 | + |
| 31 | +**parser.rs** |
| 32 | +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. |
| 33 | + |
| 34 | +**ast.rs** |
| 35 | + Implements abstract syntax tree (AST) nodes for the python language. Roughly equivalent to [the python AST](https://docs.python.org/3/library/ast.html). |
| 36 | + |
| 37 | +**python.lalrpop** |
| 38 | +Python grammar. |
| 39 | + |
| 40 | +**token.rs** |
| 41 | +Different token definitions. Loosely based on token.h from CPython source. |
| 42 | + |
| 43 | +**errors.rs** |
| 44 | +Define internal parse error types. The goal is to provide a matching and a safe error API, masking errors from LALR. |
| 45 | + |
| 46 | +**fstring.rs** |
| 47 | +Format strings. |
| 48 | + |
| 49 | +**function.rs** |
| 50 | +Collection of functions for parsing parameters, arguments. |
| 51 | + |
| 52 | +**location.rs** |
| 53 | +Datatypes to support source location information. |
| 54 | + |
| 55 | +**mode.rs** |
| 56 | +Execution mode check. Allowed modes are `exec`, `eval` or `single`. |
| 57 | + |
| 58 | + |
| 59 | +## How to use |
| 60 | + |
| 61 | +For example, one could do this: |
| 62 | +``` |
| 63 | + use rustpython_parser::{parser, ast}; |
| 64 | + let python_source = "print('Hello world')"; |
| 65 | + let python_ast = parser::parse_expression(python_source).unwrap(); |
| 66 | +``` |
0 commit comments