tree_sitter_postgres/lib.rs
1//! This crate provides PostgreSQL and PL/pgSQL language support for the
2//! [tree-sitter][] parsing library.
3//!
4//! Typically, you will use the [LANGUAGE][] constant to add the PostgreSQL SQL
5//! grammar to a tree-sitter [Parser][], and [LANGUAGE_PLPGSQL][] for PL/pgSQL:
6//!
7//! ```
8//! let code = r#"
9//! "#;
10//! let mut parser = tree_sitter::Parser::new();
11//! let language = tree_sitter_postgres::LANGUAGE;
12//! parser
13//! .set_language(&language.into())
14//! .expect("Error loading Postgres parser");
15//! let tree = parser.parse(code, None).unwrap();
16//! assert!(!tree.root_node().has_error());
17//! ```
18//!
19//! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
20//! [tree-sitter]: https://tree-sitter.github.io/
21
22use tree_sitter_language::LanguageFn;
23
24unsafe extern "C" {
25 fn tree_sitter_postgres() -> *const ();
26 fn tree_sitter_plpgsql() -> *const ();
27}
28
29/// The tree-sitter [`LanguageFn`] for the PostgreSQL SQL grammar.
30pub const LANGUAGE: LanguageFn = unsafe { LanguageFn::from_raw(tree_sitter_postgres) };
31
32/// The tree-sitter [`LanguageFn`] for the PL/pgSQL grammar.
33pub const LANGUAGE_PLPGSQL: LanguageFn = unsafe { LanguageFn::from_raw(tree_sitter_plpgsql) };
34
35/// The content of the [`node-types.json`][] file for the PostgreSQL grammar.
36pub const NODE_TYPES: &str = include_str!("../../postgres/src/node-types.json");
37
38/// The content of the [`node-types.json`][] file for the PL/pgSQL grammar.
39pub const NODE_TYPES_PLPGSQL: &str = include_str!("../../plpgsql/src/node-types.json");
40
41#[cfg(test)]
42mod tests {
43 #[test]
44 fn test_can_load_grammar() {
45 let mut parser = tree_sitter::Parser::new();
46 parser
47 .set_language(&super::LANGUAGE.into())
48 .expect("Error loading Postgres parser");
49 }
50
51 #[test]
52 fn test_can_load_plpgsql_grammar() {
53 let mut parser = tree_sitter::Parser::new();
54 parser
55 .set_language(&super::LANGUAGE_PLPGSQL.into())
56 .expect("Error loading PL/pgSQL parser");
57 }
58}