tree_sitter_r/
lib.rs

1//! This crate provides R language support for the [tree-sitter] parsing library.
2//!
3//! Typically, you will use the [`LANGUAGE`] constant to add this language to a
4//! tree-sitter [`Parser`], and then use the parser to parse some code:
5//!
6//! ```
7//! let code = r#"
8//! "#;
9//! let mut parser = tree_sitter::Parser::new();
10//! let language = tree_sitter_r::LANGUAGE;
11//! parser
12//!     .set_language(&language.into())
13//!     .expect("Error loading R parser");
14//! let tree = parser.parse(code, None).unwrap();
15//! assert!(!tree.root_node().has_error());
16//! ```
17//!
18//! [`Parser`]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
19//! [tree-sitter]: https://tree-sitter.github.io/
20
21use tree_sitter_language::LanguageFn;
22
23extern "C" {
24    fn tree_sitter_r() -> *const ();
25}
26
27/// The tree-sitter [`LanguageFn`] for this grammar.
28pub const LANGUAGE: LanguageFn = unsafe { LanguageFn::from_raw(tree_sitter_r) };
29
30/// The content of the [`node-types.json`] file for this grammar.
31///
32/// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types
33pub const NODE_TYPES: &str = include_str!("../../src/node-types.json");
34
35pub const HIGHLIGHTS_QUERY: &str = include_str!("../../queries/highlights.scm");
36// pub const INJECTIONS_QUERY: &str = include_str!("../../queries/injections.scm");
37pub const LOCALS_QUERY: &str = include_str!("../../queries/locals.scm");
38pub const TAGS_QUERY: &str = include_str!("../../queries/tags.scm");
39
40#[cfg(test)]
41mod tests {
42    #[test]
43    fn test_can_load_grammar() {
44        let mut parser = tree_sitter::Parser::new();
45        parser
46            .set_language(&super::LANGUAGE.into())
47            .expect("Error loading R parser");
48    }
49
50    // See https://github.com/tree-sitter/tree-sitter/issues/2767
51    #[test]
52    fn test_tree_cursor() {
53        let mut parser = tree_sitter::Parser::new();
54        parser.set_language(&super::LANGUAGE.into()).unwrap();
55
56        // This is an `identifier`
57        let text = "foo";
58
59        let tree = parser.parse(text, None).unwrap();
60
61        let mut cursor = tree.walk();
62        assert_eq!(cursor.node().kind(), "program");
63
64        // program -> identifier
65        assert!(cursor.goto_first_child());
66        assert_eq!(cursor.node().kind(), "identifier");
67        assert_eq!(cursor.node().utf8_text(text.as_bytes()).unwrap(), "foo");
68
69        assert!(!cursor.goto_first_child());
70        assert_eq!(cursor.node().kind(), "identifier");
71        assert_eq!(cursor.node().utf8_text(text.as_bytes()).unwrap(), "foo");
72
73        assert!(!cursor.goto_last_child());
74        assert_eq!(cursor.node().kind(), "identifier");
75        assert_eq!(cursor.node().utf8_text(text.as_bytes()).unwrap(), "foo");
76    }
77}