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

Commit 368d016

Browse files
committed
more simple clean ups
named arguments, removing unncessary stuff.
1 parent 3d2fc3d commit 368d016

File tree

8 files changed

+48
-30
lines changed

8 files changed

+48
-30
lines changed

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ public sealed class InterpreterConfiguration : IEquatable<InterpreterConfigurati
2222
/// Constructs a new interpreter configuration based on the provided values.
2323
/// </summary>
2424
public InterpreterConfiguration(string interpreterPath = null, Version version = null) :
25-
this(interpreterPath, string.Empty, null, null, default, version) { }
25+
this(interpreterPath, pathVar: string.Empty, libPath: null, sitePackagesPath: null, architecture: default, version: version) { }
2626

2727
// Tests only
2828
internal InterpreterConfiguration(
@@ -31,8 +31,7 @@ internal InterpreterConfiguration(
3131
string libPath = null,
3232
string sitePackagesPath = null,
3333
InterpreterArchitecture architecture = default,
34-
Version version = null
35-
) {
34+
Version version = null) {
3635
InterpreterPath = interpreterPath;
3736
PathEnvironmentVariable = pathVar;
3837
Architecture = architecture ?? InterpreterArchitecture.Unknown;

src/Core/Impl/Collections/ImmutableArray.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ public ImmutableArray<T> Add(T item) {
9191
var newItems = _items;
9292
var newRef = _ref;
9393

94+
// _ref indicates whether the array "_items" can be re-used when creating new ImmutableArray.
95+
// this is an optimization to reduce array allocation while new elements are kept added at the end of the list
96+
// this is an alternative design compared to Builder model
97+
// (https://docs.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutablearray-1.builder)
9498
if (Interlocked.CompareExchange(ref newRef.Count, newCount, _count) != _count || newCount > _items.Length) {
9599
var capacity = GetCapacity(newCount);
96100
newItems = new T[capacity];

src/Core/Impl/Extensions/TaskExtensions.cs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,16 @@ private static void DoNotWaitSynchronizationContextContinuation(Task task, objec
105105
/// </summary>
106106
public static T WaitAndUnwrapExceptions<T>(this Task<T> task) => task.GetAwaiter().GetResult();
107107

108+
/// <summary>
109+
/// Attach new <see cref="CancellationToken" /> to the given task.
110+
///
111+
/// this allows caller to have its own cancellation without aborting underlying work.
112+
///
113+
/// if <paramref name="task"/> uses different cancellation token than one given <paramref name="cancellationToken"/>
114+
/// it will throw <see cref="AggregateException" /> instead of <see cref="OperationCanceledException" /> and
115+
/// Task will be set to faulted rather than cancelled.
116+
/// </summary>
108117
public static Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken)
109-
=> task.ContinueWith(t => t.GetAwaiter().GetResult(), cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default);
118+
=> task.ContinueWith(t => t.WaitAndUnwrapExceptions(), cancellationToken, TaskContinuationOptions.None, TaskScheduler.Default);
110119
}
111120
}

src/Core/Impl/Services/IdleTimeService.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,15 @@
1919

2020
namespace Microsoft.Python.Core.Services {
2121
public sealed class IdleTimeService : IIdleTimeService, IIdleTimeTracker, IDisposable {
22+
private static readonly TimeSpan s_initialDelay = TimeSpan.FromMilliseconds(50);
23+
private static readonly TimeSpan s_interval = TimeSpan.FromMilliseconds(50);
24+
private static readonly TimeSpan s_idleInterval = TimeSpan.FromMilliseconds(100);
25+
2226
private Timer _timer;
2327
private DateTime _lastActivityTime;
2428

2529
public IdleTimeService() {
26-
_timer = new Timer(OnTimer, this, 50, 50);
30+
_timer = new Timer(OnTimer, state: this, s_initialDelay, s_interval);
2731
NotifyUserActivity();
2832
}
2933

@@ -32,11 +36,12 @@ public IdleTimeService() {
3236
public void Dispose() {
3337
_timer?.Dispose();
3438
_timer = null;
39+
3540
Closing?.Invoke(this, EventArgs.Empty);
3641
}
3742

3843
private void OnTimer(object state) {
39-
if ((DateTime.Now - _lastActivityTime).TotalMilliseconds >= 100 && _timer != null) {
44+
if (_timer != null && (DateTime.Now - _lastActivityTime) >= s_idleInterval) {
4045
Idle?.Invoke(this, EventArgs.Empty);
4146
}
4247
}

src/Core/Impl/Text/SourceLocation.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public SourceLocation(int index, int line, int column) {
4949
/// <param name="column">The column in the source stream the location represents (1-based).</param>
5050
[DebuggerStepThrough]
5151
public SourceLocation(int line, int column) {
52-
ValidateLocation(0, line, column);
52+
ValidateLocation(index: 0, line, column);
5353

5454
_index = -1;
5555
Line = line;

src/Core/Impl/Threading/SingleThreadSynchronizationContext.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
namespace Microsoft.Python.Core.Threading {
2222
public class SingleThreadSynchronizationContext : SynchronizationContext, IDisposable {
23-
private readonly ConcurrentQueue<Tuple<SendOrPostCallback, object>> _queue = new ConcurrentQueue<Tuple<SendOrPostCallback, object>>();
23+
private readonly ConcurrentQueue<(SendOrPostCallback callback, object state)> _queue = new ConcurrentQueue<(SendOrPostCallback, object)>();
2424
private readonly ManualResetEventSlim _workAvailable = new ManualResetEventSlim(false);
2525
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
2626

@@ -29,7 +29,7 @@ public SingleThreadSynchronizationContext() {
2929
}
3030

3131
public override void Post(SendOrPostCallback d, object state) {
32-
_queue.Enqueue(new Tuple<SendOrPostCallback, object>(d, state));
32+
_queue.Enqueue((d, state));
3333
_workAvailable.Set();
3434
}
3535

@@ -41,9 +41,10 @@ private void QueueWorker() {
4141
if (_cts.IsCancellationRequested) {
4242
break;
4343
}
44-
while (_queue.TryDequeue(out var t)) {
45-
t.Item1(t.Item2);
44+
while (_queue.TryDequeue(out var entry)) {
45+
entry.callback(entry.state);
4646
}
47+
4748
_workAvailable.Reset();
4849
}
4950
}

src/LanguageServer/Impl/LanguageServer.Configuration.cs

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -51,19 +51,19 @@ public async Task DidChangeConfiguration(JToken token, CancellationToken cancell
5151
}
5252

5353
var autoComplete = pythonSection["autoComplete"];
54-
settings.completion.showAdvancedMembers = GetSetting(autoComplete, "showAdvancedMembers", true);
55-
settings.completion.addBrackets = GetSetting(autoComplete, "addBrackets", false);
54+
settings.completion.showAdvancedMembers = GetSetting(autoComplete, "showAdvancedMembers", defaultValue: true);
55+
settings.completion.addBrackets = GetSetting(autoComplete, "addBrackets", defaultValue: false);
5656

5757
var analysis = pythonSection["analysis"];
58-
settings.symbolsHierarchyDepthLimit = GetSetting(analysis, "symbolsHierarchyDepthLimit", 10);
59-
settings.symbolsHierarchyMaxSymbols = GetSetting(analysis, "symbolsHierarchyMaxSymbols", 1000);
58+
settings.symbolsHierarchyDepthLimit = GetSetting(analysis, "symbolsHierarchyDepthLimit", defaultValue: 10);
59+
settings.symbolsHierarchyMaxSymbols = GetSetting(analysis, "symbolsHierarchyMaxSymbols", defaultValue: 1000);
6060

6161
_logger.LogLevel = GetLogLevel(analysis).ToTraceEventType();
6262

6363
var userConfiguredPaths = GetUserConfiguredPaths(pythonSection);
6464

6565
HandleUserConfiguredPathsChanges(userConfiguredPaths);
66-
HandlePathWatchChanges(GetSetting(analysis, "watchSearchPaths", true));
66+
HandlePathWatchChanges(GetSetting(analysis, "watchSearchPaths", defaultValue: true));
6767
HandleDiagnosticsChanges(pythonSection, settings);
6868

6969
_server.DidChangeConfiguration(new DidChangeConfigurationParams { settings = settings }, cancellationToken);
@@ -73,23 +73,23 @@ public async Task DidChangeConfiguration(JToken token, CancellationToken cancell
7373
private void HandleDiagnosticsChanges(JToken pythonSection, LanguageServerSettings settings) {
7474
var analysis = pythonSection["analysis"];
7575

76-
settings.diagnosticPublishDelay = GetSetting(analysis, "diagnosticPublishDelay", 1000);
76+
settings.diagnosticPublishDelay = GetSetting(analysis, "diagnosticPublishDelay", defaultValue: 1000);
7777
var ds = _services.GetService<IDiagnosticsService>();
7878
ds.PublishingDelay = settings.diagnosticPublishDelay;
7979

8080
ds.DiagnosticsSeverityMap = new DiagnosticsSeverityMap(
81-
GetSetting(analysis, "errors", Array.Empty<string>()),
82-
GetSetting(analysis, "warnings", Array.Empty<string>()),
83-
GetSetting(analysis, "information", Array.Empty<string>()),
84-
GetSetting(analysis, "disabled", Array.Empty<string>()));
81+
GetSetting(analysis, "errors", defaultValue: Array.Empty<string>()),
82+
GetSetting(analysis, "warnings", defaultValue: Array.Empty<string>()),
83+
GetSetting(analysis, "information", defaultValue: Array.Empty<string>()),
84+
GetSetting(analysis, "disabled", defaultValue: Array.Empty<string>()));
8585

8686
var linting = pythonSection["linting"];
87-
HandleLintingOnOff(_services, GetSetting(linting, "enabled", true));
87+
HandleLintingOnOff(_services, GetSetting(linting, "enabled", defaultValue: true));
8888

8989
var memory = analysis["memory"];
9090
var optionsProvider = _services.GetService<IAnalysisOptionsProvider>();
91-
optionsProvider.Options.KeepLibraryLocalVariables = GetSetting(memory, "keepLibraryLocalVariables", false);
92-
optionsProvider.Options.KeepLibraryAst = GetSetting(memory, "keepLibraryAst", false);
91+
optionsProvider.Options.KeepLibraryLocalVariables = GetSetting(memory, "keepLibraryLocalVariables", defaultValue: false);
92+
optionsProvider.Options.KeepLibraryAst = GetSetting(memory, "keepLibraryAst", defaultValue: false);
9393
optionsProvider.Options.AnalysisCachingLevel = GetAnalysisCachingLevel(analysis);
9494

9595
_logger?.Log(TraceEventType.Information, Resources.AnalysisCacheLevel.FormatInvariant(optionsProvider.Options.AnalysisCachingLevel));
@@ -135,10 +135,10 @@ private ImmutableArray<string> GetUserConfiguredPaths(JToken pythonSection) {
135135
// The values of these may not be null even if the value is "unset", depending on
136136
// what the client uses as a default. Use null as a default anyway until the
137137
// extension uses a null default (and/or extraPaths is dropped entirely).
138-
var autoCompleteExtraPaths = GetSetting<IReadOnlyList<string>>(autoComplete, "extraPaths", null);
139-
var analysisSearchPaths = GetSetting<IReadOnlyList<string>>(analysis, "searchPaths", null);
140-
var analysisUsePYTHONPATH = GetSetting(analysis, "usePYTHONPATH", true);
141-
var analayisAutoSearchPaths = GetSetting(analysis, "autoSearchPaths", true);
138+
var autoCompleteExtraPaths = GetSetting<IReadOnlyList<string>>(autoComplete, "extraPaths", defaultValue: null);
139+
var analysisSearchPaths = GetSetting<IReadOnlyList<string>>(analysis, "searchPaths", defaultValue: null);
140+
var analysisUsePYTHONPATH = GetSetting(analysis, "usePYTHONPATH", defaultValue: true);
141+
var analayisAutoSearchPaths = GetSetting(analysis, "autoSearchPaths", defaultValue: true);
142142

143143
if (analysisSearchPaths != null) {
144144
set = true;
@@ -181,7 +181,7 @@ private ImmutableArray<string> GetUserConfiguredPaths(JToken pythonSection) {
181181
}
182182

183183
private AnalysisCachingLevel GetAnalysisCachingLevel(JToken analysisKey) {
184-
var s = GetSetting(analysisKey, "cachingLevel", "None");
184+
var s = GetSetting(analysisKey, "cachingLevel", defaultValue: "None");
185185
if (s.EqualsIgnoreCase("System")) {
186186
return AnalysisCachingLevel.System;
187187
}

src/LanguageServer/Impl/PathsWatcher.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ private void OnChanged(object sender, FileSystemEventArgs e) {
9090
// if there is massive change to the file structure.
9191
lock (_lock) {
9292
_changedSinceLastTick = true;
93-
_throttleTimer = _throttleTimer ?? new Timer(TimerProc, null, 500, 500);
93+
_throttleTimer = _throttleTimer ?? new Timer(TimerProc, state: null, dueTime: 500, period: 500);
9494
}
9595
}
9696

0 commit comments

Comments
 (0)