Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Apr 14, 2022. It is now read-only.

Commit 3673741

Browse files
committed
Merge branch 'master' of github.com:microsoft/python-language-server into scratch/SuppressBinaryOp
2 parents 1613cc7 + 4e2d30f commit 3673741

File tree

15 files changed

+141
-85
lines changed

15 files changed

+141
-85
lines changed

src/Analysis/Ast/Impl/Analyzer/Handlers/FromImportHandler.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ private void AssignVariables(FromImportStatement node, IImportSearchResult impor
5959
// TODO: warn this is not a good style per
6060
// TODO: https://docs.python.org/3/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-module
6161
// TODO: warn this is invalid if not in the global scope.
62-
HandleModuleImportStar(variableModule);
62+
HandleModuleImportStar(variableModule, imports is ImplicitPackageImport);
6363
return;
6464
}
6565

@@ -75,14 +75,16 @@ private void AssignVariables(FromImportStatement node, IImportSearchResult impor
7575
}
7676
}
7777

78-
private void HandleModuleImportStar(PythonVariableModule variableModule) {
78+
private void HandleModuleImportStar(PythonVariableModule variableModule, bool isImplicitPackage) {
7979
if (variableModule.Module == Module) {
8080
// from self import * won't define any new members
8181
return;
8282
}
8383

8484
// If __all__ is present, take it, otherwise declare all members from the module that do not begin with an underscore.
85-
var memberNames = variableModule.Analysis.StarImportMemberNames ?? variableModule.GetMemberNames().Where(s => !s.StartsWithOrdinal("_"));
85+
var memberNames = isImplicitPackage
86+
? variableModule.GetMemberNames()
87+
: variableModule.Analysis.StarImportMemberNames ?? variableModule.GetMemberNames().Where(s => !s.StartsWithOrdinal("_"));
8688

8789
foreach (var memberName in memberNames) {
8890
var member = variableModule.GetMember(memberName);

src/Analysis/Ast/Impl/Analyzer/Handlers/ImportHandler.cs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,25 +55,28 @@ private void HandleImport(ModuleName moduleImportExpression, NameExpression asNa
5555
// import_module('fob.oar')
5656
// import_module('fob.oar.baz')
5757
var importNames = ImmutableArray<string>.Empty;
58-
var variableModule = default(PythonVariableModule);
59-
var importedNamesCount = 0;
58+
var lastModule = default(PythonVariableModule);
59+
var firstModule = default(PythonVariableModule);
6060
foreach (var nameExpression in moduleImportExpression.Names) {
6161
importNames = importNames.Add(nameExpression.Name);
6262
var imports = ModuleResolution.CurrentPathResolver.GetImportsFromAbsoluteName(Module.FilePath, importNames, forceAbsolute);
63-
if (!HandleImportSearchResult(imports, variableModule, asNameExpression, moduleImportExpression, out variableModule)) {
63+
if (!HandleImportSearchResult(imports, lastModule, asNameExpression, moduleImportExpression, out lastModule)) {
64+
lastModule = default;
6465
break;
6566
}
6667

67-
importedNamesCount++;
68+
if (firstModule == default) {
69+
firstModule = lastModule;
70+
}
6871
}
6972

7073
// "import fob.oar.baz as baz" is handled as baz = import_module('fob.oar.baz')
7174
// "import fob.oar.baz" is handled as fob = import_module('fob')
72-
if (!string.IsNullOrEmpty(asNameExpression?.Name) && importedNamesCount == moduleImportExpression.Names.Count) {
73-
Eval.DeclareVariable(asNameExpression.Name, variableModule, VariableSource.Import, asNameExpression);
74-
} else if (importedNamesCount > 0 && !string.IsNullOrEmpty(importNames[0]) && _variableModules.TryGetValue(importNames[0], out variableModule)) {
75+
if (!string.IsNullOrEmpty(asNameExpression?.Name) && lastModule != default) {
76+
Eval.DeclareVariable(asNameExpression.Name, lastModule, VariableSource.Import, asNameExpression);
77+
} else if (firstModule != default && !string.IsNullOrEmpty(importNames[0])) {
7578
var firstName = moduleImportExpression.Names[0];
76-
Eval.DeclareVariable(importNames[0], variableModule, VariableSource.Import, firstName);
79+
Eval.DeclareVariable(importNames[0], firstModule, VariableSource.Import, firstName);
7780
}
7881
}
7982

src/Analysis/Ast/Impl/Analyzer/PythonAnalyzerSession.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ private void AnalyzeEntry(IDependencyChainNode<PythonAnalyzerEntry> node, Python
348348

349349
private void LogCompleted(IDependencyChainNode<PythonAnalyzerEntry> node, IPythonModule module, Stopwatch stopWatch, TimeSpan startTime) {
350350
if (_log != null) {
351-
var completed = node != null && module.Analysis is LibraryAnalysis ? "completed" : "completed for library";
351+
var completed = node != null && module.Analysis is LibraryAnalysis ? "completed for library" : "completed ";
352352
var message = node != null
353353
? $"Analysis of {module.Name}({module.ModuleType}) on depth {node.VertexDepth} {completed} in {(stopWatch.Elapsed - startTime).TotalMilliseconds} ms."
354354
: $"Out of order analysis of {module.Name}({module.ModuleType}) completed in {(stopWatch.Elapsed - startTime).TotalMilliseconds} ms.";

src/Analysis/Ast/Impl/Modules/Definitions/IModuleManagement.cs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,6 @@ public interface IModuleManagement: IModuleResolution {
4141

4242
bool TryAddModulePath(in string path, in bool allowNonRooted, out string fullName);
4343

44-
/// <summary>
45-
/// Sets user search paths. This changes <see cref="IModuleResolution.CurrentPathResolver"/>.
46-
/// </summary>
47-
/// <returns>Added roots.</returns>
48-
IEnumerable<string> SetUserSearchPaths(in IEnumerable<string> searchPaths);
49-
5044
/// <summary>
5145
/// Provides ability to specialize module by replacing module import by
5246
/// <see cref="IPythonModule"/> implementation in code. Real module

src/Analysis/Ast/Impl/Modules/Resolution/MainModuleResolution.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -206,13 +206,10 @@ public async Task ReloadAsync(CancellationToken cancellationToken = default) {
206206
}
207207

208208
addedRoots.UnionWith(PathResolver.SetInterpreterSearchPaths(InterpreterPaths));
209-
addedRoots.UnionWith(SetUserSearchPaths(userSearchPaths));
209+
addedRoots.UnionWith(PathResolver.SetUserSearchPaths(userSearchPaths));
210210
ReloadModulePaths(addedRoots);
211211
}
212212

213-
public IEnumerable<string> SetUserSearchPaths(in IEnumerable<string> searchPaths)
214-
=> PathResolver.SetUserSearchPaths(searchPaths);
215-
216213
// For tests
217214
internal void AddUnimportableModule(string moduleName)
218215
=> Modules[moduleName] = new ModuleRef(new SentinelModule(moduleName, _services));

src/Analysis/Ast/Test/AnalysisTestBase.cs

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
// permissions and limitations under the License.
1515

1616
using System;
17+
using System.Collections.Generic;
1718
using System.Diagnostics;
1819
using System.IO;
1920
using System.Threading;
@@ -42,7 +43,7 @@ public abstract class AnalysisTestBase {
4243

4344
protected virtual IDiagnosticsService GetDiagnosticsService(IServiceContainer s) => null;
4445

45-
protected virtual ServiceManager CreateServiceManager() {
46+
protected ServiceManager CreateServiceManager() {
4647
Services = new ServiceManager();
4748

4849
var platform = new OSPlatform();
@@ -55,26 +56,23 @@ protected virtual ServiceManager CreateServiceManager() {
5556
return Services;
5657
}
5758

58-
protected string GetAnalysisTestDataFilesPath() => TestData.GetPath(Path.Combine("TestData", "AstAnalysis"));
59+
protected string GetAnalysisTestDataFilesPath() => TestData.GetPath("TestData", "AstAnalysis");
5960

60-
protected Task<IServiceManager> CreateServicesAsync(InterpreterConfiguration configuration, IServiceManager sm = null)
61-
=> CreateServicesAsync(TestData.GetTestSpecificRootUri().AbsolutePath, configuration, null, sm);
61+
protected Task<IServiceManager> CreateServicesAsync(InterpreterConfiguration configuration, string[] searchPaths = null)
62+
=> CreateServicesAsync(TestData.GetTestSpecificRootPath(), configuration, null, null, searchPaths);
6263

63-
protected async Task<IServiceManager> CreateServicesAsync(string root, InterpreterConfiguration configuration, string stubCacheFolderPath = null, IServiceManager sm = null) {
64+
protected async Task<IServiceManager> CreateServicesAsync(string root, InterpreterConfiguration configuration, string stubCacheFolderPath = null, IServiceManager sm = null, string[] searchPaths = null) {
6465
configuration = configuration ?? PythonVersions.LatestAvailable;
6566
configuration.AssertInstalled();
6667
stubCacheFolderPath = stubCacheFolderPath ?? TestData.GetAstAnalysisCachePath(configuration.Version, true);
6768
Trace.TraceInformation("Cache Path: " + stubCacheFolderPath);
68-
configuration.SearchPaths = new[] { GetAnalysisTestDataFilesPath() };
69+
configuration.SearchPaths = searchPaths ?? new[] { GetAnalysisTestDataFilesPath() };
6970
configuration.TypeshedPath = TestData.GetDefaultTypeshedPath();
7071

7172
sm = sm ?? CreateServiceManager();
7273

73-
var clientApp = Substitute.For<IClientApplication>();
74-
sm.AddService(clientApp);
75-
76-
var idle = Substitute.For<IIdleTimeService>();
77-
sm.AddService(idle);
74+
sm.AddService(Substitute.For<IClientApplication>())
75+
.AddService(Substitute.For<IIdleTimeService>());
7876

7977
var ds = GetDiagnosticsService(Services);
8078
if (ds != null) {
@@ -90,8 +88,7 @@ protected async Task<IServiceManager> CreateServicesAsync(string root, Interpret
9088
sm.AddService(interpreter);
9189

9290
TestLogger.Log(TraceEventType.Information, "Create RunningDocumentTable");
93-
var documentTable = new RunningDocumentTable(sm);
94-
sm.AddService(documentTable);
91+
sm.AddService(new RunningDocumentTable(sm));
9592

9693
return sm;
9794
}

src/Analysis/Ast/Test/TypeshedTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ public async Task TypeStubConditionalDefine() {
113113
}
114114

115115
Console.WriteLine(@"Testing with {0}", ver.InterpreterPath);
116-
using (var s = await CreateServicesAsync(TestData.Root, ver)) {
116+
using (var s = await CreateServicesAsync(ver)) {
117117
var analysis = await GetAnalysisAsync(code, s, @"testmodule", TestData.GetTestSpecificPath(@"testmodule.pyi"));
118118

119119
var expected = new List<string>();

src/Analysis/Core/Impl/DependencyResolution/PathResolverSnapshot.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ public IImportSearchResult GetImportsFromAbsoluteName(in string modulePath, in I
141141
}
142142

143143
var rootEdges = _roots.Select((r, i) => new Edge(i, r));
144-
if (!lastEdge.IsEmpty && !forceAbsolute) {
144+
if (!lastEdge.IsEmpty && !forceAbsolute && !lastEdge.Previous.IsFirst) {
145145
rootEdges = rootEdges.Prepend(lastEdge.Previous);
146146
}
147147

@@ -711,7 +711,7 @@ private bool TryFindModule(string modulePath, out Edge lastEdge, out StringSpan
711711
var rootIndex = 0;
712712
while (rootIndex < _roots.Count) {
713713
var rootPath = _roots[rootIndex].Name;
714-
if (normalizedPath.PathStartsWith(rootPath) && IsRootedPathEndsWithValidNames(normalizedPath, rootPath.Length)) {
714+
if (PathUtils.PathStartsWith(normalizedPath, rootPath) && IsRootedPathEndsWithValidNames(normalizedPath, rootPath.Length)) {
715715
break;
716716
}
717717

src/Analysis/Core/Impl/Interpreter/PythonLibraryPath.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ public static async Task<List<PythonLibraryPath>> GetSearchPathsFromInterpreterA
186186
try {
187187
var output = await ps.ExecuteAndCaptureOutputAsync(startInfo, cancellationToken);
188188
return output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Select(s => {
189-
if (s.PathStartsWith(tempWorkingDir)) {
189+
if (PathUtils.PathStartsWith(s, tempWorkingDir)) {
190190
return null;
191191
}
192192
try {

src/Core/Impl/Extensions/StringExtensions.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,6 @@ public static string QuoteArgument(this string arg) {
146146
return "\"{0}\"".FormatInvariant(arg);
147147
}
148148

149-
public static bool PathStartsWith(this string s, string prefix)
150-
=> s?.StartsWith(prefix, PathsStringComparison) ?? false;
151-
152149
public static bool StartsWithOrdinal(this string s, string prefix, bool ignoreCase = false)
153150
=> s?.StartsWith(prefix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
154151

0 commit comments

Comments
 (0)