tree_sitter_python/lib.rs
1//! This crate provides Python language support for the [tree-sitter] parsing library.
2//!
3//! Its ABI (`0x5742000d`) rejects upstream Tree-sitter runtimes and WillBooster runtimes prior to
4//! 22.0.0. Use this crate with [willbooster-tree-sitter] 23.0.0 or later within 23.x, the runtime
5//! line it is tested and fuzzed with.
6//!
7//! Typically, you will use the [`LANGUAGE`] constant to add this language to a
8//! tree-sitter [`Parser`], and then use the parser to parse some code:
9//!
10//! ```
11//! let code = "def double(x):\n return x * 2\n";
12//! let mut parser = tree_sitter::Parser::new();
13//! let language = tree_sitter_python::LANGUAGE;
14//! parser
15//! .set_language(&language.into())
16//! .expect("Error loading Python parser");
17//! let tree = parser.parse(code).unwrap();
18//! assert!(!tree.root_node().has_error());
19//! ```
20//!
21//! [`Parser`]: https://docs.rs/willbooster-tree-sitter/23.0.0/tree_sitter/struct.Parser.html
22//! [tree-sitter]: https://tree-sitter.github.io/
23//! [willbooster-tree-sitter]: https://crates.io/crates/willbooster-tree-sitter
24
25use tree_sitter_language::LanguageFn;
26
27unsafe extern "C" {
28 fn tree_sitter_python() -> *const ();
29}
30
31/// The tree-sitter [`LanguageFn`] for this grammar.
32pub const LANGUAGE: LanguageFn = unsafe { LanguageFn::from_raw(tree_sitter_python) };
33
34/// The content of the [`node-types.json`] file for this grammar.
35///
36/// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers/6-static-node-types
37pub const NODE_TYPES: &str = include_str!("../../src/node-types.json");
38
39#[cfg(test)]
40mod tests {
41 #[test]
42 fn test_can_load_grammar() {
43 let mut parser = tree_sitter::Parser::new();
44 parser
45 .set_language(&super::LANGUAGE.into())
46 .expect("Error loading Python parser");
47 }
48}