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