### CMake Configuration File and Installation Rules Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/CMakeLists.txt Configures the `tree-sitter-rust.pc` file using a template and the current binary directory. It then defines installation rules for the header file, the pkgconfig file, and the built library. ```cmake configure_file(bindings/c/tree-sitter-rust.pc.in "${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-rust.pc" @ONLY) include(GNUInstallDirs) install(FILES bindings/c/tree-sitter-rust.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/tree_sitter") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-rust.pc" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig") install(TARGETS tree-sitter-rust LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") ``` -------------------------------- ### Rust For Expression - Code and AST Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Provides examples of Rust 'for' loops, including iterating over a collection, a range, and nested loops with labels and continue statements. The corresponding Abstract Syntax Trees (ASTs) are shown, detailing the iteration variable, the collection or range, and the loop body. The ASTs also represent labels and continue expressions. ```rust for e in v { bar(e); } for i in 0..256 { bar(i); } 'outer: for x in 0..10 { 'inner: for y in 0..10 { if x % 2 == 0 { continue 'outer; } if y % 2 == 0 { continue 'inner; } } } ``` ```tree-sitter grammar (source_file (expression_statement (for_expression (identifier) (identifier) (block (expression_statement (call_expression (identifier) (arguments (identifier))))))) (expression_statement (for_expression (identifier) (range_expression (integer_literal) (integer_literal)) (block (expression_statement (call_expression (identifier) (arguments (identifier))))))) (expression_statement (for_expression (label (identifier)) (identifier) (range_expression (integer_literal) (integer_literal)) (block (expression_statement (for_expression (label (identifier)) (identifier) (range_expression (integer_literal) (integer_literal)) (block ...) ``` -------------------------------- ### Rust If Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Provides examples of if, else if, and else constructs in Rust, including nested conditional logic and if expressions used in variable assignments. It also demonstrates simple boolean conditions. ```rust fn main() { if n == 1 { } else if n == 2 { } else { } } let y = if x == 5 { 10 } else { 15 }; if foo && bar {} if foo && bar || baz {} ``` -------------------------------- ### Rust Reference Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Shows how reference expressions are parsed in Rust, covering immutable borrows (`&`), mutable borrows (`&mut`), and raw borrows (`&raw`, `&raw mut`). Examples include borrowing simple identifiers and fields of `self`. ```rust &a; &mut self.name; &raw const b; &raw mut self.age; (source_file (expression_statement (reference_expression (identifier))) (expression_statement (reference_expression (mutable_specifier) (field_expression (self) (field_identifier)))) (expression_statement (reference_expression (identifier))) (expression_statement (reference_expression (mutable_specifier) (field_expression (self) (field_identifier))))) ``` -------------------------------- ### Rust Try Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates the parsing of try expressions (`?`) in Rust, used for error propagation. Examples include applying the `?` operator to a method call on an identifier and to a simple identifier. ```rust a.unwrap()?; &a?; (source_file (expression_statement (try_expression (call_expression (field_expression (identifier) (field_identifier)) (arguments)))) (expression_statement (reference_expression (try_expression (identifier))))) ``` -------------------------------- ### Rust If Let Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Illustrates various forms of 'if let' expressions in Rust, including matching tuples, chaining conditions with '&&', and using closures. ```rust if let ("Bacon", b) = dish { } ``` ```rust if let Some("chained") = a && b && let (C, D) = e { } ``` ```rust if foo && let bar = || baz && quux {} ``` ```rust if a && let b = || c || d && e {} ``` -------------------------------- ### Rust Tuple Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates the syntax for creating and destructuring tuple expressions in Rust. This includes empty tuples, single-element tuples, and multi-element tuples used in variable assignments. ```rust (); (0,); let (x, y, z) = (1, 2, 3); ``` -------------------------------- ### Rust Macro Invocation - No Arguments Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/macros.txt Illustrates basic macro invocations in Rust, including those with simple identifiers and scoped identifiers. These examples show the structure of macro calls without any arguments. ```rust a!(); b![]; c!{}; d::e!(); f::g::h!{}; ``` -------------------------------- ### Rust Grouped Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates the parsing of grouped expressions in Rust using parentheses. This includes simple grouping of literals and nested grouping of binary operations. ```rust (0); (2 * (3 + 4)); (source_file (expression_statement (parenthesized_expression (integer_literal))) (expression_statement (parenthesized_expression (binary_expression (integer_literal) (parenthesized_expression (binary_expression (integer_literal) (integer_literal))))))) ``` -------------------------------- ### Rust Match Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Provides examples of 'match' expressions in Rust, a powerful control flow operator that allows comparing a value against a series of patterns and executing code based on the match. It covers simple literals, ranges, attributes, macros, and complex conditional matching. ```rust match x { 1 => { "one" } 2 => "two", -1 => 1, -3.14 => 3, #[attr1] 3 => "three", macro!(4) => "four", _ => "something else", } ``` ```rust let msg = match x { 0 | 1 | 10 => "one of zero, one, or ten", y if y < 20 => "less than 20, but not zero, one, or ten", y if y == 200 => if a { "200 (but this is not very stylish)" } y if let Some(z) = foo && z && let Some(w) = bar => "very chained", _ => "something else", }; ``` -------------------------------- ### Rust Struct Expressions with Update Initializers Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Shows how to create a new struct instance by updating fields from an existing struct instance in Rust. This is useful for creating modified copies of structs. ```rust let u = User{name, ..current_user()}; ``` -------------------------------- ### Rust Struct Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Illustrates various ways to define and initialize struct instances in Rust. This covers empty structs, structs with named fields, shorthand field initializers, scoped types, and initialization using integer literals for fields. ```rust NothingInMe {}; Point {x: 10.0, y: 20.0}; let a = SomeStruct { field1, field2: expression, field3, }; let u = game::User {name: "Joe", age: 35, score: 100_000}; let i = Instant { 0: Duration::from_millis(0) }; ``` -------------------------------- ### Rust Basic If Let Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates the basic 'if let' syntax in Rust, which allows pattern matching within conditional statements. This is useful for destructuring enums like Option. ```rust if let Some(a) = b && c && d && let Some(e) = f { } ``` -------------------------------- ### Closures with Typed Parameters in Rust Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates Rust closures where parameter types are explicitly annotated. This improves code clarity and can help the compiler with type inference, especially in complex scenarios. ```rust a.map(|b: usize| b.push(c)); ``` -------------------------------- ### Rust Loop Expression - Code and AST Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Illustrates nested Rust 'loop' expressions with labels and break statements, along with their Abstract Syntax Tree (AST). The example shows breaking out of the inner loop and the outer loop using labels, as well as a simple break. The AST captures the labels, nested blocks, and break expressions. ```rust 'outer: loop { 'inner: loop { break 'outer; break true; } } ``` ```tree-sitter grammar (source_file (expression_statement (loop_expression (label (identifier)) (block (expression_statement (loop_expression (label (identifier)) (block (expression_statement (break_expression (label (identifier)))) (expression_statement (break_expression (boolean_literal)))))))))) ``` -------------------------------- ### Rust Assignment Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates the parsing of simple assignment expressions in Rust, where a value is assigned to an identifier. This covers the basic `identifier = identifier;` syntax. ```tree-sitter-grammar (source_file (expression_statement (assignment_expression left: (identifier) right: (identifier)))) ``` -------------------------------- ### Rust Unary Operator Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Illustrates the parsing of unary operator expressions in Rust, including negation (`-`), logical NOT (`!`), and dereferencing (`*`). Each example shows a simple expression with a unary operator applied to an identifier. ```rust -num; !bits; *boxed_thing; (source_file (expression_statement (unary_expression (identifier))) (expression_statement (unary_expression (identifier))) (expression_statement (unary_expression (identifier)))) ``` -------------------------------- ### Generator Closure in Rust Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Presents a generator closure in Rust, which uses the `yield` keyword to produce a sequence of values. This example includes a `while` loop and a `return` statement within the generator. ```rust move || { while i <= n { yield i; i += 1; } return; }; ``` -------------------------------- ### Rust Macro Definition - Repetition and Optional Arguments Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/macros.txt Illustrates advanced `macro_rules!` features in Rust, including repetition (`$()*`) and optional arguments (`$?`). These examples show how to define macros that handle varying numbers of inputs. ```rust macro_rules! o_O { ( $($x:expr; [ $( $y:expr ),* ]);* ) => { $($($x + $e),*),* } } macro_rules! zero_or_one { ($($e:expr),?) => { $($e),? }; } macro_rules! empty [ () => {}; ]; ``` -------------------------------- ### Rust Macro Definition - Basic Rules Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/macros.txt Defines simple Rust macros using `macro_rules!`. Examples include macros with no arguments that print a string, and macros that evaluate simple arithmetic expressions. ```rust macro_rules! say_hello { () => ( println!("Hello!"); ) } macro_rules! four { () => {1 + 3}; } ``` -------------------------------- ### Rust Type Cast Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Shows how type cast expressions are parsed in Rust, using the `as` keyword. This includes casting literals, identifiers, and results of complex expressions to primitive types. ```tree-sitter-grammar (source_file (expression_statement (type_cast_expression value: (integer_literal) type: (primitive_type))) (let_declaration pattern: (identifier) value: (type_cast_expression value: (identifier) type: (primitive_type))) (let_declaration pattern: (identifier) type: (primitive_type) value: (binary_expression left: (binary_expression left: (float_literal) right: (type_cast_expression value: (unary_expression (call_expression function: (identifier) arguments: (arguments (identifier)))) type: (primitive_type))) right: (float_literal)))) ``` -------------------------------- ### Rust Macro Invocation - With Comments Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/macros.txt Shows how comments, both line and block comments, can be included within a Rust macro invocation's token tree. The parser correctly handles these comments. ```rust ok! { // one /* two */ } ``` -------------------------------- ### Rust While Let Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Shows the 'while let' construct in Rust, which repeatedly executes a block as long as a pattern matches. This is commonly used for iterating over sequences or consuming data structures. ```rust while let ("Bacon", b) = dish { } ``` -------------------------------- ### Rust Binary Operator Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Illustrates the parsing of various binary operator expressions in Rust. This includes arithmetic (`*`, `/`, `%`, `+`, `-`), shift (`>>`, `<<`), equality (`==`), and logical (`&&`, `||`) operators. ```rust a * b; a / b; a % b; a + b; a - b; a >> b; a << b; a == b; a && b; a || b; (source_file (expression_statement (binary_expression (identifier) (identifier))) (expression_statement (binary_expression (identifier) (identifier))) (expression_statement (binary_expression (identifier) (identifier))) (expression_statement (binary_expression (identifier) (identifier))) (expression_statement (binary_expression (identifier) (identifier))) (expression_statement (binary_expression (identifier) (identifier))) (expression_statement (binary_expression (identifier) (identifier))) (expression_statement (binary_expression (identifier) (identifier))) (expression_statement (binary_expression (identifier) (identifier))) (expression_statement (binary_expression (identifier) (identifier)))) ``` -------------------------------- ### Rust Identifiers: Basic and Raw Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates the parsing of basic and raw identifiers in Rust. Raw identifiers allow the use of keywords as identifiers by prefixing them with `r#`. This section shows simple identifier usage and more complex field access with raw identifiers. ```rust fn main() { abc; } (source_file (function_item (identifier) (parameters) (block (expression_statement (identifier))))) fn main() { (r#abc as r#Def).r#ghi; } (source_file (function_item (identifier) (parameters) (block (expression_statement (field_expression (parenthesized_expression (type_cast_expression (identifier) (type_identifier))) (field_identifier)))))) ``` -------------------------------- ### Rust Range Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Illustrates the parsing of various range expressions in Rust. This covers full ranges, open-ended ranges, ranges with literals and identifiers, and ranges used within `for` loops. ```rust 1..2; 3..; ..4; ..; 1..b; a..b; 1..(1); (1)..1; (1)..(1); 1..{1}; for i in 1.. { } (source_file (expression_statement (range_expression)) (expression_statement (range_expression)) (expression_statement (range_expression)) (expression_statement (range_expression)) (expression_statement (range_expression)) (expression_statement (range_expression)) (expression_statement (range_expression)) (expression_statement (range_expression)) (expression_statement (range_expression)) (expression_statement (range_expression)) (for_statement (range_expression))) ``` -------------------------------- ### Rust Async Closure Declaration Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/async.txt Provides an example of declaring an asynchronous closure in Rust, which returns a unit type. ```rust let _ = async || (); ``` -------------------------------- ### Rust Macro Definition - Pattern Matching Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/macros.txt Demonstrates Rust macros defined with `macro_rules!` that use pattern matching on the input. This includes matching specific identifiers and expression fragments (`$e:expr`). ```rust macro_rules! foo { (x => $e:expr) => (println!("mode X: {}", $e)); (y => $e:expr) => (println!("mode Y: {}", $e)) } ``` -------------------------------- ### Generic Function Calls in Rust Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Illustrates calling generic functions in Rust, specifying type arguments using angle brackets. This includes calls to standard library functions like `sizeof` and custom generic functions. ```rust std::sizeof::(); foo::<8>(); ``` -------------------------------- ### Closure Expressions in Rust Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Shows various forms of closure expressions in Rust, including closures with tuple parameters, closures with `move` semantics, and closures with explicit return types. These are fundamental for functional programming patterns. ```rust a.map(|(b, c)| b.push(c)); d.map(move |mut e| { f(e); g(e) }); h(|| -> i { j }); ``` -------------------------------- ### Rust Call Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Documents the parsing of function call expressions in Rust, including calls with no arguments, multiple arguments, and trailing commas in argument lists. It covers basic function invocation syntax. ```tree-sitter-grammar (source_file (expression_statement (call_expression function: (identifier) arguments: (arguments))) (expression_statement (call_expression function: (identifier) arguments: (arguments (integer_literal) (integer_literal)))) (expression_statement (call_expression function: (identifier) arguments: (arguments (integer_literal) (integer_literal))))) ``` -------------------------------- ### Rust Trait Implementation Example Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/declarations.txt Shows a basic Rust trait implementation, specifically for the `Iterator` trait with a lifetime parameter, and a conversion trait from `i32` to `i64`. ```Rust impl<'a> iter::Iterator for Self::Iter<'a> { } impl ConvertTo for i32 { fn convert(&self) -> i64 { *self as i64 } } ``` -------------------------------- ### Rust While Expression - Code and AST Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates a basic Rust 'while' loop and its corresponding Abstract Syntax Tree (AST) representation. The loop continues as long as the 'done' condition is false, setting 'done' to true upon execution. The AST shows the condition and the body of the while loop. ```rust while !done { done = true; } ``` ```tree-sitter grammar (source_file (expression_statement (while_expression condition: (unary_expression (identifier)) body: (block (expression_statement (assignment_expression left: (identifier) right: (boolean_literal))))))) ``` -------------------------------- ### Rust Array Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Details the parsing of array expressions in Rust. This includes empty arrays, arrays with literal elements, arrays initialized with a default value and a length, and arrays with conditional compilation attributes. ```tree-sitter-grammar (source_file (expression_statement (array_expression)) (expression_statement (array_expression (integer_literal) (integer_literal) (integer_literal))) (expression_statement (array_expression (string_literal (string_content)) (string_literal (string_content)) (string_literal (string_content)))) (expression_statement (array_expression (integer_literal) length: (integer_literal))) (expression_statement (array_expression (attribute_item (attribute (identifier) arguments: (token_tree (identifier)))) (string_literal ``` -------------------------------- ### Rust Macro Invocation - Arbitrary Tokens Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/macros.txt Demonstrates Rust macro invocations with a wide variety of tokens within the macro's token tree. This includes operators, character literals, ranges, lifetimes, and special characters like '$'. ```rust a!(* a *); a!(& a &); a!(- a -); a!(b + c + +); a!('a'..='z'); a!('\u{0}'..='\u{2}'); a!('lifetime) default!(a); union!(a); a!($); a!($()); a!($ a $); a!(${$([ a ])}); a!($a $a:ident $($a);*); ``` -------------------------------- ### Rust Range Expressions Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Covers the parsing of range expressions in Rust, which are used for creating ranges between two values. This includes ranges with two integers, a single integer, identifiers, parenthesized expressions, and blocks. ```tree-sitter-grammar (source_file (expression_statement (range_expression (integer_literal) (integer_literal))) (expression_statement (range_expression (integer_literal))) (expression_statement (range_expression (integer_literal))) (expression_statement (range_expression)) (expression_statement (range_expression (integer_literal) (identifier))) (expression_statement (range_expression (identifier) (identifier))) (expression_statement (range_expression (integer_literal) (parenthesized_expression (integer_literal)))) (expression_statement (range_expression (parenthesized_expression (integer_literal)) (integer_literal))) (expression_statement (range_expression (parenthesized_expression (integer_literal)) (parenthesized_expression (integer_literal)))) (expression_statement (range_expression (integer_literal) (block (integer_literal)))) (expression_statement (for_expression (identifier) (range_expression (integer_literal)) (block)))) ``` -------------------------------- ### Raw Reference Expression Conflicts in Rust Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Illustrates scenarios involving raw reference expressions in Rust, particularly when combined with `const` or within function calls. This highlights potential syntax ambiguities or specific usage patterns that the grammar needs to parse correctly. ```rust some_call(&raw); let a = &raw const b; ``` -------------------------------- ### Rust Match Expression with Tuple Struct Or Patterns Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/patterns.txt Provides an example of using or patterns with tuple structs within a Rust match expression. This allows matching against different tuple struct variants. ```rust if let x!() | y!() = () {} ``` -------------------------------- ### Scoped Identifier with Nested Super in Rust Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates a scoped identifier that navigates up the module hierarchy using nested 'super' keywords, followed by a function call. This is common in Rust for accessing items in parent modules. ```rust super::super::foo(); ``` -------------------------------- ### Inline Const Blocks as Expressions in Rust Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Demonstrates the usage of inline `const` blocks as expressions in Rust. These blocks allow for constant evaluation within expressions, such as initializing arrays or within conditional statements. Note that the exact syntax and support may vary with Rust versions. ```rust const { 1 + 3 }; if *x < 0 { const { &4i32.pow(4) } } else { x } let three_ranges = [const { (0..=5).into_inner() }; 3]; ``` -------------------------------- ### Unsafe Block for FFI or Low-Level Operations in Rust Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Illustrates the use of an `unsafe` block in Rust. These blocks are required for operations that the Rust compiler cannot guarantee are memory-safe, such as calling external C functions or dereferencing raw pointers. ```rust const a : A = unsafe { foo() }; ``` -------------------------------- ### Rust Trait Impl Signature with Generics and Bounds Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/declarations.txt Provides examples of Rust trait implementation signatures, showcasing generic type parameters with trait bounds like `Debug` and `Ord` for types such as `OccupiedError`. ```Rust impl Debug for OccupiedError; impl Display for OccupiedError; ``` -------------------------------- ### Rust Index Expressions Parsing with Tree-sitter Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Parses Rust index expressions, used for accessing elements within arrays, tuples, or other indexable collections. It covers indexing with integer literals, identifiers, and nested structures. ```tree-sitter grammar (source_file (expression_statement (index_expression (parenthesized_expression (array_expression (integer_literal) (integer_literal) (integer_literal) (integer_literal))) (integer_literal))) (expression_statement (index_expression (identifier) (integer_literal))) (expression_statement (index_expression (identifier) (identifier)))) ``` -------------------------------- ### Rust Method Call Expressions Parsing with Tree-sitter Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Parses Rust method call expressions, where a method is invoked on a struct instance. This rule specifically captures the syntax of calling a method using dot notation. ```tree-sitter grammar (source_file (expression_statement (call_expression (field_expression (identifier) (field_identifier)) (arguments)))) ``` -------------------------------- ### Rust Match Expression AST Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Abstract Syntax Tree (AST) representation of a Rust match expression. This snippet illustrates the structure of match arms, patterns (including macro invocations, or patterns, and identifiers with conditions), and the values associated with each arm, which can be string literals or if expressions. ```tree-sitter grammar (source_file (expression_statement (match_expression value: (identifier) body: (match_block (match_arm pattern: (match_pattern (integer_literal)) value: (string_literal (string_content))) (match_arm pattern: (match_pattern (macro_invocation macro: (identifier) (token_tree (integer_literal)))) value: (string_literal (string_content))) (match_arm pattern: (match_pattern) value: (string_literal (string_content)))))) (let_declaration pattern: (identifier) value: (match_expression value: (identifier) body: (match_block (match_arm pattern: (match_pattern (or_pattern (or_pattern (integer_literal) (integer_literal)) (integer_literal))) value: (string_literal (string_content))) (match_arm pattern: (match_pattern (identifier) condition: (binary_expression left: (identifier) right: (integer_literal))) value: (string_literal (string_content))) (match_arm pattern: (match_pattern (identifier) condition: (binary_expression left: (identifier) right: (integer_literal))) value: (if_expression condition: (identifier) consequence: (block (string_literal (string_content)))))) (match_arm pattern: (match_pattern (identifier) condition: (let_chain (let_condition pattern: (tuple_struct_pattern type: (identifier) (identifier)) value: (identifier)) (identifier) (let_condition pattern: (tuple_struct_pattern type: (identifier) (identifier)) value: (identifier)))) value: (string_literal (string_content))) (match_arm pattern: (match_pattern) value: (string_literal (string_content))))))) ``` -------------------------------- ### Parse Rust Code with Python Tree-sitter Source: https://context7.com/tree-sitter/tree-sitter-rust/llms.txt Illustrates using the tree-sitter-rust Python package to parse Rust code. It shows how to load the Rust language, configure the parser, inspect the syntax tree, find specific code constructs like structs, and perform incremental parsing. It also accesses query files for syntax highlighting and symbol tagging. Dependencies include 'tree-sitter' and 'tree-sitter-rust' Python packages. ```python import tree_sitter_rust from tree_sitter import Language, Parser # Load the Rust language rust_language = Language(tree_sitter_rust.language()) # Create and configure the parser parser = Parser(rust_language) # Sample Rust code with various language features source_code = b''' #![allow(dead_code)] use std::sync::{Arc, Mutex}; /// A thread-safe counter implementation pub struct Counter { value: Arc>, } impl Counter { pub fn new() -> Self { Counter { value: Arc::new(Mutex::new(0)), } } pub async fn increment(&self) -> i64 { let mut guard = self.value.lock().unwrap(); *guard += 1; *guard } } #[cfg(test)] mod tests { use super::*; #[test] fn test_counter() { let counter = Counter::new(); assert_eq!(counter.value.lock().unwrap(), &0); } } ''' # Parse the source code tree = parser.parse(source_code) root_node = tree.root_node # Check for syntax errors print(f"Parse successful: {not root_node.has_error}") # True # Navigate the syntax tree print(f"Root type: {root_node.type}") # 'source_file' print(f"Child count: {root_node.child_count}") # Multiple children # Find all struct definitions def find_structs(node): structs = [] if node.type == 'struct_item': name_node = node.child_by_field_name('name') if name_node: structs.append(name_node.text.decode('utf-8')) for child in node.children: structs.extend(find_structs(child)) return structs print(f"Structs found: {find_structs(root_node)}") # ['Counter'] # Access query files for syntax highlighting highlights = tree_sitter_rust.HIGHLIGHTS_QUERY print(f"Highlights query: {len(highlights)} characters") # Access injection query for macro handling injections = tree_sitter_rust.INJECTIONS_QUERY print(f"Injections query: {len(injections)} characters") # Access tags query for symbol extraction tags = tree_sitter_rust.TAGS_QUERY print(f"Tags query: {len(tags)} characters") # Incremental editing example new_source = source_code.replace(b'Counter', b'AtomicCounter') tree.edit( start_byte=0, old_end_byte=len(source_code), new_end_byte=len(new_source), start_point=(0, 0), old_end_point=(35, 0), new_end_point=(35, 0), ) new_tree = parser.parse(new_source, tree) print(f"Incremental parse has errors: {new_tree.root_node.has_error}") ``` -------------------------------- ### Rust Trait with Optional Type Parameters Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/declarations.txt Shows the tree-sitter grammar for Rust traits that include optional type parameters with default values. This example demonstrates parsing of `trait_item` with `type_parameters`, including associated types and function signatures within the trait. ```rust trait Add { type Output; fn add(self, rhs: RHS) -> Self::Output; } ``` ```tree-sitter-grammar (source_file (trait_item (type_identifier) (type_parameters (type_parameter (type_identifier) (type_identifier))) (declaration_list (associated_type (type_identifier)) (function_signature_item (identifier) (parameters (self_parameter (self)) (parameter (identifier) (type_identifier))) (scoped_type_identifier (identifier) (type_identifier)))))) ``` -------------------------------- ### Parse Rust Code with SwiftTreeSitter Source: https://context7.com/tree-sitter/tree-sitter-rust/llms.txt This snippet demonstrates how to initialize a SwiftTreeSitter parser, load the Rust grammar, and parse a Rust source code string. It includes error handling for language loading and parsing, and basic exploration of the resulting syntax tree, such as checking for errors and identifying the root node type. ```swift import SwiftTreeSitter import TreeSitterRust // Create a parser instance let parser = Parser() // Load and set the Rust language let language = Language(language: tree_sitter_rust()) do { try parser.setLanguage(language) } catch { fatalError("Error loading Rust grammar: \(error)") } // Sample Rust code to parse let sourceCode = """ use std::path::PathBuf; #[derive(Debug, Default)] pub struct Config { pub root_path: PathBuf, pub max_depth: Option, pub follow_symlinks: bool, } impl Config { pub fn new(root: impl Into) -> Self { Config { root_path: root.into(), ..Default::default() } } pub fn with_max_depth(mut self, depth: usize) -> Self { self.max_depth = Some(depth); self } } async fn process_files(config: &Config) -> Result, std::io::Error> { let mut files = Vec::new(); // Process files... Ok(files) } """ // Parse the source code guard let tree = parser.parse(sourceCode) else { fatalError("Failed to parse source code") } let rootNode = tree.rootNode // Check for parse errors print("Has errors: \(rootNode.hasError)") // false // Explore the syntax tree print("Root type: \(rootNode.nodeType ?? "unknown")") // source_file print("Child count: \(rootNode.childCount)") ``` -------------------------------- ### Rust Scoped Functions with Fully Qualified Syntax Parsing with Tree-sitter Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/test/corpus/expressions.txt Parses Rust scoped function calls that use fully qualified syntax, including trait implementations. This rule specifically handles complex type annotations within scoped identifiers. ```tree-sitter grammar (source_file (expression_statement (call_expression (scoped_identifier (bracketed_type (qualified_type (type_identifier) (type_identifier))) (identifier)) (arguments (identifier))))) ``` -------------------------------- ### Rust API: Configure Parser with Rust Language Source: https://context7.com/tree-sitter/tree-sitter-rust/llms.txt Demonstrates how to use the `LANGUAGE` constant from `tree-sitter-rust` to configure a `tree-sitter::Parser` for Rust code. It shows parsing sample Rust code, verifying the syntax tree, and accessing node information. ```rust use tree_sitter::Parser; use tree_sitter_rust::{LANGUAGE, HIGHLIGHTS_QUERY, NODE_TYPES}; fn main() { // Create a new parser instance let mut parser = Parser::new(); // Configure the parser to use the Rust language grammar parser .set_language(&LANGUAGE.into()) .expect("Error loading Rust parser"); // Sample Rust code to parse let code = r#" fn fibonacci(n: u32) -> u32 { match n { 0 => 0, 1 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } } #[derive(Debug, Clone)] pub struct Point { pub x: T, pub y: T, } impl + Copy> Point { pub fn translate(&self, dx: T, dy: T) -> Point { Point { x: self.x + dx, y: self.y + dy, } } } "#; // Parse the code and get the syntax tree let tree = parser.parse(code, None).unwrap(); let root_node = tree.root_node(); // Verify the parse was successful (no syntax errors) assert!(!root_node.has_error()); // Traverse the syntax tree println!("Root node kind: {}", root_node.kind()); // "source_file" println!("Child count: {}", root_node.child_count()); // 3 (function, struct, impl) // Access specific nodes let function_node = root_node.child(0).unwrap(); println!("First child kind: {}", function_node.kind()); // "function_item" // Get the function name let name_node = function_node.child_by_field_name("name").unwrap(); println!("Function name: {}", name_node.utf8_text(code.as_bytes()).unwrap()); // "fibonacci" // Access syntax highlighting query println!("Highlights query available: {} bytes", HIGHLIGHTS_QUERY.len()); // Access node type information println!("Node types JSON available: {} bytes", NODE_TYPES.len()); } ``` -------------------------------- ### Parse Rust Code with Go Tree-sitter Source: https://context7.com/tree-sitter/tree-sitter-rust/llms.txt This Go code snippet demonstrates how to load the Rust language grammar using tree-sitter, parse a given Rust source code string, and then traverse the syntax tree to find function definitions. It utilizes the `go-tree-sitter` package and the specific `tree-sitter-rust` bindings. ```go package main import ( "fmt" tree_sitter "github.com/tree-sitter/go-tree-sitter" tree_sitter_rust "github.com/tree-sitter/tree-sitter-rust/bindings/go" ) func main() { // Get the Rust language grammar language := tree_sitter.NewLanguage(tree_sitter_rust.Language()) if language == nil { panic("Failed to load Rust grammar") } // Create a new parser parser := tree_sitter.NewParser() defer parser.Close() // Set the language to Rust err := parser.SetLanguage(language) if err != nil { panic(err) } // Sample Rust code to parse sourceCode := []byte(` use std::io::{self, Write}; fn main() -> io::Result<()> { let mut buffer = Vec::new(); writeln!(buffer, "Hello, {}!", "world")?; let numbers: Vec = (1..=10) .filter(|x| x % 2 == 0) .map(|x| x * x) .collect(); for num in &numbers { println!("{}", num); } Ok(()) } trait Drawable { fn draw(&self); fn bounding_box(&self) -> (f64, f64, f64, f64); } struct Circle { x: f64, y: f64, radius: f64, } impl Drawable for Circle { fn draw(&self) { println!("Drawing circle at ({}, {}) with radius {}", self.x, self.y, self.radius); } fn bounding_box(&self) -> (f64, f64, f64, f64) { (self.x - self.radius, self.y - self.radius, self.x + self.radius, self.y + self.radius) } } `) // Parse the source code tree := parser.Parse(sourceCode, nil) defer tree.Close() // Get the root node rootNode := tree.RootNode() // Check for parse errors fmt.Printf("Has errors: %v\n", rootNode.HasError()) // false // Print tree structure info fmt.Printf("Root node type: %s\n", rootNode.Type()) // source_file fmt.Printf("Child count: %d\n", rootNode.ChildCount()) // Traverse and find function definitions cursor := tree_sitter.NewTreeCursor(rootNode) defer cursor.Close() findFunctions(cursor, sourceCode, 0) } func findFunctions(cursor *tree_sitter.TreeCursor, source []byte, depth int) { node := cursor.CurrentNode() if node.Type() == "function_item" { // Find the function name for i := uint(0); i < node.ChildCount(); i++ { child := node.Child(i) if child.Type() == "identifier" { name := source[child.StartByte():child.EndByte()] fmt.Printf("Function: %s\n", string(name)) break } } } // Recurse into children if cursor.GoToFirstChild() { findFunctions(cursor, source, depth+1) for cursor.GoToNextSibling() { findFunctions(cursor, source, depth+1) } cursor.GoToParent() } } ``` -------------------------------- ### Benchmarking Rust Parsing Speed with tree-sitter Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/README.md Compares the parsing speed of tree-sitter-rust against rustc for a given Rust file. It demonstrates the initial parsing time and highlights the speed advantage of tree-sitter for incremental updates. ```shell $ wc -l examples/ast.rs 2157 examples/ast.rs $ rustc -Z unpretty=ast-tree -Z time-passes examples/ast.rs | head -n0 time: 0.002; rss: 55MB -> 60MB ( +5MB) parse_crate $ tree-sitter parse examples/ast.rs --quiet --time examples/ast.rs 6.48 ms 9908 bytes/ms ``` -------------------------------- ### Parse Rust Code with Node.js Tree-sitter Source: https://context7.com/tree-sitter/tree-sitter-rust/llms.txt Demonstrates how to use the tree-sitter-rust npm package to parse Rust source code. It covers parser configuration, syntax tree exploration, querying for specific code elements like functions, and incremental parsing. Dependencies include the 'tree-sitter' and 'tree-sitter-rust' npm packages. ```javascript const Parser = require('tree-sitter'); const Rust = require('tree-sitter-rust'); // Create and configure the parser const parser = new Parser(); parser.setLanguage(Rust); // Parse Rust source code const sourceCode = ` use std::collections::HashMap; async fn fetch_data(url: &str) -> Result { let response = reqwest::get(url).await?; response.text().await } macro_rules! create_function { ($func_name:ident) => { fn $func_name() { println!("Called {:?}", stringify!($func_name)); } }; } pub enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), Data(T), } `; const tree = parser.parse(sourceCode); // Check for parse errors console.log('Has errors:', tree.rootNode.hasError()); // false // Explore the syntax tree console.log('Root type:', tree.rootNode.type); // 'source_file' console.log('Children:', tree.rootNode.childCount); // 4 (use, async fn, macro, enum) // Find all function definitions using a tree query const query = new Parser.Query(Rust, '(function_item name: (identifier) @name)'); const matches = query.matches(tree.rootNode); matches.forEach(match => { match.captures.forEach(capture => { console.log('Function found:', capture.node.text); // 'fetch_data' }); }); // Access node types for tooling console.log('Node types available:', !!Rust.nodeTypeInfo); // Incremental parsing example const newSourceCode = sourceCode.replace('fetch_data', 'get_data'); const newTree = parser.parse(newSourceCode, tree, { includedRanges: [{ startIndex: 0, endIndex: newSourceCode.length, startPosition: { row: 0, column: 0 }, endPosition: { row: 20, column: 0 } }] }); console.log('Incremental parse completed'); ``` -------------------------------- ### CMake Project Configuration and Options Source: https://github.com/tree-sitter/tree-sitter-rust/blob/master/CMakeLists.txt Sets up the minimum CMake version, project name, version, description, homepage, and language. It also defines build options for shared libraries and allocator reuse, and configures the Tree-sitter ABI version with validation. ```cmake cmake_minimum_required(VERSION 3.13) project(tree-sitter-rust VERSION "0.24.0" DESCRIPTION "Rust grammar for tree-sitter" HOMEPAGE_URL "https://github.com/tree-sitter/tree-sitter-rust" LANGUAGES C) option(BUILD_SHARED_LIBS "Build using shared libraries" ON) option(TREE_SITTER_REUSE_ALLOCATOR "Reuse the library allocator" OFF) set(TREE_SITTER_ABI_VERSION 14 CACHE STRING "Tree-sitter ABI version") if(NOT ${TREE_SITTER_ABI_VERSION} MATCHES "^[0-9]+$") unset(TREE_SITTER_ABI_VERSION CACHE) message(FATAL_ERROR "TREE_SITTER_ABI_VERSION must be an integer") endif() ``` -------------------------------- ### Syntax Highlighting Queries (highlights.scm) Source: https://context7.com/tree-sitter/tree-sitter-rust/llms.txt Defines patterns for syntax highlighting in Rust code. It categorizes various code elements like types, properties, constants, functions, comments, keywords, and literals, assigning them specific highlight scopes. This file is crucial for visual code representation in editors. ```scm ; highlights.scm - Syntax highlighting queries ; Type identifiers (type_identifier) @type (primitive_type) @type.builtin ; Field and property access (field_identifier) @property ; Constants (ALL_CAPS naming convention) ((identifier) @constant (#match? @constant "^[A-Z][A-Z\d_]+$")) ; Enum constructors (PascalCase) ((identifier) @constructor (#match? @constructor "^[A-Z]")) ; Function calls (call_expression function: (identifier) @function) (call_expression function: (field_expression field: (field_identifier) @function.method)) ; Macro invocations (macro_invocation macro: (identifier) @function.macro "!" @function.macro) ; Function definitions (function_item (identifier) @function) (function_signature_item (identifier) @function) ; Comments and documentation (line_comment) @comment (block_comment) @comment (line_comment (doc_comment)) @comment.documentation (block_comment (doc_comment)) @comment.documentation ; Keywords "async" @keyword "await" @keyword "fn" @keyword "let" @keyword "mut" @keyword "pub" @keyword "struct" @keyword "impl" @keyword "trait" @keyword "enum" @keyword "match" @keyword "if" @keyword "else" @keyword "for" @keyword "while" @keyword "loop" @keyword "return" @keyword "use" @keyword ; Literals (string_literal) @string (char_literal) @string (boolean_literal) @constant.builtin (integer_literal) @constant.builtin (float_literal) @constant.builtin ```