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

Ensure builtins module is created synchronously #1798

Merged
merged 22 commits into from
Nov 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
c6a9c22
Remove stale reference
Sep 30, 2019
1360827
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 1, 2019
ccaaa02
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 4, 2019
da40dcc
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 4, 2019
c348ac3
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 5, 2019
53bc044
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 7, 2019
484a92a
Merge branch 'master' of https://github.com/MikhailArkhipov/python-la…
Oct 7, 2019
e6df3aa
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 8, 2019
1d289d8
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 8, 2019
126f355
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 12, 2019
7e715f3
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 25, 2019
32923a5
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 31, 2019
1b72f4b
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 2, 2019
f74d5b6
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 7, 2019
0b28fa4
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 12, 2019
6109ac7
Don't suppress LHS diagnostics on augmented assign
Nov 12, 2019
bcfc3b7
Revert "Don't suppress LHS diagnostics on augmented assign"
Nov 12, 2019
dc286b8
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 13, 2019
1f716e8
Sync builtins creation
Nov 15, 2019
e304507
Sync builtins
Nov 15, 2019
6e1a119
Usings
Nov 15, 2019
6093070
Debug code
Nov 15, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/Analysis/Ast/Impl/Analyzer/Definitions/IAnalyzable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// permissions and limitations under the License.

using Microsoft.Python.Analysis.Dependencies;
using Microsoft.Python.Parsing.Ast;

namespace Microsoft.Python.Analysis.Analyzer {
/// <summary>
Expand All @@ -30,6 +31,11 @@ internal interface IAnalyzable {
/// </summary>
void NotifyAnalysisBegins();

/// <summary>
/// Performs standard analysis pass. Does not include any restoration from databases.
/// </summary>
ModuleWalker Analyze(PythonAst ast);

/// <summary>
/// Notifies document that its analysis is now complete.
/// </summary>
Expand Down
10 changes: 5 additions & 5 deletions src/Analysis/Ast/Impl/Analyzer/PythonAnalyzerSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -527,11 +527,11 @@ private IDocumentAnalysis RestoreOrAnalyzeModule(IDependencyChainSingleNode<Pyth
return analysis;
}

var eval = new ExpressionEval(_services, module, ast);
var walker = new ModuleWalker(eval, SimpleImportedVariableHandler.Instance);
ast.Walk(walker);
walker.Complete();
return CreateAnalysis(node, (IDocument)module, ast, version, walker);
if (module is IAnalyzable analyzable) {
var walker = analyzable.Analyze(ast);
return CreateAnalysis(node, (IDocument)module, ast, version, walker);
}
return new EmptyAnalysis(_services, (IDocument)module);
}

private bool MarkNodeWalked(IDependencyChainNode node) {
Expand Down
1 change: 0 additions & 1 deletion src/Analysis/Ast/Impl/Analyzer/PythonInterpreter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
using Microsoft.Python.Analysis.Modules.Resolution;
using Microsoft.Python.Analysis.Specializations.Typing;
using Microsoft.Python.Analysis.Types;
using Microsoft.Python.Analysis.Values;
using Microsoft.Python.Core;
using Microsoft.Python.Core.Collections;
using Microsoft.Python.Core.Services;
Expand Down
16 changes: 15 additions & 1 deletion src/Analysis/Ast/Impl/Modules/BuiltinsPythonModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.Python.Analysis.Analyzer;
using Microsoft.Python.Analysis.Specializations;
using Microsoft.Python.Analysis.Specializations.Typing;
using Microsoft.Python.Analysis.Types;
using Microsoft.Python.Analysis.Values;
using Microsoft.Python.Core;
Expand All @@ -41,15 +42,28 @@ internal sealed class BuiltinsPythonModule : CompiledPythonModule, IBuiltinsPyth
public BuiltinsPythonModule(string moduleName, string filePath, IServiceContainer services)
: base(moduleName, ModuleType.Builtins, filePath, null, false, false, services) { } // TODO: builtins stub & persistence

#region IMemberContainer
public override IMember GetMember(string name) => _hiddenNames.Contains(name) ? null : base.GetMember(name);

public IMember GetAnyMember(string name) => base.GetMember(name);

public override IEnumerable<string> GetMemberNames() => base.GetMemberNames().Except(_hiddenNames).ToArray();
#endregion

public void Initialize() => ParseAndLogExceptions(CancellationToken.None);

protected override string[] GetScrapeArguments(IPythonInterpreter interpreter)
=> !InstallPath.TryGetFile("scrape_module.py", out var sb) ? null : new[] { "-W", "ignore", "-B", "-E", sb };

protected override void Parse() { }

protected override void Analyze(PythonAst ast, int version) {
NotifyAnalysisBegins();
var walker = Analyze(ast);
var analysis = new DocumentAnalysis(this, version, walker.GlobalScope, walker.Eval, walker.StarImportMemberNames);
NotifyAnalysisComplete(analysis);
}

protected override void OnAnalysisComplete() {
SpecializeTypes();
SpecializeFunctions();
Expand Down
33 changes: 22 additions & 11 deletions src/Analysis/Ast/Impl/Modules/PythonModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Python.Analysis.Analyzer;
using Microsoft.Python.Analysis.Analyzer.Evaluation;
using Microsoft.Python.Analysis.Analyzer.Handlers;
using Microsoft.Python.Analysis.Dependencies;
using Microsoft.Python.Analysis.Diagnostics;
using Microsoft.Python.Analysis.Documents;
using Microsoft.Python.Analysis.Specializations.Typing;
using Microsoft.Python.Analysis.Types;
using Microsoft.Python.Analysis.Values;
using Microsoft.Python.Core;
Expand Down Expand Up @@ -305,7 +306,7 @@ public void Invalidate() {
Services.GetService<IPythonAnalyzer>().InvalidateAnalysis(this);
}

private void Parse() {
protected virtual void Parse() {
_parseCts?.Cancel();
_parseCts = new CancellationTokenSource();

Expand All @@ -316,7 +317,7 @@ private void Parse() {
_parsingTask = Task.Run(() => ParseAndLogExceptions(_linkedParseCts.Token), _linkedParseCts.Token);
}

private void ParseAndLogExceptions(CancellationToken cancellationToken) {
protected void ParseAndLogExceptions(CancellationToken cancellationToken) {
try {
Parse(cancellationToken);
} catch (Exception ex) when (!(ex is OperationCanceledException)) {
Expand All @@ -325,6 +326,15 @@ private void ParseAndLogExceptions(CancellationToken cancellationToken) {
}
}

protected virtual void Analyze(PythonAst ast, int version) {
if (ContentState < State.Analyzing) {
ContentState = State.Analyzing;

var analyzer = Services.GetService<IPythonAnalyzer>();
analyzer.EnqueueDocumentForAnalysis(this, ast, version);
}
}

private void Parse(CancellationToken cancellationToken) {
CollectingErrorSink sink = null;
int version;
Expand All @@ -345,7 +355,6 @@ private void Parse(CancellationToken cancellationToken) {
}

var ast = parser.ParseFile(Uri);

// Log?.Log(TraceEventType.Verbose, $"Parse complete: {Name} ({ModuleType})");

lock (_syncObj) {
Expand All @@ -370,13 +379,7 @@ private void Parse(CancellationToken cancellationToken) {
}

NewAst?.Invoke(this, EventArgs.Empty);

if (ContentState < State.Analyzing) {
ContentState = State.Analyzing;

var analyzer = Services.GetService<IPythonAnalyzer>();
analyzer.EnqueueDocumentForAnalysis(this, ast, version);
}
Analyze(ast, version);

lock (_syncObj) {
_parsingTask = null;
Expand Down Expand Up @@ -423,6 +426,14 @@ public void NotifyAnalysisBegins() {
}
}

public ModuleWalker Analyze(PythonAst ast) {
var eval = new ExpressionEval(Services, this, ast);
var walker = new ModuleWalker(eval, SimpleImportedVariableHandler.Instance);
ast.Walk(walker);
walker.Complete();
return walker;
}

public void NotifyAnalysisComplete(IDocumentAnalysis analysis) {
lock (_syncObj) {
if (analysis.Version < Analysis.Version) {
Expand Down
19 changes: 8 additions & 11 deletions src/Analysis/Ast/Impl/Modules/Resolution/MainModuleResolution.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ namespace Microsoft.Python.Analysis.Modules.Resolution {
internal sealed class MainModuleResolution : ModuleResolutionBase, IModuleManagement {
private readonly ConcurrentDictionary<string, IPythonModule> _specialized = new ConcurrentDictionary<string, IPythonModule>();
private readonly IUIService _ui;
private BuiltinsPythonModule _builtins;
private IModuleDatabaseService _dbService;
private IRunningDocumentTable _rdt;

Expand All @@ -53,7 +54,7 @@ public MainModuleResolution(string root, IServiceContainer services, ImmutableAr
public string BuiltinModuleName => BuiltinTypeId.Unknown.GetModuleName(Interpreter.LanguageVersion);
public ImmutableArray<PythonLibraryPath> LibraryPaths { get; private set; } = ImmutableArray<PythonLibraryPath>.Empty;

public IBuiltinsPythonModule BuiltinsModule { get; private set; }
public IBuiltinsPythonModule BuiltinsModule => _builtins;

public IEnumerable<IPythonModule> GetImportedModules(CancellationToken cancellationToken) {
foreach (var module in _specialized.Values) {
Expand Down Expand Up @@ -185,12 +186,8 @@ public IPythonModule GetSpecializedModule(string fullName, bool allowCreation =
public bool IsSpecializedModule(string fullName, string modulePath = null)
=> _specialized.ContainsKey(fullName);

private async Task AddBuiltinTypesToPathResolverAsync(CancellationToken cancellationToken = default) {
var analyzer = Services.GetService<IPythonAnalyzer>();
await analyzer.GetAnalysisAsync(BuiltinsModule, Timeout.Infinite, cancellationToken);

private void AddBuiltinTypesToPathResolver() {
Check.InvalidOperation(!(BuiltinsModule.Analysis is EmptyAnalysis), "Builtins analysis did not complete correctly.");

// Add built-in module names
var builtinModuleNamesMember = BuiltinsModule.GetAnyMember("__builtin_module_names__");
var value = builtinModuleNamesMember is IVariable variable ? variable.Value : builtinModuleNamesMember;
Expand Down Expand Up @@ -222,16 +219,16 @@ public async Task ReloadAsync(CancellationToken cancellationToken = default) {
ReloadModulePaths(addedRoots, cancellationToken);

if (!builtinsIsCreated) {
var builtinsModule = CreateBuiltinsModule(Services, Interpreter, StubCache);
BuiltinsModule = builtinsModule;
builtinsRef = new ModuleRef(builtinsModule);
_builtins = CreateBuiltinsModule(Services, Interpreter, StubCache);
builtinsRef = new ModuleRef(_builtins);
_builtins.Initialize();
}

Modules[BuiltinModuleName] = builtinsRef;
await AddBuiltinTypesToPathResolverAsync(cancellationToken);
AddBuiltinTypesToPathResolver();
}

private static IBuiltinsPythonModule CreateBuiltinsModule(IServiceContainer services, IPythonInterpreter interpreter, IStubCache stubCache) {
private static BuiltinsPythonModule CreateBuiltinsModule(IServiceContainer services, IPythonInterpreter interpreter, IStubCache stubCache) {
var moduleName = BuiltinTypeId.Unknown.GetModuleName(interpreter.LanguageVersion);
var modulePath = stubCache.GetCacheFilePath(interpreter.Configuration.InterpreterPath);
return new BuiltinsPythonModule(moduleName, modulePath, services);
Expand Down