kartta_lang/language.rs
1use std::fmt;
2use std::io;
3
4use crate::extraction::{Extraction, RawExtraction};
5
6/// A language the code graph understands: which files are its, what it extracts from their bytes, and how it
7/// resolves what it extracted against the repository.
8///
9/// The engine names no language of its own. It is handed the languages to build with, and each claims its files,
10/// extracts them on the build's threads, and resolves its imports through the [`Resolver`] it builds over a read-only
11/// [`Repository`]. A crate that implements this trait plugs a language in without a change to kartta.
12///
13/// Extraction is split in two so that its expensive half can be shared. [`Language::extract`] sees only the bytes, so
14/// a cache keyed by their hash and by [`Language::fingerprint`] can hand its result to every file with the same
15/// content, in any tree; [`Resolver::resolve`] applies the path and the repository, which no cache shares.
16pub trait Language: Send + Sync + fmt::Debug {
17 /// The language's name: `go`, `cpp`. Answers report it, and the cache files the language's extractions under it.
18 fn name(&self) -> &str;
19
20 /// The family whose files resolve against each other in one graph; the language's own name unless several
21 /// languages share one, as TypeScript and JavaScript files call each other.
22 fn family(&self) -> &str {
23 self.name()
24 }
25
26 /// Whether the file at `path`, root-relative with forward slashes, is this language's.
27 fn claims(&self, path: &str) -> bool;
28
29 /// Identifies what [`Language::extract`] computes from the same bytes: it changes whenever the grammar or the
30 /// language's extraction does, and a cache keeps the extractions of each fingerprint apart. The code of this crate,
31 /// which shapes the result too, is identified by [`FINGERPRINT`](crate::FINGERPRINT), which a cache folds in
32 /// beside it.
33 fn fingerprint(&self) -> &[u8];
34
35 /// The conventions the graph resolves this language's calls under.
36 fn conventions(&self) -> Conventions {
37 Conventions::default()
38 }
39
40 /// What `source`, one file's whole content, holds, from the bytes alone.
41 ///
42 /// Runs on the build's threads, many files at a time. A file the parser gives no tree for yields an empty
43 /// extraction; a tree with syntax errors, which a recovering parser such as tree-sitter returns, is extracted as
44 /// far as the language can read it.
45 fn extract(&self, source: &[u8]) -> RawExtraction;
46
47 /// The resolver for one build over `repository`, which the build asks once and then shares between its threads.
48 /// A language that reads configuration — a `go.mod`, a `tsconfig.json` — reads it here.
49 fn resolver<'r>(&'r self, repository: &'r dyn Repository) -> Box<dyn Resolver + 'r>;
50}
51
52/// Applies a file's path and the repository to what its language extracted from the bytes.
53pub trait Resolver: Send + Sync {
54 /// The extraction of the file at `path`, from `raw`: its imports and includes resolved, its symbols' flags
55 /// completed by what the path shows.
56 fn resolve(&self, raw: RawExtraction, path: &str) -> Extraction;
57}
58
59/// The repository as a resolver sees it: the files a build indexes, and the bytes of any of them.
60///
61/// Paths are root-relative with forward slashes, and `.` and the empty path both name the root directory, as
62/// [`path::dir`](crate::path::dir) and [`path::join`](crate::path::join) spell it. An index may keep its paths in a
63/// compact form it rebuilds on reading, so the lookups hand out owned paths rather than borrowing them.
64pub trait Repository: Sync {
65 /// Whether `path` is a regular file of the repository.
66 fn contains(&self, path: &str) -> bool;
67
68 /// The regular files directly in `dir`, in index order.
69 fn files_in_dir<'a>(&'a self, dir: &str) -> Box<dyn Iterator<Item = String> + 'a>;
70
71 /// The regular files whose last component is `name`, in index order.
72 fn files_named<'a>(&'a self, name: &str) -> Box<dyn Iterator<Item = String> + 'a>;
73
74 /// The content of the file at `path`.
75 ///
76 /// # Errors
77 ///
78 /// The error of reading it.
79 fn read(&self, path: &str) -> io::Result<Vec<u8>>;
80}
81
82/// The conventions a language's calls resolve under, which the graph cannot infer from its extractions. The default
83/// states those of the languages that change none.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85#[non_exhaustive]
86pub struct Conventions {
87 /// When a bare call inside a member reaches the members of that member's own owner. A bare call inside a member of
88 /// a namespace reaches the namespace's members whatever this says, because a namespace is a lexical scope.
89 pub own_members: OwnMembers,
90 /// What a bare call that reaches no member of the caller's own owner takes from the owners that owner derives
91 /// from.
92 pub inherited_members: InheritedMembers,
93 /// Whether a variable or a constant can be called. True where a function-valued binding is a callable form of the
94 /// language; false where such a name is data, and a call of it is some other symbol's.
95 pub values_are_call_targets: bool,
96 /// The separator that joins an owner's chain of names, `.` in `A.Worker` and `::` in `a::Worker`, where an owner
97 /// is such a chain: a receiver that spells the chain's end at a separator, `Worker` or `m::Worker` for
98 /// `a::m::Worker`, names that owner. `None` where an owner is a single name.
99 pub owner_chain_separator: Option<&'static str>,
100 /// Whether a bare call reaches a member of an owner whose chain encloses the caller's own owner at
101 /// [`Conventions::owner_chain_separator`], as a TypeScript `namespace` is a lexical scope of what it holds.
102 pub bare_call_reaches_enclosing_owners: bool,
103}
104
105impl Default for Conventions {
106 fn default() -> Self {
107 Self {
108 own_members: OwnMembers::Fallback,
109 inherited_members: InheritedMembers::Unreached,
110 values_are_call_targets: true,
111 owner_chain_separator: None,
112 bare_call_reaches_enclosing_owners: false,
113 }
114 }
115}
116
117/// When a bare call inside a member reaches the members of that member's own owner.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
119pub enum OwnMembers {
120 /// Before a free symbol of the name, as C++ name lookup does inside a member function: the caller's own class is
121 /// searched first.
122 First,
123 /// Only when no free symbol of the name exists, as in a class method whose body is wrapped in `with(self)`.
124 #[default]
125 Fallback,
126 /// Never: a member is reached only through a receiver, `s.len()` or `self.load()`, and a bare name reaches a
127 /// package- or module-level symbol.
128 Unreached,
129}
130
131/// How a bare call reaches the members of the types the caller's owner derives from, as the `parents` of its type
132/// name them.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
134pub enum InheritedMembers {
135 /// A bare call reaches no inherited member.
136 #[default]
137 Unreached,
138 /// The `parents` of a type also name types its member lookup does not search, as a Ruby `extend` does, so an
139 /// inherited member is one candidate among those of its name.
140 Admitted,
141 /// The `parents` of a type are the bases its member lookup searches, as C++ class-scope lookup does, so an
142 /// inherited member a base certainly declares is taken when the caller's owner declares none of the name.
143 Found,
144}