-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathfsharp.rs
More file actions
438 lines (400 loc) · 15.1 KB
/
Copy pathfsharp.rs
File metadata and controls
438 lines (400 loc) · 15.1 KB
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use tree_sitter::{Node, Tree};
use crate::cfg::build_function_cfg;
use crate::complexity::compute_all_metrics;
use crate::types::*;
use super::helpers::*;
use super::SymbolExtractor;
pub struct FSharpExtractor;
impl SymbolExtractor for FSharpExtractor {
fn extract(&self, tree: &Tree, source: &[u8], file_path: &str) -> FileSymbols {
let mut symbols = FileSymbols::new(file_path.to_string());
walk_tree(&tree.root_node(), source, &mut symbols, match_fsharp_node);
walk_ast_nodes_with_config(&tree.root_node(), source, &mut symbols.ast_nodes, &FSHARP_AST_CONFIG);
symbols
}
}
fn match_fsharp_node(node: &Node, source: &[u8], symbols: &mut FileSymbols, _depth: usize) {
match node.kind() {
"named_module" => handle_named_module(node, source, symbols),
"function_declaration_left" => handle_function_decl(node, source, symbols),
"type_definition" => handle_type_def(node, source, symbols),
"import_decl" => handle_import_decl(node, source, symbols),
"application_expression" => handle_application(node, source, symbols),
"dot_expression" => handle_dot_expression(node, source, symbols),
"value_definition" => handle_value_definition(node, source, symbols),
_ => {}
}
}
/// Find the enclosing `named_module` and return its identifier text.
fn enclosing_module_name(node: &Node, source: &[u8]) -> Option<String> {
let module = find_parent_of_type(node, "named_module")?;
let id = find_child(&module, "long_identifier")?;
Some(node_text(&id, source).to_string())
}
fn handle_named_module(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let name_node = match find_child(node, "long_identifier") {
Some(n) => n,
None => return,
};
symbols.definitions.push(Definition {
name: node_text(&name_node, source).to_string(),
kind: "module".to_string(),
line: start_line(node),
end_line: Some(end_line(node)),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
}
fn handle_function_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
// function_declaration_left: first child is the function name identifier,
// followed by argument_patterns.
let name_node = match find_child(node, "identifier") {
Some(n) => n,
None => return,
};
let raw_name = node_text(&name_node, source).to_string();
let line = start_line(node);
// Avoid duplicates — the DFS walk also visits the inner curried
// `function_declaration_left` of multi-parameter functions
// (e.g. `let add x y = …`), which would otherwise push the same
// `(name, line)` definition twice. Mirrors the JS extractor's guard,
// which compares against the raw (unqualified) identifier text.
if symbols
.definitions
.iter()
.any(|d| d.name == raw_name && d.line == line)
{
return;
}
let module_name = enclosing_module_name(node, source);
let qualified = match module_name {
Some(m) => format!("{}.{}", m, raw_name),
None => raw_name,
};
let params = extract_fsharp_params(node, source);
// JS extractor uses the parent's endLine (the function_or_value_defn) for
// a tighter bound; do the same to preserve parity.
let end = node.parent().unwrap_or(*node);
symbols.definitions.push(Definition {
name: qualified,
kind: "function".to_string(),
line,
end_line: Some(end_line(&end)),
decorators: None,
complexity: compute_all_metrics(&end, source, "fsharp"),
cfg: build_function_cfg(&end, "fsharp", source),
children: opt_children(params),
});
}
fn extract_fsharp_params(decl_left: &Node, source: &[u8]) -> Vec<Definition> {
let mut params = Vec::new();
if let Some(arg_patterns) = find_child(decl_left, "argument_patterns") {
collect_param_identifiers(&arg_patterns, source, &mut params);
}
params
}
fn collect_param_identifiers(node: &Node, source: &[u8], params: &mut Vec<Definition>) {
if node.kind() == "identifier" {
params.push(child_def(
node_text(node, source).to_string(),
"parameter",
start_line(node),
));
return;
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
collect_param_identifiers(&child, source, params);
}
}
}
fn handle_type_def(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
// type_definition contains union_type_defn, record_type_defn, etc.
for i in 0..node.child_count() {
let child = match node.child(i) {
Some(c) => c,
None => continue,
};
let kind = child.kind();
if !matches!(
kind,
"union_type_defn"
| "record_type_defn"
| "type_abbreviation_defn"
| "class_type_defn"
| "interface_type_defn"
| "type_defn"
) {
continue;
}
let name = match find_child(&child, "type_name") {
Some(type_name) => find_child(&type_name, "identifier")
.map(|n| node_text(&n, source).to_string())
.unwrap_or_else(|| node_text(&type_name, source).to_string()),
None => match find_child(&child, "identifier") {
Some(id) => node_text(&id, source).to_string(),
None => continue,
},
};
let mut children: Vec<Definition> = Vec::new();
extract_type_members(&child, source, &mut children);
symbols.definitions.push(Definition {
name,
kind: determine_type_kind(kind).to_string(),
line: start_line(&child),
end_line: Some(end_line(&child)),
decorators: None,
complexity: None,
cfg: None,
children: opt_children(children),
});
}
}
fn determine_type_kind(node_kind: &str) -> &'static str {
match node_kind {
"union_type_defn" => "enum",
"record_type_defn" => "record",
"class_type_defn" => "class",
"interface_type_defn" => "interface",
_ => "type",
}
}
fn extract_type_members(type_defn: &Node, source: &[u8], children: &mut Vec<Definition>) {
for i in 0..type_defn.child_count() {
let child = match type_defn.child(i) {
Some(c) => c,
None => continue,
};
match child.kind() {
"union_type_case" => {
if let Some(name) = find_child(&child, "identifier") {
children.push(child_def(
node_text(&name, source).to_string(),
"property",
start_line(&child),
));
}
}
"record_field" => {
let name_node = child
.child_by_field_name("name")
.or_else(|| find_child(&child, "identifier"));
if let Some(name) = name_node {
children.push(child_def(
node_text(&name, source).to_string(),
"property",
start_line(&child),
));
}
}
// Recurse into container nodes that hold cases/fields.
"union_type_cases" | "record_fields" => {
extract_type_members(&child, source, children);
}
_ => {}
}
}
}
fn handle_import_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let module_node = match find_child(node, "long_identifier") {
Some(n) => n,
None => return,
};
let source_name = node_text(&module_node, source).to_string();
let last = source_name
.split('.')
.last()
.unwrap_or(&source_name)
.to_string();
symbols
.imports
.push(Import::new(source_name, vec![last], start_line(node)));
}
fn handle_application(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let func_node = match node.child(0) {
Some(n) => n,
None => return,
};
// Mirrors the JS extractor's `handleApplication`: the full dotted name
// (e.g. `Service.createUser`) is stored in `name`. Splitting `name` into
// `(receiver, method)` would diverge from the JS engine's output and
// change which resolution rules fire downstream.
match func_node.kind() {
"identifier" | "long_identifier" => {
symbols.calls.push(Call {
name: node_text(&func_node, source).to_string(),
line: start_line(node),
dynamic: None,
receiver: None,
});
}
"long_identifier_or_op" => {
// Inner child is either `identifier` (bare, e.g. `validateUser`) or
// `long_identifier` (qualified, e.g. `Repository.save`). Order
// matches the JS extractor (`identifier` first). Operator forms
// like `( + )` have neither child; we emit nothing in that case,
// mirroring the JS extractor's silent skip.
if let Some(inner) = find_child(&func_node, "identifier")
.or_else(|| find_child(&func_node, "long_identifier"))
{
symbols.calls.push(Call {
name: node_text(&inner, source).to_string(),
line: start_line(node),
dynamic: None,
receiver: None,
});
}
}
_ => {}
}
}
fn handle_dot_expression(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
// Mirrors the JS extractor's `handleDotExpression`: collect identifier
// segments and emit `name = last`, `receiver = everything-before`.
let mut parts: Vec<String> = Vec::new();
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
match child.kind() {
"identifier" | "long_identifier" => {
parts.push(node_text(&child, source).to_string());
}
_ => {}
}
}
}
if parts.len() >= 2 {
let method = parts.last().cloned().unwrap_or_default();
let receiver = parts[..parts.len() - 1].join(".");
symbols.calls.push(Call {
name: method,
line: start_line(node),
dynamic: None,
receiver: Some(receiver),
});
}
}
/// Handle `val name : type` declarations in `.fsi` signature files.
///
/// The signature grammar reuses the `value_definition` node kind for `val`
/// declarations, distinguished from the source grammar's `let` bindings by
/// the first child being the literal `val` keyword. Source-file
/// `value_definition` nodes (which start with `let`) are intentionally
/// ignored here to preserve `.fs` extractor parity.
fn handle_value_definition(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let first = match node.child(0) {
Some(c) => c,
None => return,
};
if first.kind() != "val" {
return;
}
let decl_left = match find_child(node, "value_declaration_left") {
Some(n) => n,
None => return,
};
let name = match extract_value_name(&decl_left, source) {
Some(n) => n,
None => return,
};
let kind = if has_function_type(node) { "function" } else { "variable" };
let module_name = enclosing_module_name(node, source);
let qualified = match module_name {
Some(m) => format!("{}.{}", m, name),
None => name,
};
symbols.definitions.push(Definition {
name: qualified,
kind: kind.to_string(),
line: start_line(node),
end_line: Some(end_line(node)),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
}
fn extract_value_name(decl_left: &Node, source: &[u8]) -> Option<String> {
let pattern = find_child(decl_left, "identifier_pattern")?;
let ident = find_child(&pattern, "long_identifier_or_op")
.and_then(|n| find_child(&n, "identifier"))
.or_else(|| find_child(&pattern, "identifier"))?;
Some(node_text(&ident, source).to_string())
}
fn has_function_type(node: &Node) -> bool {
// The grammar wraps every type signature in `curried_spec`. A function type
// (e.g. `val add : int -> int -> int`) contains one or more `arguments_spec`
// children; a plain value (e.g. `val pi : float`) wraps a single `simple_type`.
let Some(curried) = find_child(node, "curried_spec") else { return false };
for i in 0..curried.child_count() {
if let Some(child) = curried.child(i) {
if child.kind() == "arguments_spec" {
return true;
}
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::extractors::SymbolExtractor;
use tree_sitter::Parser;
fn parse_source(code: &str) -> FileSymbols {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_fsharp::LANGUAGE_FSHARP.into())
.unwrap();
let tree = parser.parse(code.as_bytes(), None).unwrap();
FSharpExtractor.extract(&tree, code.as_bytes(), "test.fs")
}
fn parse_signature(code: &str) -> FileSymbols {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_fsharp::LANGUAGE_SIGNATURE.into())
.unwrap();
let tree = parser.parse(code.as_bytes(), None).unwrap();
FSharpExtractor.extract(&tree, code.as_bytes(), "test.fsi")
}
#[test]
fn signature_extracts_val_declarations() {
let s = parse_signature("namespace MyApp.Domain\n\nval add : int -> int -> int\nval pi : float\n");
let add = s
.definitions
.iter()
.find(|d| d.name == "add")
.expect("val add should be extracted");
assert_eq!(add.kind, "function");
let pi = s
.definitions
.iter()
.find(|d| d.name == "pi")
.expect("val pi should be extracted");
assert_eq!(pi.kind, "variable");
}
#[test]
fn signature_extracts_bare_val_declarations() {
let s = parse_signature("val negate : int -> int\nval count : int\n");
assert!(s
.definitions
.iter()
.any(|d| d.name == "negate" && d.kind == "function"));
assert!(s
.definitions
.iter()
.any(|d| d.name == "count" && d.kind == "variable"));
}
#[test]
fn source_grammar_does_not_extract_let_bindings_as_val() {
// `let x = 5` is a value_definition in the source grammar but its
// first child is `let`, not `val`. Our handler must not extract it
// (preserves prior `.fs` extraction parity — only function_declaration_left
// produces definitions in source files).
let s = parse_source("module M\n\nlet x = 5\n");
assert!(
s.definitions.iter().all(|d| d.name != "x"),
"let bindings in .fs files must not be extracted as val definitions"
);
}
}