Trait rustpython_vm::compiler::parser::Parse
source · pub trait Parse: Sized {
// Required methods
fn lex_starts_at(
source: &str,
offset: TextSize
) -> SoftKeywordTransformer<Lexer<Chars<'_>>>;
fn parse_tokens(
lxr: impl IntoIterator<Item = Result<(Tok, TextRange), LexicalError>>,
source_path: &str
) -> Result<Self, BaseError<ParseErrorType>>;
// Provided methods
fn parse(
source: &str,
source_path: &str
) -> Result<Self, BaseError<ParseErrorType>> { ... }
fn parse_without_path(
source: &str
) -> Result<Self, BaseError<ParseErrorType>> { ... }
fn parse_starts_at(
source: &str,
source_path: &str,
offset: TextSize
) -> Result<Self, BaseError<ParseErrorType>> { ... }
}
Expand description
Parse Python code string to implementor’s type.
Example
For example, parsing a simple function definition and a call to that function:
use rustpython_parser::{self as parser, ast, Parse};
let source = r#"
def foo():
return 42
print(foo())
"#;
let program = ast::Suite::parse(source, "<embedded>");
assert!(program.is_ok());
Parsing a single expression denoting the addition of two numbers, but this time specifying a different, somewhat silly, location:
use rustpython_parser::{self as parser, ast, Parse, text_size::TextSize};
let expr = ast::Expr::parse_starts_at("1 + 2", "<embedded>", TextSize::from(400));
assert!(expr.is_ok());