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

Prefer stub content when stub is available #1845

Open
wants to merge 136 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
136 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
745a3eb
Fix saving of ALL import statements
Oct 25, 2019
2a1ca14
Attributes
Oct 26, 2019
91f3ca6
Initial
Oct 26, 2019
b2e92ff
Partial
Oct 28, 2019
32923a5
Merge branch 'master' of https://github.com/microsoft/python-language…
Oct 31, 2019
9b691e6
Part I
Nov 1, 2019
9612990
Test pass
Nov 2, 2019
1b72f4b
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 2, 2019
2fa422b
Partial proxies
Nov 4, 2019
832d981
Initial lazy types
Nov 4, 2019
d613300
Fix test
Nov 4, 2019
cdc7875
AST library test passed
Nov 4, 2019
9e6917b
Fix more tests
Nov 4, 2019
960ee87
Fix generics
Nov 5, 2019
45ed4eb
Handle specialization in dependencies
Nov 5, 2019
fd7a285
Merge master
Nov 5, 2019
68b2f3b
Merge issues
Nov 5, 2019
e68e1b6
Fix os test (posix stub)
Nov 5, 2019
800e231
Fix sys.stdin case
Nov 5, 2019
d49e246
Better handle circular references, cache models and resolve os.path
Nov 5, 2019
013df6a
Improve stub handling
Nov 5, 2019
5ebcdfe
Test fixes
Nov 6, 2019
3fff06f
Test updates
Nov 6, 2019
a928741
Fix deadlock
Nov 6, 2019
da64646
Simplify
Nov 6, 2019
a5bc47f
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 6, 2019
2b93042
Properly handle caching level setting
Nov 6, 2019
2abe2cf
Caching level fix
Nov 6, 2019
4711d90
Fix endless analysis
Nov 6, 2019
fdbf219
Fix 'missing keys' message with cached modules
Nov 6, 2019
01f763b
Optimize IO
Nov 6, 2019
d569619
More IO optimizations
Nov 7, 2019
f74d5b6
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 7, 2019
2a64510
Full restore tests
Nov 7, 2019
f2bd272
Deeper comparison in tests
Nov 8, 2019
d8b46ba
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 8, 2019
d7ca27f
Fix instance/class mismatch in operators eval
Nov 8, 2019
79e8b2d
Properly handle variables in type.AddMember
Nov 8, 2019
f197a6d
Fix function inner members restore
Nov 8, 2019
3f9ee9a
Cache models by qualified name
Nov 10, 2019
7a488b3
Don't restore all members on GetMember. Improves tensorflow by 30%
Nov 10, 2019
c5f2cb8
Turn off indexing of libraries, 25%
Nov 11, 2019
dee8420
optimize db access
Nov 11, 2019
d7a6fea
fix test
Nov 11, 2019
f109701
Remove debug code
Nov 11, 2019
c4891cf
Fix comment
Nov 11, 2019
6726924
Delete debug file
Nov 11, 2019
1d0b1ba
Bump up db version
Nov 11, 2019
36aba0b
Bump db version to 5
Nov 11, 2019
8b4942c
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 11, 2019
e155470
Test fix
Nov 11, 2019
e0de03e
Handle empty bases
Nov 11, 2019
a2caf6a
Fix one more 'missing keys' case
Nov 11, 2019
aa60787
Remove null declaring module from iterators
Nov 11, 2019
d9db6a3
Add queued cache write
Nov 11, 2019
3f9e96f
Dispose writer
Nov 11, 2019
cd60912
Formatting
Nov 11, 2019
72dd9c8
Simplify unique name
Nov 12, 2019
4541035
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 12, 2019
ac490f7
Cache unique id against multiple calls
Nov 12, 2019
053249a
Delay writing analysis into cache until done.
Nov 12, 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
0c13e00
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 13, 2019
e8c7a9d
Baseline updates
Nov 13, 2019
883fd73
Baselines
Nov 13, 2019
2ea1631
Add option to write analysis immediately to disk for tests
Nov 13, 2019
471d1f7
Workaround for named tuples naming
Nov 13, 2019
8e766a2
Comment
Nov 13, 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
63ed836
Merge builtins fix
Nov 16, 2019
0de428d
Merge fix
Nov 16, 2019
0aab4f5
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 16, 2019
cc909be
Merge master
Nov 16, 2019
b953ce7
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 18, 2019
3229082
Merge branch 'master' of https://github.com/microsoft/python-language…
Nov 19, 2019
b73961b
Basic stub-only mode
Nov 20, 2019
a199edd
Add option
Nov 20, 2019
9ca0422
Fix test code
Nov 22, 2019
1659d28
Limit analysis to docs and locations
Dec 2, 2019
9fcf441
Remove debug code
Dec 2, 2019
6277959
Test fix
Dec 2, 2019
c771595
Undo accidental checkin
Dec 2, 2019
f93aa44
Add handling of exceptions to indexer
Dec 2, 2019
3edce72
Update baseline
Dec 2, 2019
e397e2a
Improve synchronization of analysis sessions
Dec 3, 2019
0564a28
Tweak locks
Dec 3, 2019
cd42f79
Reduce lock
Dec 3, 2019
6aee99e
Track next session
Dec 3, 2019
cfd339a
Better next session tracking
Dec 3, 2019
a01d309
Adjust timeout for slower machines
Dec 3, 2019
fd9445d
Timeout on slower machines
Dec 3, 2019
3da1cac
Merge branch 'newdb' of https://github.com/MikhailArkhipov/python-lan…
Dec 3, 2019
298e5cd
Unify type member collection lock
Dec 3, 2019
ad53c29
Extend lock in invalidate
Dec 3, 2019
234733e
Revert "Extend lock in invalidate"
Dec 4, 2019
e22f03f
Account for modules still in parsing
Dec 4, 2019
25fb86a
Unify type member collection lock
Dec 3, 2019
2b11782
Correct AST used in stub loop analysis
Dec 5, 2019
caf77c9
Unify type member collection lock
Dec 3, 2019
10a577e
Spelling
Dec 5, 2019
4dbc1b1
Null check
Dec 5, 2019
026b40a
Comment out services dispose for test stability since when test compl…
Dec 5, 2019
e63a4ac
Remove another dispose
Dec 5, 2019
cd68be8
Merge branch 'newdb' of https://github.com/MikhailArkhipov/python-lan…
Dec 6, 2019
337ff52
Old code in comments
Dec 6, 2019
e16d0b5
Merge branch 'newdb' into stubs
Dec 6, 2019
20ac8ba
Merge branch 'master' of https://github.com/MikhailArkhipov/python-la…
Dec 9, 2019
75cdf98
Merge master
Dec 16, 2019
2c7e729
Merge issues
Dec 16, 2019
18b619e
Uncomment
Dec 16, 2019
1c59d01
Fix test analysis options
Dec 16, 2019
bf030c9
Undo too aggressive optimization
Dec 16, 2019
e7a2bd5
Test fix
Dec 17, 2019
6367764
Merge branch 'master' of https://github.com/microsoft/python-language…
Dec 18, 2019
cbac83f
Fix tests
Dec 19, 2019
85c5b0c
Test update
Jan 2, 2020
dc233dd
Merge branch 'stubs' of https://github.com/MikhailArkhipov/python-lan…
Jan 2, 2020
b166a31
Merge branch 'master' of https://github.com/microsoft/python-language…
May 4, 2020
e68117f
Fix merge
May 5, 2020
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
19 changes: 18 additions & 1 deletion src/Analysis/Ast/Impl/Analyzer/Evaluation/ExpressionEval.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ internal sealed partial class ExpressionEval : IExpressionEvaluator {
private readonly Stack<Scope> _openScopes = new Stack<Scope>();
private readonly object _lock = new object();
private readonly List<DiagnosticsEntry> _diagnostics = new List<DiagnosticsEntry>();
private readonly AnalysisOptions _analysisOptions;

public ExpressionEval(IServiceContainer services, IPythonModule module, PythonAst ast) {
Services = services ?? throw new ArgumentNullException(nameof(services));
Expand All @@ -46,6 +47,18 @@ public ExpressionEval(IServiceContainer services, IPythonModule module, PythonAs
CurrentScope = GlobalScope;
DefaultLocation = new Location(module);
//Log = services.GetService<ILogger>();

var optionsOptovider = services.GetService<IAnalysisOptionsProvider>();
if (optionsOptovider != null) {
_analysisOptions = optionsOptovider.Options;
} else {
_analysisOptions = new AnalysisOptions {
AnalysisCachingLevel = AnalysisCachingLevel.None,
StubOnlyAnalysis = true,
KeepLibraryAst = false,
LintingEnabled = true
};
}
}

public GlobalScope GlobalScope { get; }
Expand All @@ -56,7 +69,11 @@ public ExpressionEval(IServiceContainer services, IPythonModule module, PythonAs
public IPythonType UnknownType => Interpreter.UnknownType;
public Location DefaultLocation { get; }
public IPythonModule BuiltinsModule => Interpreter.ModuleResolution.BuiltinsModule;


public bool StubOnlyAnalysis
=> _analysisOptions.StubOnlyAnalysis
&& Module.Stub != null && Module.ModuleType != ModuleType.User && Module.Stub.IsTypeshed;

public LocationInfo GetLocationInfo(Node node) => node?.GetLocation(this) ?? LocationInfo.Empty;

public Location GetLocationOfName(Node node) {
Expand Down
5 changes: 1 addition & 4 deletions src/Analysis/Ast/Impl/Analyzer/ModuleWalker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,7 @@ private void HandleAugmentedAllAssign(AugmentedAssignStatement node) {
}

var rightVar = Eval.GetValueFromExpression(node.Right);
var right = rightVar as IPythonCollection;

if (right == null) {
if (!(rightVar is IPythonCollection right)) {
_allIsUsable = false;
return;
}
Expand Down Expand Up @@ -202,7 +200,6 @@ public void Complete() {
_cancellationToken.ThrowIfCancellationRequested();

SymbolTable.EvaluateAll();
SymbolTable.ReplacedByStubs.Clear();
new StubMerger(Eval).MergeStub(_stubAnalysis, _cancellationToken);

if (_allIsUsable && _allReferencesCount >= 1 && GlobalScope.Variables.TryGetVariable(AllVariableName, out var variable)
Expand Down
59 changes: 32 additions & 27 deletions src/Analysis/Ast/Impl/Analyzer/Symbols/ClassEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,36 +72,41 @@ private void ProcessClassBody() {
SymbolTable.Evaluate(b.ClassDefinition);
}

// Process imports
foreach (var s in GetStatements<FromImportStatement>(_classDef)) {
ImportHandler.HandleFromImport(s);
}
foreach (var s in GetStatements<ImportStatement>(_classDef)) {
ImportHandler.HandleImport(s);
}
UpdateClassMembers();
if (!Eval.StubOnlyAnalysis) {
// Process imports
foreach (var s in GetStatements<FromImportStatement>(_classDef)) {
ImportHandler.HandleFromImport(s);
}

// Process assignments so we get class variables declared.
// Note that annotated definitions and assignments can be intermixed
// and must be processed in order. Consider
// class A:
// x: int
// x = 1
foreach (var s in GetStatements<Statement>(_classDef)) {
switch (s) {
case AssignmentStatement assignment:
AssignmentHandler.HandleAssignment(assignment, LookupOptions.All);
break;
case ExpressionStatement e:
AssignmentHandler.HandleAnnotatedExpression(e.Expression as ExpressionWithAnnotation, null, LookupOptions.All);
break;
foreach (var s in GetStatements<ImportStatement>(_classDef)) {
ImportHandler.HandleImport(s);
}
}
UpdateClassMembers();

// Ensure constructors are processed so class members are initialized.
EvaluateConstructors(_classDef);
UpdateClassMembers();
UpdateClassMembers();

// Process assignments so we get class variables declared.
// Note that annotated definitions and assignments can be intermixed
// and must be processed in order. Consider
// class A:
// x: int
// x = 1
foreach (var s in GetStatements<Statement>(_classDef)) {
switch (s) {
case AssignmentStatement assignment:
AssignmentHandler.HandleAssignment(assignment, LookupOptions.All);
break;
case ExpressionStatement e:
AssignmentHandler.HandleAnnotatedExpression(e.Expression as ExpressionWithAnnotation, null, LookupOptions.All);
break;
}
}

UpdateClassMembers();

// Ensure constructors are processed so class members are initialized.
EvaluateConstructors(_classDef);
UpdateClassMembers();
}

// Process remaining methods.
SymbolTable.EvaluateScope(_classDef);
Expand Down
8 changes: 5 additions & 3 deletions src/Analysis/Ast/Impl/Analyzer/Symbols/FunctionEvaluator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,11 @@ public FunctionEvaluator(ExpressionEval eval, PythonFunctionOverload overload)
private FunctionDefinition FunctionDefinition { get; }

public override void Evaluate() {
var stub = SymbolTable.ReplacedByStubs.Contains(Target)
|| _function.DeclaringModule.ModuleType == ModuleType.Stub
|| Module.ModuleType == ModuleType.Specialized;
if(Eval.StubOnlyAnalysis) {
return;
}

var stub = _function.DeclaringModule.ModuleType == ModuleType.Stub;

using (Eval.OpenScope(_function.DeclaringModule, FunctionDefinition, out _)) {
var returnType = TryDetermineReturnValue();
Expand Down
2 changes: 0 additions & 2 deletions src/Analysis/Ast/Impl/Analyzer/Symbols/ModuleSymbolTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ internal sealed class ModuleSymbolTable {
private readonly Dictionary<ScopeStatement, MemberEvaluator> _evaluators = new Dictionary<ScopeStatement, MemberEvaluator>();
private readonly HashSet<ScopeStatement> _processed = new HashSet<ScopeStatement>();

public HashSet<Node> ReplacedByStubs { get; } = new HashSet<Node>();

public IEnumerable<KeyValuePair<ScopeStatement, MemberEvaluator>> Evaluators => _evaluators.ToArray();
public void Add(MemberEvaluator e) => _evaluators[e.Target] = e;
public bool Contains(ScopeStatement node) => _evaluators.ContainsKey(node) || _processed.Contains(node);
Expand Down
35 changes: 5 additions & 30 deletions src/Analysis/Ast/Impl/Analyzer/Symbols/SymbolCollector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Python.Analysis.Analyzer.Evaluation;
using Microsoft.Python.Analysis.Types;
Expand Down Expand Up @@ -70,8 +69,7 @@ public override bool Walk(ClassDefinition cd) {
}

public override void PostWalk(ClassDefinition cd) {
if (!string.IsNullOrEmpty(cd.NameExpression?.Name) &&
_typeMap.ContainsKey(cd)) {
if (!string.IsNullOrEmpty(cd.NameExpression?.Name) && _typeMap.ContainsKey(cd)) {
_scopes.Pop().Dispose();
}
base.PostWalk(cd);
Expand Down Expand Up @@ -136,43 +134,20 @@ private void AddFunction(FunctionDefinition fd, PythonType declaringType) {
}

private void AddOverload(FunctionDefinition fd, IPythonClassMember function, Action<PythonFunctionOverload> addOverload) {
// Check if function exists in stubs. If so, take overload from stub
// and the documentation from this actual module.
if (!_table.ReplacedByStubs.Contains(fd)) {
var stubOverload = GetOverloadFromStub(fd);
if (stubOverload != null) {
var documentation = fd.GetDocumentation();
if (!string.IsNullOrEmpty(documentation)) {
stubOverload.SetDocumentation(documentation);
}
addOverload(stubOverload);
_table.ReplacedByStubs.Add(fd);
return;
}
}

if (!_table.Contains(fd)) {
// Do not evaluate parameter types just yet. During light-weight top-level information
// collection types cannot be determined as imports haven't been processed.
var overload = new PythonFunctionOverload(function, fd, _eval.GetLocationOfName(fd), fd.ReturnAnnotation?.ToCodeString(_eval.Ast));
addOverload(overload);
_table.Add(new FunctionEvaluator(_eval, overload));
}
}

private PythonFunctionOverload GetOverloadFromStub(FunctionDefinition node) {
var t = GetMemberFromStub(node.Name).GetPythonType();
if (t is IPythonFunctionType f) {
return f.Overloads
.OfType<PythonFunctionOverload>()
.FirstOrDefault(o => o.Parameters.Count == node.Parameters.Count(p => !p.IsPositionalOnlyMarker));
if (!_eval.StubOnlyAnalysis) {
_table.Add(new FunctionEvaluator(_eval, overload));
}
}
return null;
}

private bool TryAddProperty(FunctionDefinition node, PythonType declaringType) {
// We can't add a property to an unknown type. Fallback to a regular function for now.
// TOOD: Decouple declaring types from the property.
// TODO: Decouple declaring types from the property.
if (declaringType.IsUnknown()) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,5 @@ internal interface IModuleDatabaseService: IModuleDatabaseCache {
/// </param>
/// <param name="cancellationToken">Cancellation token</param>
Task StoreModuleAnalysisAsync(IDocumentAnalysis analysis, bool immediate = false, CancellationToken cancellationToken = default);

/// <summary>
/// Determines if module analysis exists in the storage.
/// </summary>
bool ModuleExistsInStorage(string name, string filePath, ModuleType moduleType);
}

internal static class ModuleDatabaseExtensions {
public static bool ModuleExistsInStorage(this IModuleDatabaseService dbs, IPythonModule module)
=> dbs.ModuleExistsInStorage(module.Name, module.FilePath, module.ModuleType);
}
}
7 changes: 7 additions & 0 deletions src/Analysis/Ast/Impl/Definitions/AnalysisOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,12 @@ public class AnalysisOptions {
/// Defines level of caching analysis engine will maintain.
/// </summary>
public AnalysisCachingLevel AnalysisCachingLevel { get; set; }

/// <summary>
/// Tells if source module should be analyzed or, if stub is present,
/// the stub becomes primary source of information on types and source
/// modules would be used only as documentation provider.
/// </summary>
public bool StubOnlyAnalysis { get; set; }
}
}
8 changes: 8 additions & 0 deletions src/Analysis/Ast/Test/AnalysisTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ protected async Task<IServiceManager> CreateServicesAsync(string root, Interpret
sm.AddService(ds);
}

var ap = Substitute.For<IAnalysisOptionsProvider>();
ap.Options.Returns(x => new AnalysisOptions {
AnalysisCachingLevel = AnalysisCachingLevel.None,
StubOnlyAnalysis = false,
LintingEnabled = true
});
sm.AddService(ap);

TestLogger.Log(TraceEventType.Information, "Create PythonAnalyzer");

CacheService.Register(sm, stubCacheFolderPath, pathCheck: false);
Expand Down
1 change: 0 additions & 1 deletion src/Analysis/Ast/Test/BasicTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
using Microsoft.Python.Analysis.Tests.FluentAssertions;
using Microsoft.Python.Analysis.Types;
using Microsoft.Python.Analysis.Values;
using Microsoft.Python.Parsing.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;

Expand Down
26 changes: 1 addition & 25 deletions src/Caching/Impl/ModuleDatabase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ private readonly ConcurrentDictionary<AnalysisModuleKey, bool> _searchResults
private readonly IFileSystem _fs;
private readonly AnalysisCachingLevel _defaultCachingLevel;
private readonly CacheWriter _cacheWriter;
private AnalysisCachingLevel? _cachingLevel;

public ModuleDatabase(IServiceManager sm, string cacheFolder = null) {
_services = sm;
Expand Down Expand Up @@ -76,27 +75,6 @@ public IPythonModule RestoreModule(string moduleName, string modulePath, ModuleT
? RestoreModule(model) : null;
}

/// <summary>
/// Determines if module analysis exists in the storage.
/// </summary>
public bool ModuleExistsInStorage(string name, string filePath, ModuleType moduleType) {
if (GetCachingLevel() == AnalysisCachingLevel.None) {
return false;
}

var key = new AnalysisModuleKey(name, filePath);
if (_searchResults.TryGetValue(key, out var result)) {
return result;
}

WithRetries.Execute(() => {
var dbPath = FindDatabaseFile(name, filePath, moduleType);
_searchResults[key] = result = !string.IsNullOrEmpty(dbPath);
return result;
}, "Unable to find database file for {name}.", _log);
return false;
}

public async Task StoreModuleAnalysisAsync(IDocumentAnalysis analysis, bool immediate = false, CancellationToken cancellationToken = default) {
var cachingLevel = GetCachingLevel();
if (cachingLevel == AnalysisCachingLevel.None) {
Expand Down Expand Up @@ -192,9 +170,7 @@ private bool TryGetModuleModel(string moduleName, string dbPath, out ModuleModel
}

private AnalysisCachingLevel GetCachingLevel()
=> _cachingLevel
?? (_cachingLevel = _services.GetService<IAnalysisOptionsProvider>()?.Options.AnalysisCachingLevel)
?? _defaultCachingLevel;
=> _services.GetService<IAnalysisOptionsProvider>()?.Options.AnalysisCachingLevel ?? _defaultCachingLevel;

public void Dispose() => _cacheWriter.Dispose();
}
Expand Down
1 change: 0 additions & 1 deletion src/Caching/Test/AnalysisCachingTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
using Microsoft.Python.Analysis.Analyzer;
using Microsoft.Python.Analysis.Caching.Models;
using Microsoft.Python.Analysis.Caching.Tests.FluentAssertions;
using Microsoft.Python.Analysis.Dependencies;
using Microsoft.Python.Analysis.Tests;
using Microsoft.Python.Analysis.Types;
using Newtonsoft.Json;
Expand Down
18 changes: 17 additions & 1 deletion src/Caching/Test/RestoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
using Microsoft.Python.Analysis.Documents;
using Microsoft.Python.Analysis.Types;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using TestUtilities;

namespace Microsoft.Python.Analysis.Caching.Tests {
Expand Down Expand Up @@ -57,6 +58,8 @@ def func2() -> C2: ...

var dbs = new ModuleDatabase(Services, Path.GetDirectoryName(TestData.GetDefaultModulePath()));
Services.AddService(dbs);

EnableCaching();
await dbs.StoreModuleAnalysisAsync(analysis2, immediate: true, CancellationToken.None);

await Services.GetService<IPythonAnalyzer>().ResetAnalyzer();
Expand Down Expand Up @@ -101,15 +104,28 @@ private async Task CreateDatabaseAsync(IPythonInterpreter interpreter) {
var dbs = new ModuleDatabase(Services, Path.GetDirectoryName(TestData.GetDefaultModulePath()));
Services.AddService(dbs);

EnableCaching();

var importedModules = interpreter.ModuleResolution.GetImportedModules();
foreach (var m in importedModules.Where(m => m.Analysis is LibraryAnalysis)) {
await dbs.StoreModuleAnalysisAsync(m.Analysis, immediate: true);
}

importedModules = interpreter.TypeshedResolution.GetImportedModules();
foreach (var m in importedModules.Where(m => m.Analysis is LibraryAnalysis)) {
await dbs.StoreModuleAnalysisAsync(m.Analysis, immediate: true);
}
}

private void EnableCaching() {
var a = Services.GetService<IAnalysisOptionsProvider>();
Services.RemoveService(a);
var aop = Substitute.For<IAnalysisOptionsProvider>();
aop.Options.Returns(x => new AnalysisOptions {
AnalysisCachingLevel = AnalysisCachingLevel.Library,
StubOnlyAnalysis = a.Options.StubOnlyAnalysis
});
Services.AddService(aop);
}
}
}
1 change: 1 addition & 0 deletions src/LanguageServer/Impl/LanguageServer.Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ private void HandleDiagnosticsChanges(JToken pythonSection, LanguageServerSettin
var optionsProvider = _services.GetService<IAnalysisOptionsProvider>();
optionsProvider.Options.KeepLibraryAst = GetSetting(memory, "keepLibraryAst", false);
optionsProvider.Options.AnalysisCachingLevel = GetAnalysisCachingLevel(analysis);
optionsProvider.Options.StubOnlyAnalysis = GetSetting(analysis, "stubsOnly", true);

_logger?.Log(TraceEventType.Information, Resources.AnalysisCacheLevel.FormatInvariant(optionsProvider.Options.AnalysisCachingLevel));
}
Expand Down
Loading