kartta_lang_rust/lib.rs
1//! Rust for the kartta code graph: the items, members and calls of Rust source, and the files its `mod` declarations
2//! pull in.
3//!
4//! [`Rust`] implements [`Language`] over the `tree-sitter-rust` grammar. It claims every file whose extension is `rs`,
5//! in any case.
6//!
7//! # What a file extracts to
8//!
9//! Every function, struct, union, enum, trait, type alias, `macro_rules!`, constant, static and inline module is a
10//! symbol, and so is every named field of a struct and every variant of an enum. A member of a `trait`, or of an `impl`
11//! whose target names a type, is owned by that type and qualified under it, `Service::new`; a member of an `impl` for a
12//! tuple, `dyn` or function type has no owner. An item of an inline module is qualified by the chain of its modules,
13//! `a::b::Worker`, so two modules of one file keep their same-named items apart. A `macro_rules!` keeps
14//! its bare name, because a macro is in scope by text order rather than by path. A file's own module is named by its
15//! path, which no qualified name carries. `impl Trait for Type` adds `Trait` to the parents of the `Type` the file
16//! declares under that name or path.
17//!
18//! A call records its callee and, where the syntax spells one, its receiver: `self.greet()` and `Self::new()` record
19//! the type of the `impl` or `trait` around them, `Widget::new()` records `Widget`, and `a::Worker::run()` records
20//! `a::Worker` when the file declares that module. A member call on anything but a name records the empty receiver,
21//! and a macro invocation is a call of the macro. A call of an item that a function body declares is a local call of
22//! that item. A `use` declaration and `extern crate` add no import: a module path names no file.
23//!
24//! # Resolution
25//!
26//! A bodiless `mod NAME;` includes the file it pulls in: its `#[path]` override, or `NAME.rs` or `NAME/mod.rs` beside
27//! a crate root or a file named `lib.rs`, `main.rs` or `mod.rs`, and under the directory named for the file's stem
28//! otherwise, one directory deeper for each inline module around the declaration. A package is a directory that holds
29//! a `Cargo.toml`, and its crate roots are the files of Cargo's conventional layout: `src/lib.rs`, `src/main.rs`,
30//! `build.rs`, and each target under `src/bin/`, `examples/`, `tests/` and `benches/`. A top-level `fn main` in a crate
31//! root other than the library is the entry point.
32//!
33//! Code gated by `#[test]`, `#[bench]` or a `cfg` that holds only under `test` is test code, and so is every file below
34//! a `tests` directory outside `src`, counted from the repository root or from a package. A file that a test-gated
35//! `mod` or a test file pulls in is a test include. A `*.gen.rs` or `*_generated.rs` file, or one with a `@generated`
36//! or `DO NOT EDIT` marker in its leading comments, outside a backtick span, is generated code.
37//!
38//! # Fingerprint
39//!
40//! [`Rust::fingerprint`] identifies this crate's name and version, a digest of its source, and the grammar: its
41//! version, ABI version, node types, and the counts of its node kinds, parse states and fields. A change to
42//! `kartta-lang` is covered by `kartta_lang::FINGERPRINT`, which a cache keys beside it. It cannot see a grammar built
43//! from changed sources that keep its version and tables, nor a change to the tree-sitter runtime that keeps its
44//! version.
45//!
46//! # Examples
47//!
48//! ```
49//! use kartta_lang::Language;
50//! use kartta_lang_rust::Rust;
51//!
52//! let rust = Rust::new();
53//! assert!(rust.claims("src/lib.rs"));
54//!
55//! let raw = rust.extract(b"struct Service;\nimpl Service {\n fn touch(&self) { self.greet(); }\n}\n");
56//! let names: Vec<&str> = raw.symbols.iter().map(|symbol| symbol.qualified_name.as_str()).collect();
57//! assert_eq!(names, ["Service", "Service::touch"]);
58//! assert_eq!(raw.calls[0].receiver.as_deref(), Some("Service"));
59//! ```
60
61use std::cell::RefCell;
62use std::sync::OnceLock;
63
64use kartta_lang::path::base;
65use kartta_lang::{Conventions, Language, OwnMembers, RawExtraction, Repository, Resolver};
66use tree_sitter::{Parser, Tree};
67
68use crate::fnv::{FNV_OFFSET, fnv};
69use crate::resolve::Crates;
70
71mod banner;
72mod fnv;
73mod resolve;
74mod walk;
75
76include!(concat!(env!("OUT_DIR"), "/source_digest.rs"));
77
78const NODE_TYPES_DIGEST: u64 = fnv(FNV_OFFSET, tree_sitter_rust::NODE_TYPES.as_bytes());
79
80/// The Rust language.
81#[derive(Debug, Clone, Copy, Default)]
82#[non_exhaustive]
83pub struct Rust;
84
85impl Rust {
86 /// The Rust language.
87 #[must_use]
88 pub const fn new() -> Self {
89 Self
90 }
91}
92
93impl Language for Rust {
94 fn name(&self) -> &'static str {
95 "rust"
96 }
97
98 fn claims(&self, path: &str) -> bool {
99 base(path)
100 .rsplit_once('.')
101 .is_some_and(|(_, extension)| extension.eq_ignore_ascii_case("rs"))
102 }
103
104 fn fingerprint(&self) -> &[u8] {
105 static FINGERPRINT: OnceLock<Vec<u8>> = OnceLock::new();
106
107 FINGERPRINT.get_or_init(fingerprint)
108 }
109
110 fn conventions(&self) -> Conventions {
111 let mut conventions = Conventions::default();
112 conventions.own_members = OwnMembers::Unreached;
113 conventions.owner_chain_separator = Some("::");
114
115 conventions
116 }
117
118 fn extract(&self, source: &[u8]) -> RawExtraction {
119 parse(source).map_or_else(RawExtraction::default, |tree| walk::raw_walk(&tree, source))
120 }
121
122 fn resolver<'r>(&'r self, repository: &'r dyn Repository) -> Box<dyn Resolver + 'r> {
123 Box::new(Crates::new(repository))
124 }
125}
126
127fn grammar() -> tree_sitter::Language {
128 tree_sitter_rust::LANGUAGE.into()
129}
130
131fn parse(source: &[u8]) -> Option<Tree> {
132 thread_local! {
133 static PARSER: RefCell<Option<Parser>> = const { RefCell::new(None) };
134 }
135
136 PARSER.with_borrow_mut(|parser| {
137 if parser.is_none() {
138 let mut fresh = Parser::new();
139 fresh.set_language(&grammar()).ok()?;
140 *parser = Some(fresh);
141 }
142 parser.as_mut()?.parse(source, None)
143 })
144}
145
146fn fingerprint() -> Vec<u8> {
147 let grammar = grammar();
148 let version = grammar.metadata().map_or([0; 3], |version| {
149 [
150 version.major_version,
151 version.minor_version,
152 version.patch_version,
153 ]
154 });
155 let counts = [
156 grammar.abi_version(),
157 grammar.node_kind_count(),
158 grammar.parse_state_count(),
159 grammar.field_count(),
160 ];
161
162 let mut bytes = Vec::new();
163 for part in [env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")] {
164 bytes.extend_from_slice(part.as_bytes());
165 bytes.push(0);
166 }
167 bytes.extend_from_slice(&SOURCE_DIGEST);
168 bytes.extend_from_slice(&NODE_TYPES_DIGEST.to_le_bytes());
169 bytes.extend_from_slice(&version);
170 for count in counts {
171 bytes.extend_from_slice(&u64::try_from(count).unwrap_or(u64::MAX).to_le_bytes());
172 }
173
174 bytes
175}