Skip to main content

kartta_lang_python/
lib.rs

1//! Python for the kartta code graph: the functions, classes, fields, calls and imports of Python source.
2//!
3//! [`Python`] implements [`Language`] over the `tree-sitter-python` grammar. It claims every file whose extension is
4//! `py` or `pyi`, in any case.
5//!
6//! # What a file extracts to
7//!
8//! Every function, method and class is a symbol, and so is a variable assigned to a bare name at module level and an
9//! annotated attribute in a class body, `name: str = ""`, which is a field of its class. A symbol is qualified by the
10//! module its path names and by the classes around it: `pkg.service.Service.greet` for a method of `Service` in
11//! `pkg/service.py`, and `pkg.Service` for a class in `pkg/__init__.py`. A definition nested in a function is qualified
12//! by the module alone, is no member of a class around that function, and is local to the function's body. A decorated
13//! definition starts at its first decorator. A name that starts with `_` is not exported.
14//!
15//! A call records its callee and, for a member call, its receiver: `self.greet()` records `greet` on `self`, and a
16//! member call on anything but a name, `items[0].close()`, records the empty receiver. A call is attributed to the
17//! function around it; a class opens no scope. A call before the first definition of the file is dropped.
18//!
19//! # Resolution
20//!
21//! An `import` or `from ... import` that names a module of the repository includes its file, `a/b.py` or
22//! `a/b/__init__.py`, or failing both its stub, `a/b.pyi` or `a/b/__init__.pyi`: an absolute module is probed from the
23//! repository root and then from each directory around the importing file, nearest first, and a relative one from the
24//! importing file's directory, one level up for each leading dot after the first. A from-import also includes each
25//! imported name that is a submodule of the package, a namespace package without an `__init__.py` included, and probes
26//! none below a plain module file. An import that includes no file, such as one of the standard library or a
27//! `from __future__ import`, is recorded as written.
28//!
29//! A file named `test_*`, `*_test` or `conftest`, or below a `test` or `tests` directory, is test code. A `*_pb2` or
30//! `*_pb2_grpc` file, or one with a `@generated` or `DO NOT EDIT` marker in the comments and module docstring that open
31//! it, outside a backtick span, is generated code. A `.pyi` stub takes the module name and the role of the `.py` source
32//! it describes. A free `def main` at module level is the entry point.
33//!
34//! # Fingerprint
35//!
36//! [`Python::fingerprint`] identifies this crate's name and version, a digest of its source, and the grammar: its
37//! version, ABI version, node types, and the counts of its node kinds, parse states and fields. A change to
38//! `kartta-lang` is covered by `kartta_lang::FINGERPRINT`, which a cache keys beside it. It cannot see a grammar built
39//! from changed sources that keep its version and tables, nor a change to the tree-sitter runtime that keeps its
40//! version.
41//!
42//! # Examples
43//!
44//! ```
45//! use kartta_lang::Language;
46//! use kartta_lang_python::Python;
47//!
48//! let python = Python::new();
49//! assert!(python.claims("pkg/service.py"));
50//!
51//! let raw = python.extract(b"class Service:\n    def greet(self):\n        return helper()\n");
52//! let names: Vec<&str> = raw.symbols.iter().map(|symbol| symbol.qualified_name.as_str()).collect();
53//! assert_eq!(names, ["Service", "Service.greet"]);
54//! assert_eq!(raw.calls[0].callee, "helper");
55//! ```
56
57use std::cell::RefCell;
58use std::sync::OnceLock;
59
60use kartta_lang::path::base;
61use kartta_lang::{Conventions, Language, OwnMembers, RawExtraction, Repository, Resolver};
62use tree_sitter::{Parser, Tree};
63
64use crate::fnv::{FNV_OFFSET, fnv};
65use crate::resolve::Modules;
66
67mod banner;
68mod fnv;
69mod resolve;
70mod walk;
71
72include!(concat!(env!("OUT_DIR"), "/source_digest.rs"));
73
74const NODE_TYPES_DIGEST: u64 = fnv(FNV_OFFSET, tree_sitter_python::NODE_TYPES.as_bytes());
75
76/// The Python language.
77#[derive(Debug, Clone, Copy, Default)]
78#[non_exhaustive]
79pub struct Python;
80
81impl Python {
82    /// The Python language.
83    #[must_use]
84    pub const fn new() -> Self {
85        Self
86    }
87}
88
89impl Language for Python {
90    fn name(&self) -> &'static str {
91        "python"
92    }
93
94    fn claims(&self, path: &str) -> bool {
95        base(path).rsplit_once('.').is_some_and(|(_, extension)| {
96            extension.eq_ignore_ascii_case("py") || extension.eq_ignore_ascii_case("pyi")
97        })
98    }
99
100    fn fingerprint(&self) -> &[u8] {
101        static FINGERPRINT: OnceLock<Vec<u8>> = OnceLock::new();
102
103        FINGERPRINT.get_or_init(fingerprint)
104    }
105
106    fn conventions(&self) -> Conventions {
107        let mut conventions = Conventions::default();
108        conventions.own_members = OwnMembers::Unreached;
109        conventions.owner_chain_separator = Some(".");
110
111        conventions
112    }
113
114    fn extract(&self, source: &[u8]) -> RawExtraction {
115        parse(source).map_or_else(RawExtraction::default, |tree| walk::raw_walk(&tree, source))
116    }
117
118    fn resolver<'r>(&'r self, repository: &'r dyn Repository) -> Box<dyn Resolver + 'r> {
119        Box::new(Modules::new(repository))
120    }
121}
122
123fn grammar() -> tree_sitter::Language {
124    tree_sitter_python::LANGUAGE.into()
125}
126
127fn parse(source: &[u8]) -> Option<Tree> {
128    thread_local! {
129        static PARSER: RefCell<Option<Parser>> = const { RefCell::new(None) };
130    }
131
132    PARSER.with_borrow_mut(|parser| {
133        if parser.is_none() {
134            let mut fresh = Parser::new();
135            fresh.set_language(&grammar()).ok()?;
136            *parser = Some(fresh);
137        }
138        parser.as_mut()?.parse(source, None)
139    })
140}
141
142fn fingerprint() -> Vec<u8> {
143    let grammar = grammar();
144    let version = grammar.metadata().map_or([0; 3], |version| {
145        [
146            version.major_version,
147            version.minor_version,
148            version.patch_version,
149        ]
150    });
151    let counts = [
152        grammar.abi_version(),
153        grammar.node_kind_count(),
154        grammar.parse_state_count(),
155        grammar.field_count(),
156    ];
157
158    let mut bytes = Vec::new();
159    for part in [env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")] {
160        bytes.extend_from_slice(part.as_bytes());
161        bytes.push(0);
162    }
163    bytes.extend_from_slice(&SOURCE_DIGEST);
164    bytes.extend_from_slice(&NODE_TYPES_DIGEST.to_le_bytes());
165    bytes.extend_from_slice(&version);
166    for count in counts {
167        bytes.extend_from_slice(&u64::try_from(count).unwrap_or(u64::MAX).to_le_bytes());
168    }
169
170    bytes
171}