1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
//! Tree-sitter based CSS extractor (#507).
//!
//! A stylesheet has no functions to call, so the useful graph is the set of
//! *names* it defines and the ones it consumes. Four things are worth a node:
//!
//! * class selectors (`.btn`) — the names markup refers to, emitted as `Class`
//! * id selectors (`#main`) — emitted as `Field`, the same kind the HTML
//! extractor gives an element's `id`, so the two sides of a page share a
//! vocabulary
//! * custom properties (`--brand-color`) — emitted as `Const`, which is what
//! they are
//! * `@keyframes` names — emitted as `Module`, a named block other rules
//! reference by name
//!
//! Two edge sources, both deliberately exact rather than name-guessed. An
//! `@import` becomes a `Use` node, and `var(--x)` becomes an unresolved
//! reference to the custom property. Selector *usage* from markup is not
//! emitted as a reference: a class named `container` or `header` would be
//! matched by bare name against every symbol in the project, and inventing
//! cross-language edges out of a stylesheet is exactly the failure #503 was
//! about. A custom property is safe because `--` cannot begin an identifier in
//! any language here, so the name cannot collide.
//!
//! A rule set with several selectors emits one node per selector, since a
//! reader searching for `.btn` should find it whether it was written alone or
//! beside `.btn-primary`.
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use tree_sitter::{Node as TsNode, Parser, Tree};
use crate::types::{
generate_node_id, Edge, EdgeKind, ExtractionResult, Node, NodeKind, UnresolvedRef, Visibility,
};
pub struct CssExtractor;
struct State {
/// Names already emitted, so a selector written in several places is one
/// node rather than one per occurrence.
seen: std::collections::HashSet<(NodeKind, String)>,
nodes: Vec<Node>,
edges: Vec<Edge>,
unresolved_refs: Vec<UnresolvedRef>,
file_path: String,
source: Vec<u8>,
file_node_id: String,
timestamp: u64,
}
impl State {
fn new(file_path: &str, source: &str) -> Self {
Self {
seen: std::collections::HashSet::new(),
nodes: Vec::new(),
edges: Vec::new(),
unresolved_refs: Vec::new(),
file_path: file_path.to_string(),
source: source.as_bytes().to_vec(),
file_node_id: generate_node_id(file_path, &NodeKind::File, file_path, 0),
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
}
}
fn text(&self, node: TsNode<'_>) -> String {
node.utf8_text(&self.source).unwrap_or_default().to_string()
}
/// Emits a node of `kind` named `name`, contained by the file.
fn emit(&mut self, kind: NodeKind, name: &str, ts_node: TsNode<'_>) {
if name.is_empty() {
return;
}
// A stylesheet repeats selectors freely — `.btn` may be written once
// plainly, again inside `@media`, and again beside a sibling selector.
// Those are one name, so the first occurrence is the definition and
// the rest are dropped. Keying on the node id would not do it: the id
// carries the line, so every repeat would be a distinct node with the
// same name, which makes a search for `.btn` return the same answer
// three times.
if !self.seen.insert((kind.clone(), name.to_string())) {
return;
}
let start_line = ts_node.start_position().row as u32;
let id = generate_node_id(&self.file_path, &kind, name, start_line);
self.nodes.push(Node {
id: id.clone(),
kind,
name: name.to_string(),
qualified_name: format!("{}::{}", self.file_path, name),
file_path: self.file_path.clone(),
start_line,
attrs_start_line: start_line,
end_line: ts_node.end_position().row as u32,
start_column: ts_node.start_position().column as u32,
end_column: ts_node.end_position().column as u32,
signature: None,
docstring: None,
visibility: Visibility::Pub,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
cognitive_complexity: 0,
distinct_operators: 0,
distinct_operands: 0,
total_operators: 0,
total_operands: 0,
updated_at: self.timestamp,
parent_id: Some(self.file_node_id.clone()),
});
let file_id = self.file_node_id.clone();
self.edges.push(Edge {
source: file_id,
target: id,
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
}
impl CssExtractor {
pub fn extract_css(file_path: &str, source: &str) -> ExtractionResult {
let start = Instant::now();
let mut state = State::new(file_path, source);
let mut errors = Vec::new();
state.nodes.push(Node {
id: state.file_node_id.clone(),
kind: NodeKind::File,
name: file_path.to_string(),
qualified_name: file_path.to_string(),
file_path: file_path.to_string(),
start_line: 0,
attrs_start_line: 0,
end_line: source.lines().count().saturating_sub(1) as u32,
start_column: 0,
end_column: 0,
signature: None,
docstring: None,
visibility: Visibility::Pub,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
cognitive_complexity: 0,
distinct_operators: 0,
distinct_operands: 0,
total_operators: 0,
total_operands: 0,
updated_at: state.timestamp,
parent_id: None,
});
match Self::parse(source) {
Ok(tree) => Self::walk(&mut state, tree.root_node()),
Err(message) => errors.push(message),
}
ExtractionResult {
nodes: state.nodes,
edges: state.edges,
unresolved_refs: state.unresolved_refs,
errors,
duration_ms: start.elapsed().as_millis() as u64,
}
}
fn parse(source: &str) -> Result<Tree, String> {
let mut parser = Parser::new();
parser
.set_language(&crate::extraction::ts_provider::language("css"))
.map_err(|e| format!("failed to load CSS grammar: {e}"))?;
parser
.parse(source, None)
.ok_or_else(|| "tree-sitter parse returned None".to_string())
}
/// One pass over the whole tree.
///
/// Selectors, custom properties and `var()` calls are found at any depth —
/// a rule nested in `@media`, `@supports` or `@layer` is still a rule —
/// so this recurses rather than walking only the stylesheet's children.
fn walk(state: &mut State, node: TsNode<'_>) {
match node.kind() {
"class_selector" => {
if let Some(name) = Self::last_child_of_kind(node, "class_name") {
let text = state.text(name);
state.emit(NodeKind::Class, &text, node);
}
}
"id_selector" => {
if let Some(name) = Self::last_child_of_kind(node, "id_name") {
let text = state.text(name);
state.emit(NodeKind::Field, &text, node);
}
}
"keyframes_statement" => {
if let Some(name) = Self::last_child_of_kind(node, "keyframes_name") {
let text = state.text(name);
state.emit(NodeKind::Module, &text, node);
}
}
"declaration" => {
// `--brand: #fff` defines a custom property; every other
// declaration sets a known CSS property and defines nothing.
if let Some(property) = Self::last_child_of_kind(node, "property_name") {
let text = state.text(property);
if text.starts_with("--") {
state.emit(NodeKind::Const, &text, node);
}
}
}
"import_statement" => Self::emit_import(state, node),
"call_expression" => Self::emit_var_reference(state, node),
_ => {}
}
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
Self::walk(state, cursor.node());
if !cursor.goto_next_sibling() {
break;
}
}
}
}
/// `@import "theme.css"` — a `Use` node named by the imported path.
fn emit_import(state: &mut State, node: TsNode<'_>) {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return;
}
loop {
let child = cursor.node();
if matches!(child.kind(), "string_value" | "call_expression") {
let raw = state.text(child);
let path = raw.trim_matches(['"', '\''].as_slice());
let path = path
.strip_prefix("url(")
.and_then(|rest| rest.strip_suffix(')'))
.map_or(path, |inner| inner.trim_matches(['"', '\''].as_slice()));
if !path.is_empty() {
state.emit(NodeKind::Use, path, node);
}
return;
}
if !cursor.goto_next_sibling() {
return;
}
}
}
/// `var(--brand)` — a reference to the custom property of that name.
///
/// Only `var` is followed. Every other CSS function (`rgb`, `calc`,
/// `translate`) names a builtin, and a reference to a builtin resolves to
/// nothing but costs a lookup on every stylesheet in the project.
fn emit_var_reference(state: &mut State, node: TsNode<'_>) {
let Some(function) = Self::last_child_of_kind(node, "function_name") else {
return;
};
if state.text(function) != "var" {
return;
}
let Some(arguments) = Self::last_child_of_kind(node, "arguments") else {
return;
};
let mut cursor = arguments.walk();
if !cursor.goto_first_child() {
return;
}
loop {
let child = cursor.node();
if child.kind() == "plain_value" {
let name = state.text(child);
if name.starts_with("--") {
let from = state.file_node_id.clone();
state.unresolved_refs.push(UnresolvedRef {
from_node_id: from,
reference_name: name,
reference_kind: EdgeKind::Uses,
line: node.start_position().row as u32,
column: node.start_position().column as u32,
file_path: state.file_path.clone(),
});
}
return;
}
if !cursor.goto_next_sibling() {
return;
}
}
}
fn last_child_of_kind<'t>(node: TsNode<'t>, kind: &str) -> Option<TsNode<'t>> {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return None;
}
let mut found = None;
loop {
let child = cursor.node();
if child.kind() == kind {
found = Some(child);
}
if !cursor.goto_next_sibling() {
return found;
}
}
}
}
impl crate::extraction::LanguageExtractor for CssExtractor {
fn extensions(&self) -> &[&str] {
&["css"]
}
fn language_name(&self) -> &'static str {
"css"
}
fn extract(&self, file_path: &str, source: &str) -> ExtractionResult {
Self::extract_css(file_path, source)
}
}