This repository was archived by the owner on Apr 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathPathResolverSnapshot.cs
More file actions
757 lines (620 loc) · 34.1 KB
/
PathResolverSnapshot.cs
File metadata and controls
757 lines (620 loc) · 34.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
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Python.Core;
using Microsoft.Python.Core.IO;
using Microsoft.Python.Core.Text;
using Microsoft.Python.Parsing;
namespace Microsoft.Python.Analysis.Core.DependencyResolution {
public partial struct PathResolverSnapshot {
private static readonly bool IgnoreCaseInPaths = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
private static readonly StringComparison PathsStringComparison = IgnoreCaseInPaths ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
// This root contains module paths that don't belong to any known search path.
// The directory of the module is stored on the first level, and name is stored on the second level
// For example, "c:\dir\sub_dir2\module1.py" will be stored like this:
//
// [*]
// ┌────────────────╔═════════╝────────┬─────────────────┐
// [c:\dir\sub_dir] [c:\dir\sub_dir2] [c:\dir2\sub_dir] [c:\dir2\sub_dir2]
// ╔═════════╤════╝────┬─────────┐
// [module1] [module2] [module3] [module4]
//
// When search paths changes, nodes may be added or removed from this subtree
private readonly Node _nonRooted;
// This node contains available builtin modules.
private readonly Node _builtins;
private readonly PythonLanguageVersion _pythonLanguageVersion;
private readonly string _workDirectory;
private readonly string[] _interpreterSearchPaths;
private readonly string[] _userSearchPaths;
private readonly ImmutableArray<Node> _roots;
private readonly int _userRootsCount;
public int Version { get; }
public PathResolverSnapshot(PythonLanguageVersion pythonLanguageVersion)
: this(pythonLanguageVersion, string.Empty, Array.Empty<string>(), Array.Empty<string>(), ImmutableArray<Node>.Empty, 0, Node.CreateDefaultRoot(), Node.CreateBuiltinRoot(), default) { }
private PathResolverSnapshot(PythonLanguageVersion pythonLanguageVersion, string workDirectory, string[] userSearchPaths, string[] interpreterSearchPaths, ImmutableArray<Node> roots, int userRootsCount, Node nonRooted, Node builtins, int version) {
_pythonLanguageVersion = pythonLanguageVersion;
_workDirectory = workDirectory;
_userSearchPaths = userSearchPaths;
_interpreterSearchPaths = interpreterSearchPaths;
_roots = roots;
_userRootsCount = userRootsCount;
_nonRooted = nonRooted;
_builtins = builtins;
Version = version;
}
public IEnumerable<string> GetAllModuleNames() => GetModuleNames(_roots.Prepend(_nonRooted).Append(_builtins));
public IEnumerable<string> GetInterpreterModuleNames() => GetModuleNames(_roots.Skip(_userRootsCount).Append(_builtins));
private IEnumerable<string> GetModuleNames(IEnumerable<Node> roots) {
var builtins = new HashSet<Node>(_builtins.Children);
return roots.SelectMany(r => r.TraverseBreadthFirst(n => n.IsModule? Enumerable.Empty<Node>() : n.Children))
.Where(n => n.IsModule || builtins.Contains(n))
.Select(n => n.FullModuleName);
}
public ModuleImport GetModuleImportFromModuleName(in string fullModuleName) {
foreach (var root in _roots) {
var node = root;
var matched = true;
foreach (var nameSpan in fullModuleName.SplitIntoSpans('.')) {
var childIndex = node.GetChildIndex(nameSpan);
if (childIndex == -1) {
matched = false;
break;
}
node = node.Children[childIndex];
}
if (matched && TryCreateModuleImport(root, node, out var moduleImports)) {
return moduleImports;
}
}
if (fullModuleName.IndexOf('.') != -1) {
return default;
}
if (TryFindNonRootedModule(fullModuleName, out var moduleImport)) {
return moduleImport;
}
if (_builtins.TryGetChild(fullModuleName, out var builtin)) {
return new ModuleImport(builtin.Name, builtin.FullModuleName, null, null, true);
}
return default;
}
public IEnumerable<string> GetPossibleModuleStubPaths(in string fullModuleName) {
var firstDotIndex = fullModuleName.IndexOf('.');
if (firstDotIndex == -1) {
return Array.Empty<string>();
}
var relativeStubPath = new StringBuilder(fullModuleName)
.Replace('.', Path.DirectorySeparatorChar)
.Insert(firstDotIndex, "-stubs")
.Append(".pyi")
.ToString();
return _roots.Select(r => Path.Combine(r.Name, relativeStubPath));
}
[Pure]
public IImportSearchResult GetImportsFromAbsoluteName(in string modulePath, in IEnumerable<string> fullName, bool forceAbsolute) {
Edge lastEdge;
if (modulePath == null) {
lastEdge = default;
} else if (!TryFindModule(modulePath, out lastEdge, out _)) {
// Module wasn't found in current snapshot, but we still can search for some of the absolute paths
lastEdge = default;
}
var fullNameList = fullName.ToList();
if (fullNameList.Count == 1 && lastEdge.IsNonRooted && TryFindNonRootedModule(fullNameList[0], out var moduleImport)) {
return moduleImport;
}
var rootEdges = _roots.Select((r, i) => new Edge(i, r));
if (!lastEdge.IsEmpty && !forceAbsolute) {
rootEdges = rootEdges.Prepend(lastEdge.Previous);
}
if (TryFindImport(rootEdges, fullNameList, out var matchedEdges, out var shortestPath)) {
return TryGetSearchResults(matchedEdges, out var searchResult) ? searchResult : new ImportNotFound(string.Join(".", fullNameList));
}
if (fullNameList.Count == 1 && _builtins.TryGetChild(fullNameList[0], out var builtin)) {
return new ModuleImport(builtin.Name, builtin.FullModuleName, null, null, true);
}
// Special case for sys.modules
// If import wasn't found, but first parts of the import point to a module,
// it is possible that module defines a member that is also a module
// and there is a matching sys.modules key
// For example:
//
// ---module1.py---:
// import module2.mod as mod
// print(mod.VALUE)
//
// ---module2.py---:
// import module3 as mod
//
// ---module3.py---:
// import sys
// sys.modules['module2.mod'] = None
// VALUE = 42
if (shortestPath.PathLength > 0 && shortestPath.End.IsModule) {
var possibleFullName = string.Join(".", fullNameList);
var rootPath = shortestPath.FirstEdge.End.Name;
var existingModuleFullName = shortestPath.End.FullModuleName;
var remainingNameParts = fullNameList.Skip(shortestPath.PathLength - 1).ToList();
return new PossibleModuleImport(possibleFullName, rootPath, existingModuleFullName, remainingNameParts);
}
return new ImportNotFound(string.Join(".", fullNameList));
}
public IImportSearchResult GetImportsFromRelativePath(in string modulePath, in int parentCount, in IEnumerable<string> relativePath) {
if (modulePath == null || !TryFindModule(modulePath, out var lastEdge, out _)) {
// Module wasn't found in current snapshot, can't search for relative path
return default;
}
if (parentCount > lastEdge.PathLength) {
// Can't get outside of the root
return default;
}
var fullNameList = relativePath.ToList();
if (lastEdge.IsNonRooted) {
// Handle relative imports only for modules in the same folder
if (parentCount > 1) {
return default;
}
if (parentCount == 1 && fullNameList.Count == 1 && lastEdge.Start.TryGetChild(fullNameList[0], out var nameNode)) {
return new ModuleImport(fullNameList[0], fullNameList[0], lastEdge.Start.Name, nameNode.ModulePath, IsPythonCompiled(nameNode.ModulePath));
}
return new ImportNotFound(new StringBuilder(lastEdge.Start.Name)
.Append(".")
.Append(fullNameList)
.ToString());
}
var relativeParentEdge = lastEdge.GetPrevious(parentCount);
var rootEdges = new List<Edge>();
for (var i = 0; i < _roots.Count; i++) {
if (RootContains(i, relativeParentEdge, out var rootEdge)) {
rootEdges.Add(rootEdge);
}
}
if (TryFindImport(rootEdges, fullNameList, out var matchedEdges, out _) && TryGetSearchResults(matchedEdges, out var searchResult)) {
return searchResult;
}
if (relativeParentEdge.IsNonRooted) {
return default;
}
var fullName = GetFullModuleNameBuilder(relativeParentEdge).Append(".", fullNameList).ToString();
return new ImportNotFound(fullName);
}
private bool TryGetSearchResults(in ImmutableArray<Edge> matchedEdges, out IImportSearchResult searchResult) {
foreach (var edge in matchedEdges) {
if (TryCreateModuleImport(edge, out var moduleImport)) {
searchResult = moduleImport;
return true;
}
}
if (_pythonLanguageVersion.IsImplicitNamespacePackagesSupported()) {
return TryCreateNamespacePackageImports(matchedEdges, out searchResult);
}
searchResult = default;
return false;
}
private static bool TryCreateModuleImport(Edge lastEdge, out ModuleImport moduleImport)
=> TryCreateModuleImport(lastEdge.FirstEdge.End, lastEdge.End, out moduleImport);
private static bool TryCreateModuleImport(Node rootNode, Node moduleNode, out ModuleImport moduleImport) {
if (moduleNode.TryGetChild("__init__", out var initPyNode) && initPyNode.IsModule) {
moduleImport = new ModuleImport(moduleNode.Name, initPyNode.FullModuleName, rootNode.Name, initPyNode.ModulePath, false);
return true;
}
if (moduleNode.IsModule) {
moduleImport = new ModuleImport(moduleNode.Name, moduleNode.FullModuleName, rootNode.Name, moduleNode.ModulePath, IsPythonCompiled(moduleNode.ModulePath));
return true;
}
moduleImport = default;
return false;
}
private bool TryFindNonRootedModule(string moduleName, out ModuleImport moduleImport) {
foreach (var directoryNode in _nonRooted.Children) {
if (directoryNode.TryGetChild(moduleName, out var nameNode)) {
moduleImport = new ModuleImport(moduleName, moduleName, directoryNode.Name, nameNode.ModulePath, IsPythonCompiled(nameNode.ModulePath));
return true;
}
}
moduleImport = default;
return false;
}
private static bool TryCreateNamespacePackageImports(in ImmutableArray<Edge> matchedEdges, out IImportSearchResult searchResult) {
if (matchedEdges.Count == 0) {
searchResult = default;
return false;
}
var modules = new List<ModuleImport>();
var packageNames = new List<string>();
foreach (var edge in matchedEdges) {
var packageNode = edge.End;
var rootNode = edge.FirstEdge.End;
foreach (var child in packageNode.Children) {
if (TryCreateModuleImport(rootNode, child, out var moduleImports)) {
modules.Add(moduleImports);
} else {
packageNames.Add(child.Name);
}
}
}
searchResult = new PackageImport(matchedEdges[0].End.Name, modules.Distinct().ToArray(), packageNames.Distinct().ToArray());
return true;
}
public PathResolverSnapshot SetWorkDirectory(in string workDirectory, out IEnumerable<string> addedRoots) {
var normalizedRootDirectory = !string.IsNullOrEmpty(workDirectory) && Path.IsPathRooted(workDirectory)
? PathUtils.NormalizePath(workDirectory)
: string.Empty;
if (_workDirectory.Equals(normalizedRootDirectory, PathsStringComparison)) {
addedRoots = Enumerable.Empty<string>();
return this;
}
CreateRoots(normalizedRootDirectory, _userSearchPaths, _interpreterSearchPaths, out var newRoots, out var userRootsCount);
addedRoots = newRoots.Select(r => r.Name).Except(_roots.Select(n => n.Name));
return new PathResolverSnapshot(_pythonLanguageVersion, normalizedRootDirectory, _userSearchPaths, _interpreterSearchPaths, newRoots, userRootsCount, _nonRooted, _builtins, Version + 1);
}
public PathResolverSnapshot SetUserSearchPaths(in IEnumerable<string> searchPaths, out IEnumerable<string> addedRoots) {
var userSearchPaths = searchPaths.ToArray();
CreateRoots(_workDirectory, userSearchPaths, _interpreterSearchPaths, out var newRoots, out var userRootsCount);
addedRoots = newRoots.Select(r => r.Name).Except(_roots.Select(n => n.Name));
return new PathResolverSnapshot(_pythonLanguageVersion, _workDirectory, userSearchPaths, _interpreterSearchPaths, newRoots, userRootsCount, _nonRooted, _builtins, Version + 1);
}
public PathResolverSnapshot SetInterpreterPaths(in IEnumerable<string> searchPaths, out IEnumerable<string> addedRoots) {
var interpreterSearchPaths = searchPaths.ToArray();
CreateRoots(_workDirectory, _userSearchPaths, interpreterSearchPaths, out var newRoots, out var userRootsCount);
addedRoots = newRoots.Select(r => r.Name).Except(_roots.Select(n => n.Name));
return new PathResolverSnapshot(_pythonLanguageVersion, _workDirectory, _userSearchPaths, interpreterSearchPaths, newRoots, userRootsCount, _nonRooted, _builtins, Version + 1);
}
public PathResolverSnapshot SetBuiltins(in IEnumerable<string> builtinModuleNames) {
var builtins = ImmutableArray<Node>.Empty
.AddRange(builtinModuleNames.Select(Node.CreateBuiltinModule).ToArray());
return new PathResolverSnapshot(
_pythonLanguageVersion,
_workDirectory,
_userSearchPaths,
_interpreterSearchPaths,
_roots,
_userRootsCount,
_nonRooted,
Node.CreateBuiltinRoot(builtins),
Version + 1);
}
private void CreateRoots(string rootDirectory, string[] userSearchPaths, string[] interpreterSearchPaths, out ImmutableArray<Node> nodes, out int userRootsCount) {
if (rootDirectory != string.Empty) {
CreateRootsWithDefault(rootDirectory, userSearchPaths, interpreterSearchPaths, out nodes, out userRootsCount);
} else {
CreateRootsWithoutDefault(userSearchPaths, interpreterSearchPaths, out nodes, out userRootsCount);
}
}
private void CreateRootsWithDefault(string rootDirectory, string[] userSearchPaths, string[] interpreterSearchPaths, out ImmutableArray<Node> nodes, out int userRootsCount) {
var filteredUserSearchPaths = userSearchPaths.Select(FixPath)
.Except(new[] { rootDirectory })
.ToArray();
var filteredInterpreterSearchPaths = interpreterSearchPaths.Select(FixPath)
.Except(filteredUserSearchPaths.Append(rootDirectory))
.ToArray();
userRootsCount = filteredUserSearchPaths.Length + 1;
nodes = AddRootsFromSearchPaths(rootDirectory, filteredUserSearchPaths, filteredInterpreterSearchPaths);
string FixPath(string p) => Path.IsPathRooted(p) ? PathUtils.NormalizePath(p) : PathUtils.NormalizePath(Path.Combine(rootDirectory, p));
}
private void CreateRootsWithoutDefault(string[] userSearchPaths, string[] interpreterSearchPaths, out ImmutableArray<Node> nodes, out int userRootsCount) {
var filteredUserSearchPaths = userSearchPaths
.Where(Path.IsPathRooted)
.Select(PathUtils.NormalizePath)
.ToArray();
var filteredInterpreterSearchPaths = interpreterSearchPaths
.Where(Path.IsPathRooted)
.Select(PathUtils.NormalizePath)
.Except(filteredUserSearchPaths)
.ToArray();
userRootsCount = filteredUserSearchPaths.Length;
nodes = AddRootsFromSearchPaths(filteredUserSearchPaths, filteredInterpreterSearchPaths);
}
private ImmutableArray<Node> AddRootsFromSearchPaths(string rootDirectory, string[] userSearchPaths, string[] interpreterSearchPaths) {
return ImmutableArray<Node>.Empty
.AddRange(userSearchPaths.Select(GetOrCreateRoot).ToArray())
.Add(GetOrCreateRoot(rootDirectory))
.AddRange(interpreterSearchPaths.Select(GetOrCreateRoot).ToArray());
}
private ImmutableArray<Node> AddRootsFromSearchPaths(string[] userSearchPaths, string[] interpreterSearchPaths) {
return ImmutableArray<Node>.Empty
.AddRange(userSearchPaths.Select(GetOrCreateRoot).ToArray())
.AddRange(interpreterSearchPaths.Select(GetOrCreateRoot).ToArray());
}
private Node GetOrCreateRoot(string path)
=> _roots.FirstOrDefault(r => r.Name.Equals(path, PathsStringComparison)) ?? Node.CreateRoot(path);
public PathResolverSnapshot AddModulePath(in string modulePath, out string fullModuleName) {
var isFound = TryFindModule(modulePath, out var lastEdge, out var unmatchedPathSpan);
if (unmatchedPathSpan.Source == default) {
// Not a module
fullModuleName = null;
return this;
}
if (isFound) {
// Module is already added
fullModuleName = lastEdge.End.FullModuleName;
return this;
}
if (lastEdge.IsNonRooted) {
return ReplaceNonRooted(AddToNonRooted(lastEdge, unmatchedPathSpan, out fullModuleName));
}
var newChildNode = CreateNewNodes(lastEdge, unmatchedPathSpan, out fullModuleName);
if (unmatchedPathSpan.Length == 0) {
lastEdge = lastEdge.Previous;
}
var newEnd = lastEdge.End.AddChild(newChildNode);
var newRoot = UpdateNodesFromEnd(lastEdge, newEnd);
return ImmutableReplaceRoot(newRoot, lastEdge.FirstEdge.EndIndex);
}
public PathResolverSnapshot RemoveModulePath(in string modulePath) {
if (!TryFindModule(modulePath, out var lastEdge, out _)) {
// Module not found or found package in place of a module
return this;
}
var moduleNode = lastEdge.End;
var moduleParent = lastEdge.Start;
var moduleIndex = lastEdge.EndIndex;
var newParent = moduleNode.Children.Count > 0
? moduleParent.ReplaceChildAt(moduleNode.ToPackage(), moduleIndex) // preserve node as package
: moduleParent.RemoveChildAt(moduleIndex);
if (lastEdge.IsNonRooted) {
var directoryIndex = lastEdge.Previous.EndIndex;
return ReplaceNonRooted(_nonRooted.ReplaceChildAt(newParent, directoryIndex));
}
lastEdge = lastEdge.Previous;
var newRoot = UpdateNodesFromEnd(lastEdge, newParent);
return ImmutableReplaceRoot(newRoot, lastEdge.FirstEdge.EndIndex);
}
private bool MatchNodePathInNonRooted(string normalizedPath, out Edge lastEdge, out StringSpan unmatchedPathSpan) {
var root = _nonRooted;
var moduleNameStart = GetModuleNameStart(normalizedPath);
var moduleNameEnd = GetModuleNameEnd(normalizedPath);
var directorySpan = normalizedPath.Slice(0, moduleNameStart - 1);
var nameSpan = normalizedPath.Slice(moduleNameStart, moduleNameEnd - moduleNameStart);
var directoryNodeIndex = _nonRooted.GetChildIndex(directorySpan);
lastEdge = new Edge(0, root);
if (directoryNodeIndex == -1) {
unmatchedPathSpan = normalizedPath.Slice(0, moduleNameEnd);
return false;
}
lastEdge = lastEdge.Append(directoryNodeIndex);
var nameNodeIndex = lastEdge.End.GetChildIndex(nameSpan);
if (nameNodeIndex == -1) {
unmatchedPathSpan = nameSpan;
return false;
}
lastEdge = lastEdge.Append(nameNodeIndex);
unmatchedPathSpan = new StringSpan(normalizedPath, -1, 0);
return true;
}
private bool MatchNodePath(in string normalizedModulePath, in int rootIndex, out Edge lastEdge, out StringSpan unmatchedPathSpan) {
var root = _roots[rootIndex];
var modulePathLength = GetModuleNameEnd(normalizedModulePath); // exclude extension
lastEdge = new Edge(rootIndex, root);
unmatchedPathSpan = new StringSpan(normalizedModulePath, -1, 0);
foreach (var nameSpan in normalizedModulePath.SplitIntoSpans(Path.DirectorySeparatorChar, root.Name.Length, modulePathLength - root.Name.Length)) {
var childIndex = lastEdge.End.GetChildIndex(nameSpan);
if (childIndex == -1) {
unmatchedPathSpan = normalizedModulePath.Slice(nameSpan.Start, modulePathLength - nameSpan.Start);
break;
}
lastEdge = lastEdge.Append(childIndex);
}
return unmatchedPathSpan.Length == 0 && lastEdge.End.IsModule;
}
private static bool TryFindImport(IEnumerable<Edge> rootEdges, List<string> fullNameList, out ImmutableArray<Edge> matchedEdges, out Edge shortestPath) {
shortestPath = default;
matchedEdges = ImmutableArray<Edge>.Empty;
foreach (var rootEdge in rootEdges) {
if (TryFindName(rootEdge, fullNameList, out var lastEdge)) {
matchedEdges = matchedEdges.Add(lastEdge);
}
if (lastEdge.End.IsModule && (shortestPath.IsEmpty || lastEdge.PathLength < shortestPath.PathLength)) {
shortestPath = lastEdge;
}
}
return matchedEdges.Count > 0;
}
private static bool TryFindName(in Edge edge, in IEnumerable<string> nameParts, out Edge lastEdge) {
lastEdge = edge;
foreach (var name in nameParts) {
if (lastEdge.End.IsModule) {
return false;
}
var index = lastEdge.End.GetChildIndex(name);
if (index == -1) {
return false;
}
lastEdge = lastEdge.Append(index);
}
return true;
}
private bool RootContains(in int rootIndex, in Edge lastEdge, out Edge rootEdge) {
var root = _roots[rootIndex];
var sourceEdge = lastEdge.FirstEdge;
var targetEdge = new Edge(rootIndex, root);
while (sourceEdge != lastEdge) {
var targetNode = targetEdge.End;
var nextSourceNode = sourceEdge.Next.End;
var childIndex = targetNode.GetChildIndex(nextSourceNode.Name);
if (childIndex == -1) {
rootEdge = default;
return false;
}
sourceEdge = sourceEdge.Next;
targetEdge = targetEdge.Append(childIndex);
}
rootEdge = targetEdge;
return true;
}
private Node AddToNonRooted(in Edge lastEdge, in StringSpan unmatchedPathSpan, out string fullModuleName) {
var (modulePath, unmatchedPathStart, unmatchedPathLength) = unmatchedPathSpan;
var moduleNameStart = GetModuleNameStart(modulePath);
var directoryIsKnown = unmatchedPathStart == moduleNameStart;
fullModuleName = directoryIsKnown
? modulePath.Substring(moduleNameStart, unmatchedPathLength)
: modulePath.Substring(moduleNameStart, unmatchedPathLength - moduleNameStart);
var moduleNode = Node.CreateModule(fullModuleName, modulePath, fullModuleName);
if (!directoryIsKnown) {
var directory = modulePath.Substring(0, moduleNameStart - 1);
return _nonRooted.AddChild(Node.CreatePackage(directory, moduleNode));
}
var directoryIndex = lastEdge.EndIndex;
var directoryNode = lastEdge.End.AddChild(moduleNode);
return _nonRooted.ReplaceChildAt(directoryNode, directoryIndex);
}
private static Node CreateNewNodes(in Edge lastEdge, in StringSpan unmatchedPathSpan, out string fullModuleName) {
var (modulePath, unmatchedPathStart, unmatchedPathLength) = unmatchedPathSpan;
if (unmatchedPathLength == 0) {
// Module name matches name of existing package
fullModuleName = GetFullModuleName(lastEdge);
return lastEdge.End.ToModuleNode(modulePath, fullModuleName);
}
if (unmatchedPathStart == GetModuleNameStart(modulePath)) {
// Module is added to existing package
var name = modulePath.Substring(unmatchedPathStart, unmatchedPathLength);
fullModuleName = GetFullModuleName(lastEdge, name);
return Node.CreateModule(name, modulePath, fullModuleName);
}
var names = modulePath.Split(Path.DirectorySeparatorChar, unmatchedPathStart, unmatchedPathLength);
fullModuleName = GetFullModuleName(lastEdge, names);
var newNode = Node.CreateModule(names.Last(), modulePath, fullModuleName);
for (var i = names.Length - 2; i >= 0; i--) {
newNode = Node.CreatePackage(names[i], newNode);
}
return newNode;
}
private static string GetFullModuleName(in Edge lastEdge) {
if (lastEdge.IsFirst) {
return string.Empty;
}
var sb = GetFullModuleNameBuilder(lastEdge);
if (lastEdge.End.IsModule) {
AppendNameIfNotInitPy(sb, lastEdge.End.Name);
} else {
AppendName(sb, lastEdge.End.Name);
}
return sb.ToString();
}
private static string GetFullModuleName(in Edge lastEdge, string name) {
if (lastEdge.IsFirst) {
return IsNotInitPy(name) ? name : string.Empty;
}
var sb = GetFullModuleNameBuilder(lastEdge);
AppendName(sb, lastEdge.End.Name);
AppendNameIfNotInitPy(sb, name);
return sb.ToString();
}
private static string GetFullModuleName(in Edge lastEdge, string[] names) {
var sb = GetFullModuleNameBuilder(lastEdge);
if (!lastEdge.IsFirst) {
AppendName(sb, lastEdge.End.Name);
sb.Append('.');
}
sb.Append(".", names, 0, names.Length - 1);
AppendNameIfNotInitPy(sb, names.Last());
return sb.ToString();
}
private static StringBuilder GetFullModuleNameBuilder(in Edge lastEdge) {
if (lastEdge.IsNonRooted) {
throw new InvalidOperationException($"{nameof(GetFullModuleNameBuilder)} should be called only for real root!");
}
var edge = lastEdge.FirstEdge;
var sb = new StringBuilder();
if (lastEdge.IsFirst) {
return sb;
}
edge = edge.Next;
while (edge != lastEdge) {
AppendName(sb, edge.End.Name);
edge = edge.Next;
};
return sb;
}
private static void AppendNameIfNotInitPy(StringBuilder builder, string name) {
if (IsNotInitPy(name)) {
AppendName(builder, name);
}
}
private static void AppendName(StringBuilder builder, string name)
=> builder.AppendIf(builder.Length > 0, ".").Append(name);
private static Node UpdateNodesFromEnd(Edge lastEdge, Node newEnd) {
while (lastEdge.Start != default) {
var newStart = lastEdge.Start.ReplaceChildAt(newEnd, lastEdge.EndIndex);
lastEdge = lastEdge.Previous;
newEnd = newStart;
}
return newEnd;
}
private bool TryFindModule(string modulePath, out Edge lastEdge, out StringSpan unmatchedPathSpan) {
if (!Path.IsPathRooted(modulePath)) {
throw new InvalidOperationException("Module path should be rooted");
}
var normalizedPath = PathUtils.NormalizePath(modulePath);
if (!IsRootedPathEndsWithPythonFile(normalizedPath)) {
lastEdge = default;
unmatchedPathSpan = new StringSpan(null, -1, 0);
return false;
}
var rootIndex = 0;
while (rootIndex < _roots.Count) {
var rootPath = _roots[rootIndex].Name;
if (normalizedPath.StartsWithOrdinal(rootPath, IgnoreCaseInPaths) && IsRootedPathEndsWithValidNames(normalizedPath, rootPath.Length)) {
break;
}
rootIndex++;
}
// Search for module in root, or in
return rootIndex < _roots.Count
? MatchNodePath(normalizedPath, rootIndex, out lastEdge, out unmatchedPathSpan)
: MatchNodePathInNonRooted(normalizedPath, out lastEdge, out unmatchedPathSpan);
}
private static bool IsRootedPathEndsWithValidNames(string rootedPath, int start) {
var nameSpan = (start: 0, length: start);
var modulePathLength = GetModuleNameEnd(rootedPath); // exclude extension
while (rootedPath.TryGetNextNonEmptySpan(Path.DirectorySeparatorChar, modulePathLength, ref nameSpan)) {
if (!IsValidIdentifier(rootedPath, nameSpan.start, nameSpan.length)) {
return false;
}
}
return true;
}
private static bool IsRootedPathEndsWithPythonFile(string rootedPath) {
if (!IsPythonFile(rootedPath) && !IsPythonCompiled(rootedPath)) {
return false;
}
var moduleNameStart = GetModuleNameStart(rootedPath);
var moduleNameLength = GetModuleNameEnd(rootedPath) - moduleNameStart;
return IsValidIdentifier(rootedPath, moduleNameStart, moduleNameLength);
}
private static bool IsValidIdentifier(string str, int start, int length)
=> str[start].IsLatin1LetterOrUnderscore() && str.CharsAreLatin1LetterOrDigitOrUnderscore(start + 1, length - 1);
private static bool IsPythonFile(string rootedPath)
=> rootedPath.EndsWithAnyOrdinal(new[] { ".py", ".pyi", ".pyw" }, IgnoreCaseInPaths);
private static bool IsPythonCompiled(string rootedPath)
=> rootedPath.EndsWithAnyOrdinal(new[] { ".pyd", ".so", ".dylib" }, IgnoreCaseInPaths);
private static int GetModuleNameStart(string rootedModulePath)
=> rootedModulePath.LastIndexOf(Path.DirectorySeparatorChar) + 1;
private static int GetModuleNameEnd(string rootedModulePath)
=> IsPythonCompiled(rootedModulePath) ? rootedModulePath.IndexOf('.', GetModuleNameStart(rootedModulePath)) : rootedModulePath.LastIndexOf('.');
private static bool IsNotInitPy(string name)
=> !name.EqualsOrdinal("__init__");
private PathResolverSnapshot ReplaceNonRooted(Node nonRooted)
=> new PathResolverSnapshot(_pythonLanguageVersion, _workDirectory, _userSearchPaths, _interpreterSearchPaths, _roots, _userRootsCount, nonRooted, _builtins, Version + 1);
private PathResolverSnapshot ImmutableReplaceRoot(Node root, int index)
=> new PathResolverSnapshot(_pythonLanguageVersion, _workDirectory, _userSearchPaths, _interpreterSearchPaths, _roots.ReplaceAt(index, root), _userRootsCount, _nonRooted, _builtins, Version + 1);
}
}