Repository navigation
Expand file tree
/
Copy pathRustParseService.cs
More file actions
659 lines (604 loc) · 23.6 KB
/
Copy pathRustParseService.cs
File metadata and controls
659 lines (604 loc) · 23.6 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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
using System.Text.RegularExpressions;
using CodeMesh.Domain.Contracts;
using CodeMesh.Domain.Graph;
using CodeMesh.Domain.Utilities;
namespace CodeMesh.Parser.Rust;
public sealed partial class RustParseService
{
public static ParserCapability Capability { get; } = new(
"codemesh-parser-rust",
"rust",
"0.1.1",
[".rs"],
["repositoryRoot", "pathFilter"]);
public async Task<ParseResult> ParseAsync(
ParseRequest request,
CancellationToken cancellationToken = default)
{
var repositoryRoot = Path.GetFullPath(request.RepositoryRoot);
if (!Directory.Exists(repositoryRoot))
{
return Failure($"Repository root not found: {repositoryRoot}");
}
var nodes = new List<CodeNode>();
var relationships = new List<CodeRelationship>();
var contents = new List<CodeContent>();
var diagnostics = new List<ParserDiagnostic>();
var parsedAt = DateTimeOffset.UtcNow;
foreach (var file in EnumerateRustFiles(repositoryRoot, request.PathFilter))
{
cancellationToken.ThrowIfCancellationRequested();
var relativePath = NormalizePath(Path.GetRelativePath(repositoryRoot, file));
try
{
var text = await File.ReadAllTextAsync(file, cancellationToken).ConfigureAwait(false);
ParseFile(
repositoryRoot,
relativePath,
text,
parsedAt,
nodes,
relationships,
contents,
diagnostics);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
diagnostics.Add(new ParserDiagnostic(
"CMRS001",
$"Could not read Rust file '{relativePath}': {exception.Message}",
"warning",
SourceSpan.Unknown(relativePath)));
}
}
return new ParseResult(
Capability.WorkerName,
Capability.Language,
nodes,
relationships,
contents.GroupBy(content => content.Hash, StringComparer.Ordinal).Select(group => group.First()).ToArray(),
diagnostics,
parsedAt);
}
private static void ParseFile(
string repositoryRoot,
string relativePath,
string text,
DateTimeOffset parsedAt,
List<CodeNode> nodes,
List<CodeRelationship> relationships,
List<CodeContent> contents,
List<ParserDiagnostic> diagnostics)
{
var project = ProjectName(repositoryRoot);
var module = ModuleName(relativePath);
var lines = NormalizeLines(text);
var fileHash = CodeMeshHash.Sha256Hex(text);
var fileNodeId = $"rust:file:{relativePath}";
var fileKind = IsTestFile(relativePath) ? CodeNodeKind.TestFile : CodeNodeKind.File;
nodes.Add(new CodeNode(
fileNodeId,
fileNodeId,
fileKind,
Path.GetFileName(relativePath),
"rust",
project,
new SourceSpan(relativePath, 1, 1, Math.Max(1, lines.Length), 1),
fileHash,
new Dictionary<string, string>
{
["filePath"] = relativePath,
["module"] = module,
["rustKind"] = "file"
}));
contents.Add(new CodeContent(fileHash, text, "text/x-rust", parsedAt, parsedAt));
var declarations = CollectDeclarations(lines, relativePath, diagnostics);
var built = new List<BuiltDeclaration>();
foreach (var declaration in declarations)
{
var parent = built
.Where(candidate =>
candidate.Declaration.StartLine < declaration.StartLine &&
candidate.Declaration.EndLine >= declaration.EndLine &&
candidate.Declaration.HasBody)
.OrderByDescending(candidate => candidate.Declaration.StartLine)
.FirstOrDefault();
var qualifiedName = parent is null
? declaration.Name
: $"{parent.QualifiedName}::{declaration.Name}";
var nodeId = NodeId(module, declaration, qualifiedName);
var content = string.Join(
Environment.NewLine,
lines[(declaration.StartLine - 1)..declaration.EndLine]);
var contentHash = CodeMeshHash.Sha256Hex(content);
var metadata = DeclarationMetadata(relativePath, module, declaration, qualifiedName, parent?.Node.Id ?? fileNodeId);
var node = new CodeNode(
nodeId,
nodeId,
declaration.NodeKind,
declaration.Name,
"rust",
project,
new SourceSpan(
relativePath,
declaration.StartLine,
declaration.StartColumn,
declaration.EndLine,
1),
contentHash,
metadata);
nodes.Add(node);
contents.Add(new CodeContent(
contentHash,
content,
"text/x-rust-fragment",
parsedAt,
parsedAt));
relationships.Add(Relationship(
parent?.Node.Id ?? fileNodeId,
nodeId,
CodeRelationshipKind.Contains,
null,
relativePath));
built.Add(new BuiltDeclaration(declaration, node, qualifiedName, content));
}
AddSemanticRelationships(built, relationships, relativePath);
}
private static IReadOnlyList<RustDeclaration> CollectDeclarations(
string[] lines,
string relativePath,
List<ParserDiagnostic> diagnostics)
{
var declarations = new List<RustDeclaration>();
var attributes = new List<string>();
for (var index = 0; index < lines.Length; index++)
{
var trimmed = StripLineComment(lines[index]).Trim();
if (trimmed.StartsWith("#[", StringComparison.Ordinal))
{
attributes.Add(trimmed);
continue;
}
if (string.IsNullOrWhiteSpace(trimmed))
{
continue;
}
var statement = DeclarationStatement(lines, index);
var useMatch = UseRegex().Match(statement);
var implMatch = ImplRegex().Match(statement);
var declarationMatch = DeclarationRegex().Match(statement);
RustDeclaration? declaration = null;
if (useMatch.Success)
{
var path = NormalizeWhitespace(useMatch.Groups["path"].Value);
declaration = new RustDeclaration(
"use",
path,
CodeNodeKind.Declaration,
index + 1,
LeadingColumn(lines[index]),
FindDeclarationEnd(lines, index),
false,
statement,
attributes.ToArray(),
null,
null);
}
else if (implMatch.Success)
{
var traitName = NullIfWhiteSpace(implMatch.Groups["trait"].Value);
var typeName = implMatch.Groups["type"].Value;
declaration = new RustDeclaration(
"impl",
traitName is null ? $"impl {typeName}" : $"impl {traitName} for {typeName}",
CodeNodeKind.Declaration,
index + 1,
LeadingColumn(lines[index]),
FindDeclarationEnd(lines, index),
statement.Contains('{'),
statement,
attributes.ToArray(),
traitName,
typeName);
}
else if (declarationMatch.Success)
{
var rustKind = declarationMatch.Groups["kind"].Value;
var nodeKind = NodeKind(rustKind, attributes, declarationMatch.Groups["name"].Value);
declaration = new RustDeclaration(
rustKind,
declarationMatch.Groups["name"].Value,
nodeKind,
index + 1,
LeadingColumn(lines[index]),
FindDeclarationEnd(lines, index),
statement.Contains('{'),
statement,
attributes.ToArray(),
null,
null);
}
if (declaration is not null)
{
declarations.Add(declaration);
attributes.Clear();
continue;
}
if (attributes.Count > 0 && !trimmed.StartsWith("//", StringComparison.Ordinal))
{
attributes.Clear();
}
}
if (declarations.Count == 0 && lines.Any(line => !string.IsNullOrWhiteSpace(line)))
{
diagnostics.Add(new ParserDiagnostic(
"CMRS002",
$"Rust file '{relativePath}' contained no supported declarations.",
"info",
SourceSpan.Unknown(relativePath)));
}
return declarations;
}
private static void AddSemanticRelationships(
IReadOnlyList<BuiltDeclaration> declarations,
List<CodeRelationship> relationships,
string relativePath)
{
var byName = declarations
.GroupBy(item => item.Declaration.Name, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.ToArray(), StringComparer.Ordinal);
var callableByName = declarations
.Where(item => item.Declaration.RustKind == "fn")
.GroupBy(item => item.Declaration.Name, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.ToArray(), StringComparer.Ordinal);
var typeByName = declarations
.Where(item => item.Declaration.RustKind is "struct" or "enum" or "trait")
.GroupBy(item => item.Declaration.Name, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => group.ToArray(), StringComparer.Ordinal);
foreach (var declaration in declarations)
{
if (declaration.Declaration.RustKind == "impl")
{
AddResolvedRelationship(
declaration.Node.Id,
declaration.Declaration.TraitName,
typeByName,
CodeRelationshipKind.Implements,
relationships,
relativePath);
AddResolvedRelationship(
declaration.Node.Id,
declaration.Declaration.TypeName,
typeByName,
CodeRelationshipKind.References,
relationships,
relativePath);
}
if (declaration.Declaration.RustKind == "use")
{
var target = declaration.Declaration.Name
.TrimEnd(':', '*')
.Split("::", StringSplitOptions.RemoveEmptyEntries)
.LastOrDefault();
AddResolvedRelationship(
declaration.Node.Id,
target,
byName,
CodeRelationshipKind.References,
relationships,
relativePath);
}
if (declaration.Declaration.RustKind != "fn")
{
continue;
}
var body = BodyOnly(declaration.Content);
foreach (Match match in CallRegex().Matches(body).Cast<Match>().Concat(MethodCallRegex().Matches(body).Cast<Match>()))
{
var name = match.Groups["name"].Value;
if (IgnoredCallNames.Contains(name) ||
!callableByName.TryGetValue(name, out var targets) ||
targets.Length != 1)
{
continue;
}
relationships.Add(Relationship(
declaration.Node.Id,
targets[0].Node.Id,
CodeRelationshipKind.Invokes,
name,
relativePath));
}
foreach (var (name, targets) in typeByName)
{
if (targets.Length == 1 && SignatureContainsType(declaration.Declaration.Signature, name))
{
relationships.Add(Relationship(
declaration.Node.Id,
targets[0].Node.Id,
CodeRelationshipKind.UsesType,
name,
relativePath));
}
}
}
}
private static IReadOnlyDictionary<string, string> DeclarationMetadata(
string relativePath,
string module,
RustDeclaration declaration,
string qualifiedName,
string parentNodeId)
{
var metadata = new Dictionary<string, string>
{
["filePath"] = relativePath,
["module"] = module,
["qualifiedName"] = qualifiedName,
["parentNodeId"] = parentNodeId,
["rustKind"] = declaration.RustKind,
["signature"] = declaration.Signature,
["attributes"] = string.Join(' ', declaration.Attributes)
};
if (declaration.TraitName is not null)
{
metadata["traitName"] = declaration.TraitName;
}
if (declaration.TypeName is not null)
{
metadata["typeName"] = declaration.TypeName;
}
var exportKind = PythonExportKind(declaration.Attributes);
if (exportKind is not null)
{
metadata["pythonExportKind"] = exportKind;
metadata["pythonExportName"] = PythonExportName(declaration.Attributes) ?? declaration.Name;
}
if (declaration.NodeKind == CodeNodeKind.TestCase)
{
metadata["testRole"] = "case";
metadata["testFramework"] = "rust";
}
return metadata;
}
private static CodeNodeKind NodeKind(
string rustKind,
IReadOnlyList<string> attributes,
string name)
{
return rustKind switch
{
"mod" => CodeNodeKind.Namespace,
"struct" => CodeNodeKind.Struct,
"enum" => CodeNodeKind.Enum,
"trait" => CodeNodeKind.Interface,
"fn" when IsTest(attributes, name) => CodeNodeKind.TestCase,
"fn" => CodeNodeKind.Method,
_ => CodeNodeKind.Declaration
};
}
private static string NodeId(
string module,
RustDeclaration declaration,
string qualifiedName)
{
var kind = declaration.RustKind;
return kind == "impl"
? $"rust:impl:{module}:{CodeMeshHash.StableId(declaration.Signature)}"
: $"rust:{kind}:{module}:{qualifiedName}";
}
private static CodeRelationship Relationship(
string sourceNodeId,
string targetNodeId,
CodeRelationshipKind kind,
string? label,
string relativePath)
{
return new CodeRelationship(
CodeMeshHash.StableId("rust", kind.ToString(), sourceNodeId, targetNodeId, label ?? string.Empty),
sourceNodeId,
targetNodeId,
kind,
label,
new Dictionary<string, string> { ["filePath"] = relativePath });
}
private static void AddResolvedRelationship(
string sourceNodeId,
string? name,
IReadOnlyDictionary<string, BuiltDeclaration[]> targetsByName,
CodeRelationshipKind kind,
List<CodeRelationship> relationships,
string relativePath)
{
if (name is not null &&
targetsByName.TryGetValue(name.Split("::").Last(), out var targets) &&
targets.Length == 1)
{
relationships.Add(Relationship(
sourceNodeId,
targets[0].Node.Id,
kind,
name,
relativePath));
}
}
private static int FindDeclarationEnd(string[] lines, int startIndex)
{
var depth = 0;
var opened = false;
for (var index = startIndex; index < lines.Length; index++)
{
var line = StripLineComment(lines[index]);
foreach (var character in line)
{
if (character == '{')
{
opened = true;
depth++;
}
else if (character == '}' && opened)
{
depth--;
}
}
if (opened && depth <= 0)
{
return index + 1;
}
if (!opened && line.Contains(';'))
{
return index + 1;
}
}
return Math.Max(1, lines.Length);
}
private static string DeclarationStatement(string[] lines, int startIndex)
{
var parts = new List<string>();
for (var index = startIndex; index < Math.Min(lines.Length, startIndex + 12); index++)
{
var line = StripLineComment(lines[index]).Trim();
if (!string.IsNullOrWhiteSpace(line))
{
parts.Add(line);
}
if (line.Contains('{') || line.Contains(';'))
{
break;
}
}
return NormalizeWhitespace(string.Join(' ', parts));
}
private static string? PythonExportKind(IReadOnlyList<string> attributes)
{
var joined = string.Join(' ', attributes);
if (joined.Contains("pymodule", StringComparison.Ordinal)) return "module";
if (joined.Contains("pyclass", StringComparison.Ordinal)) return "class";
if (joined.Contains("pyfunction", StringComparison.Ordinal)) return "function";
if (joined.Contains("pymethods", StringComparison.Ordinal)) return "methods";
return null;
}
private static string? PythonExportName(IReadOnlyList<string> attributes)
{
var match = PyO3NameRegex().Match(string.Join(' ', attributes));
return match.Success ? match.Groups["name"].Value : null;
}
private static bool IsTest(IReadOnlyList<string> attributes, string name)
{
return name.StartsWith("test_", StringComparison.Ordinal) ||
attributes.Any(attribute =>
attribute.Contains("#[test]", StringComparison.Ordinal) ||
attribute.Contains("::test", StringComparison.Ordinal));
}
private static bool SignatureContainsType(string signature, string name)
{
return Regex.IsMatch(signature, $@"\b{Regex.Escape(name)}\b", RegexOptions.CultureInvariant);
}
private static string BodyOnly(string content)
{
var opening = content.IndexOf('{');
return opening >= 0 ? content[(opening + 1)..] : string.Empty;
}
private static string StripLineComment(string line)
{
var index = line.IndexOf("//", StringComparison.Ordinal);
return index >= 0 ? line[..index] : line;
}
private static string NormalizeWhitespace(string value)
{
return Regex.Replace(value, @"\s+", " ").Trim();
}
private static string? NullIfWhiteSpace(string value)
{
return string.IsNullOrWhiteSpace(value) ? null : value;
}
private static int LeadingColumn(string line)
{
var index = 0;
while (index < line.Length && char.IsWhiteSpace(line[index])) index++;
return index + 1;
}
private static string[] NormalizeLines(string text)
{
return text.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Split('\n');
}
private static IEnumerable<string> EnumerateRustFiles(
string repositoryRoot,
RepositoryPathFilter? pathFilter)
{
return RepositoryPathPolicy.EnumerateFiles(repositoryRoot, "*.rs", pathFilter)
.OrderBy(file => file, StringComparer.OrdinalIgnoreCase);
}
private static bool IsTestFile(string relativePath)
{
var segments = relativePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
return segments.Any(segment => string.Equals(segment, "tests", StringComparison.OrdinalIgnoreCase)) ||
Path.GetFileNameWithoutExtension(relativePath).EndsWith("_test", StringComparison.OrdinalIgnoreCase);
}
private static string ProjectName(string repositoryRoot)
{
return new DirectoryInfo(repositoryRoot).Name;
}
private static string ModuleName(string relativePath)
{
var path = Path.ChangeExtension(relativePath, null).Replace('\\', '/');
var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries).ToList();
if (parts.Count > 0 && string.Equals(parts[0], "src", StringComparison.OrdinalIgnoreCase))
{
parts.RemoveAt(0);
}
if (parts.Count > 0 && parts[^1] is "lib" or "main" or "mod")
{
parts.RemoveAt(parts.Count - 1);
}
return parts.Count == 0 ? "crate" : $"crate::{string.Join("::", parts)}";
}
private static string NormalizePath(string path)
{
return path.Replace('\\', '/');
}
private static ParseResult Failure(string message)
{
return new ParseResult(
Capability.WorkerName,
Capability.Language,
Array.Empty<CodeNode>(),
Array.Empty<CodeRelationship>(),
Array.Empty<CodeContent>(),
[new ParserDiagnostic("CMRS000", message, "error")],
DateTimeOffset.UtcNow);
}
private static readonly HashSet<string> IgnoredCallNames = new(StringComparer.Ordinal)
{
"as", "async", "await", "else", "for", "if", "loop", "match", "move", "return", "while"
};
[GeneratedRegex(@"^(?:(?:pub(?:\([^)]*\))?)\s+)?(?:(?:default|unsafe|const|async)\s+)*(?<kind>mod|struct|enum|trait|fn)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant)]
private static partial Regex DeclarationRegex();
[GeneratedRegex(@"^(?:(?:pub(?:\([^)]*\))?)\s+)?impl(?:\s*<[^>{}]*>)?\s+(?:(?<trait>[A-Za-z_][A-Za-z0-9_:]*)\s+for\s+)?(?<type>[A-Za-z_][A-Za-z0-9_:]*)\b", RegexOptions.CultureInvariant)]
private static partial Regex ImplRegex();
[GeneratedRegex(@"^(?:(?:pub(?:\([^)]*\))?)\s+)?use\s+(?<path>[^;]+);", RegexOptions.CultureInvariant)]
private static partial Regex UseRegex();
[GeneratedRegex(@"(?<![.])\b(?:[A-Za-z_][A-Za-z0-9_]*::)*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*!?\s*\(", RegexOptions.CultureInvariant)]
private static partial Regex CallRegex();
[GeneratedRegex(@"\.\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\(", RegexOptions.CultureInvariant)]
private static partial Regex MethodCallRegex();
[GeneratedRegex("\\bname\\s*=\\s*\"(?<name>[A-Za-z_][A-Za-z0-9_]*)\"", RegexOptions.CultureInvariant)]
private static partial Regex PyO3NameRegex();
private sealed record RustDeclaration(
string RustKind,
string Name,
CodeNodeKind NodeKind,
int StartLine,
int StartColumn,
int EndLine,
bool HasBody,
string Signature,
IReadOnlyList<string> Attributes,
string? TraitName,
string? TypeName);
private sealed record BuiltDeclaration(
RustDeclaration Declaration,
CodeNode Node,
string QualifiedName,
string Content);
}