From b94045e46c74f2db019145bbe92b30748ebf8480 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 3 Sep 2018 09:47:26 +1000 Subject: [PATCH 1/9] Remove excess LINQ usage in LanguageService.cs --- .../Language/LanguageService.cs | 121 ++++++++++-------- 1 file changed, 66 insertions(+), 55 deletions(-) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index ff07acddd..0b0bfff79 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -154,19 +154,21 @@ public CompletionDetails GetCompletionDetailsInFile( ScriptFile file, string entryName) { - // Makes sure the most recent completions request was the same line and column as this request - if (file.Id.Equals(mostRecentRequestFile)) + if (!file.Id.Equals(this.mostRecentRequestFile)) { - CompletionDetails completionResult = - mostRecentCompletions.Completions.FirstOrDefault( - result => result.CompletionText.Equals(entryName)); - - return completionResult; + return null; } - else + + foreach (CompletionDetails completion in this.mostRecentCompletions.Completions) { - return null; + if (completion.CompletionText.Equals(entryName)) + { + return completion; + } } + + // If we found no completions, return null + return null; } /// @@ -245,20 +247,18 @@ public async Task FindSymbolDetailsAtLocation( lineNumber, columnNumber); - if (symbolReference != null) - { - symbolReference.FilePath = scriptFile.FilePath; - symbolDetails = - await SymbolDetails.Create( - symbolReference, - this.powerShellContext); - } - else + if (symbolReference == null) { // TODO #21: Return Result return null; } + symbolReference.FilePath = scriptFile.FilePath; + symbolDetails = + await SymbolDetails.Create( + symbolReference, + this.powerShellContext); + return symbolDetails; } @@ -270,17 +270,21 @@ await SymbolDetails.Create( public FindOccurrencesResult FindSymbolsInFile(ScriptFile scriptFile) { Validate.IsNotNull("scriptFile", scriptFile); + + var foundOccurrences = new List(); + foreach (IDocumentSymbolProvider symbolProvider in documentSymbolProviders) + { + foreach (SymbolReference reference in symbolProvider.ProvideDocumentSymbols(scriptFile)) + { + reference.SourceLine = scriptFile.GetLine(reference.ScriptRegion.StartLineNumber); + reference.FilePath = scriptFile.FilePath; + foundOccurrences.Add(reference); + } + } + return new FindOccurrencesResult { - FoundOccurrences = documentSymbolProviders - .SelectMany(p => p.ProvideDocumentSymbols(scriptFile)) - .Select(reference => - { - reference.SourceLine = - scriptFile.GetLine(reference.ScriptRegion.StartLineNumber); - reference.FilePath = scriptFile.FilePath; - return reference; - }) + FoundOccurrences = foundOccurrences }; } @@ -346,30 +350,29 @@ public async Task FindReferencesOfSymbol( foreach (object fileName in fileMap.Keys) { var file = (ScriptFile)fileMap[fileName]; - IEnumerable symbolReferencesinFile = - AstOperations - .FindReferencesOfSymbol( - file.ScriptAst, - foundSymbol, - CmdletToAliasDictionary, - AliasToCmdletDictionary) - .Select(reference => - { - try - { - reference.SourceLine = file.GetLine(reference.ScriptRegion.StartLineNumber); - } - catch (ArgumentOutOfRangeException e) - { - reference.SourceLine = string.Empty; - this.logger.WriteException("Found reference is out of range in script file", e); - } - - reference.FilePath = file.FilePath; - return reference; - }); - - symbolReferences.AddRange(symbolReferencesinFile); + + IEnumerable references = AstOperations.FindReferencesOfSymbol( + file.ScriptAst, + foundSymbol, + CmdletToAliasDictionary, + AliasToCmdletDictionary); + + foreach (SymbolReference reference in references) + { + try + { + reference.SourceLine = file.GetLine(reference.ScriptRegion.StartLineNumber); + } + catch (ArgumentOutOfRangeException e) + { + reference.SourceLine = string.Empty; + this.logger.WriteException("Found reference is out of range in script file", e); + } + reference.FilePath = file.FilePath; + symbolReferences.Add(reference); + } + + symbolReferences.AddRange(symbolReferences); } return new FindReferencesResult @@ -768,7 +771,7 @@ private ScriptFile[] GetBuiltinCommandScriptFiles( return scriptFiles.ToArray(); } - return new List().ToArray(); + return new ScriptFile[0]; } private SymbolReference FindDeclarationForBuiltinCommand( @@ -808,13 +811,21 @@ private SymbolReference FindDeclarationForBuiltinCommand( private Ast FindSmallestStatementAst(ScriptFile scriptFile, int lineNumber, int columnNumber) { - var asts = scriptFile.ScriptAst.FindAll(ast => + IEnumerable asts = scriptFile.ScriptAst.FindAll(ast => { return ast is StatementAst && ast.Extent.Contains(lineNumber, columnNumber); }, true); - // Find ast with the smallest extent - return asts.MinElement((astX, astY) => astX.Extent.ExtentWidthComparer(astY.Extent)); + Ast minAst = scriptFile.ScriptAst; + foreach (Ast ast in asts) + { + if (ast.Extent.ExtentWidthComparer(minAst.Extent) == -1) + { + minAst = ast; + } + } + + return minAst; } #endregion From 20c16cf523184e502d84d9afa88cd38ff524fe79 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 3 Sep 2018 10:04:01 +1000 Subject: [PATCH 2/9] [Style] Simplify method bodies --- .../Language/LanguageService.cs | 310 +++++++++--------- 1 file changed, 155 insertions(+), 155 deletions(-) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index 0b0bfff79..413e0f294 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -113,35 +113,36 @@ await AstOperations.GetCompletions( this.logger, new CancellationTokenSource(DefaultWaitTimeoutMilliseconds).Token); - if (commandCompletion != null) + if (commandCompletion == null) { - try - { - CompletionResults completionResults = - CompletionResults.Create( - scriptFile, - commandCompletion); - - // save state of most recent completion - mostRecentCompletions = completionResults; - mostRecentRequestFile = scriptFile.Id; - mostRecentRequestLine = lineNumber; - mostRecentRequestOffest = columnNumber; - - return completionResults; - } - catch (ArgumentException e) - { - // Bad completion results could return an invalid - // replacement range, catch that here - this.logger.Write( - LogLevel.Error, - $"Caught exception while trying to create CompletionResults:\n\n{e.ToString()}"); - } + return new CompletionResults(); } - // If all else fails, return empty results - return new CompletionResults(); + try + { + CompletionResults completionResults = + CompletionResults.Create( + scriptFile, + commandCompletion); + + // save state of most recent completion + mostRecentCompletions = completionResults; + mostRecentRequestFile = scriptFile.Id; + mostRecentRequestLine = lineNumber; + mostRecentRequestOffest = columnNumber; + + return completionResults; + } + catch (ArgumentException e) + { + // Bad completion results could return an invalid + // replacement range, catch that here + this.logger.Write( + LogLevel.Error, + $"Caught exception while trying to create CompletionResults:\n\n{e.ToString()}"); + + return new CompletionResults(); + } } /// @@ -493,26 +494,24 @@ public FindOccurrencesResult FindOccurrencesInFile( lineNumber, columnNumber); - if (foundSymbol != null) - { - // find all references, and indicate that looking for aliases is not needed - IEnumerable symbolOccurrences = - AstOperations - .FindReferencesOfSymbol( - file.ScriptAst, - foundSymbol, - false); - - return - new FindOccurrencesResult - { - FoundOccurrences = symbolOccurrences - }; - } - else + if (foundSymbol == null) { return null; } + + // find all references, and indicate that looking for aliases is not needed + IEnumerable symbolOccurrences = + AstOperations + .FindReferencesOfSymbol( + file.ScriptAst, + foundSymbol, + false); + + return + new FindOccurrencesResult + { + FoundOccurrences = symbolOccurrences + }; } /// @@ -533,44 +532,40 @@ public async Task FindParameterSetsInFile( lineNumber, columnNumber); - if (foundSymbol != null) + if (foundSymbol == null) { - CommandInfo commandInfo = - await CommandHelpers.GetCommandInfo( - foundSymbol.SymbolName, - this.powerShellContext); + return null; + } - if (commandInfo != null) - { - try - { - IEnumerable commandParamSets = commandInfo.ParameterSets; - return new ParameterSetSignatures(commandParamSets, foundSymbol); - } - catch (RuntimeException e) - { - // A RuntimeException will be thrown when an invalid attribute is - // on a parameter binding block and then that command/script has - // its signatures resolved by typing it into a script. - this.logger.WriteException("RuntimeException encountered while accessing command parameter sets", e); + CommandInfo commandInfo = + await CommandHelpers.GetCommandInfo( + foundSymbol.SymbolName, + this.powerShellContext); - return null; - } - catch (InvalidOperationException) - { - // For some commands there are no paramsets (like applications). Until - // the valid command types are better understood, catch this exception - // which gets raised when there are no ParameterSets for the command type. - return null; - } - } - else - { - return null; - } + if (commandInfo == null) + { + return null; } - else + + try + { + IEnumerable commandParamSets = commandInfo.ParameterSets; + return new ParameterSetSignatures(commandParamSets, foundSymbol); + } + catch (RuntimeException e) { + // A RuntimeException will be thrown when an invalid attribute is + // on a parameter binding block and then that command/script has + // its signatures resolved by typing it into a script. + this.logger.WriteException("RuntimeException encountered while accessing command parameter sets", e); + + return null; + } + catch (InvalidOperationException) + { + // For some commands there are no paramsets (like applications). Until + // the valid command types are better understood, catch this exception + // which gets raised when there are no ParameterSets for the command type. return null; } } @@ -649,34 +644,38 @@ public FunctionDefinitionAst GetFunctionDefinitionForHelpComment( }, true); - if (foundAsts != null && foundAsts.Any()) + if (foundAsts == null || !foundAsts.Any()) { - // of all the function definitions found, return the innermost function - // definition that contains `lineNumber` - funcDefnAst = foundAsts.Cast().Aggregate((x, y) => - { - if (x.Extent.StartOffset >= y.Extent.StartOffset && x.Extent.EndOffset <= x.Extent.EndOffset) - { - return x; - } - - return y; - }); + helpLocation = null; + return null; + } - // TODO use tokens to check for non empty character instead of just checking for line offset - if (funcDefnAst.Body.Extent.StartLineNumber == lineNumber - 1) + // of all the function definitions found, return the innermost function + // definition that contains `lineNumber` + funcDefnAst = foundAsts.Cast().Aggregate((x, y) => + { + if (x.Extent.StartOffset >= y.Extent.StartOffset && x.Extent.EndOffset <= x.Extent.EndOffset) { - helpLocation = "begin"; - return funcDefnAst; + return x; } - if (funcDefnAst.Body.Extent.EndLineNumber == lineNumber + 1) - { - helpLocation = "end"; - return funcDefnAst; - } + return y; + }); + + // TODO use tokens to check for non empty character instead of just checking for line offset + if (funcDefnAst.Body.Extent.StartLineNumber == lineNumber - 1) + { + helpLocation = "begin"; + return funcDefnAst; + } + + if (funcDefnAst.Body.Extent.EndLineNumber == lineNumber + 1) + { + helpLocation = "end"; + return funcDefnAst; } + // If we didn't find a function definition, then return null helpLocation = null; return null; } @@ -690,48 +689,50 @@ public FunctionDefinitionAst GetFunctionDefinitionForHelpComment( /// private async Task GetAliases() { - if (!this.areAliasesLoaded) + if (this.areAliasesLoaded) { - try - { - RunspaceHandle runspaceHandle = - await this.powerShellContext.GetRunspaceHandle( - new CancellationTokenSource(DefaultWaitTimeoutMilliseconds).Token); + return; + } + + try + { + RunspaceHandle runspaceHandle = + await this.powerShellContext.GetRunspaceHandle( + new CancellationTokenSource(DefaultWaitTimeoutMilliseconds).Token); - CommandInvocationIntrinsics invokeCommand = runspaceHandle.Runspace.SessionStateProxy.InvokeCommand; - IEnumerable aliases = invokeCommand.GetCommands("*", CommandTypes.Alias, true); + CommandInvocationIntrinsics invokeCommand = runspaceHandle.Runspace.SessionStateProxy.InvokeCommand; + IEnumerable aliases = invokeCommand.GetCommands("*", CommandTypes.Alias, true); - runspaceHandle.Dispose(); + runspaceHandle.Dispose(); - foreach (AliasInfo aliasInfo in aliases) + foreach (AliasInfo aliasInfo in aliases) + { + if (!CmdletToAliasDictionary.ContainsKey(aliasInfo.Definition)) + { + CmdletToAliasDictionary.Add(aliasInfo.Definition, new List() { aliasInfo.Name }); + } + else { - if (!CmdletToAliasDictionary.ContainsKey(aliasInfo.Definition)) - { - CmdletToAliasDictionary.Add(aliasInfo.Definition, new List() { aliasInfo.Name }); - } - else - { - CmdletToAliasDictionary[aliasInfo.Definition].Add(aliasInfo.Name); - } - - AliasToCmdletDictionary.Add(aliasInfo.Name, aliasInfo.Definition); + CmdletToAliasDictionary[aliasInfo.Definition].Add(aliasInfo.Name); } - this.areAliasesLoaded = true; + AliasToCmdletDictionary.Add(aliasInfo.Name, aliasInfo.Definition); } - catch (PSNotSupportedException e) - { - this.logger.Write( - LogLevel.Warning, - $"Caught PSNotSupportedException while attempting to get aliases from remote session:\n\n{e.ToString()}"); - // Prevent the aliases from being fetched again - no point if the remote doesn't support InvokeCommand. - this.areAliasesLoaded = true; - } - catch (TaskCanceledException) - { - // The wait for a RunspaceHandle has timed out, skip aliases for now - } + this.areAliasesLoaded = true; + } + catch (PSNotSupportedException e) + { + this.logger.Write( + LogLevel.Warning, + $"Caught PSNotSupportedException while attempting to get aliases from remote session:\n\n{e.ToString()}"); + + // Prevent the aliases from being fetched again - no point if the remote doesn't support InvokeCommand. + this.areAliasesLoaded = true; + } + catch (TaskCanceledException) + { + // The wait for a RunspaceHandle has timed out, skip aliases for now } } @@ -739,39 +740,38 @@ private ScriptFile[] GetBuiltinCommandScriptFiles( PSModuleInfo moduleInfo, Workspace workspace) { - // if there is module info for this command - if (moduleInfo != null) + if (moduleInfo == null) { - string modPath = moduleInfo.Path; - List scriptFiles = new List(); - ScriptFile newFile; + return new ScriptFile[0]; + } - // find any files where the moduleInfo's path ends with ps1 or psm1 - // and add it to allowed script files - if (modPath.EndsWith(@".ps1") || modPath.EndsWith(@".psm1")) - { - newFile = workspace.GetFile(modPath); - newFile.IsAnalysisEnabled = false; - scriptFiles.Add(newFile); - } - if (moduleInfo.NestedModules.Count > 0) + string modPath = moduleInfo.Path; + List scriptFiles = new List(); + ScriptFile newFile; + + // find any files where the moduleInfo's path ends with ps1 or psm1 + // and add it to allowed script files + if (modPath.EndsWith(@".ps1") || modPath.EndsWith(@".psm1")) + { + newFile = workspace.GetFile(modPath); + newFile.IsAnalysisEnabled = false; + scriptFiles.Add(newFile); + } + if (moduleInfo.NestedModules.Count > 0) + { + foreach (PSModuleInfo nestedInfo in moduleInfo.NestedModules) { - foreach (PSModuleInfo nestedInfo in moduleInfo.NestedModules) + string nestedModPath = nestedInfo.Path; + if (nestedModPath.EndsWith(@".ps1") || nestedModPath.EndsWith(@".psm1")) { - string nestedModPath = nestedInfo.Path; - if (nestedModPath.EndsWith(@".ps1") || nestedModPath.EndsWith(@".psm1")) - { - newFile = workspace.GetFile(nestedModPath); - newFile.IsAnalysisEnabled = false; - scriptFiles.Add(newFile); - } + newFile = workspace.GetFile(nestedModPath); + newFile.IsAnalysisEnabled = false; + scriptFiles.Add(newFile); } } - - return scriptFiles.ToArray(); } - return new ScriptFile[0]; + return scriptFiles.ToArray(); } private SymbolReference FindDeclarationForBuiltinCommand( From 1c8be35ce7ae6847fd482c5c6b8829846cce4b39 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 3 Sep 2018 10:10:40 +1000 Subject: [PATCH 3/9] Replace LINQ aggregate call --- .../Language/LanguageService.cs | 53 ++++++++++--------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index 413e0f294..0135f40d3 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -652,15 +652,20 @@ public FunctionDefinitionAst GetFunctionDefinitionForHelpComment( // of all the function definitions found, return the innermost function // definition that contains `lineNumber` - funcDefnAst = foundAsts.Cast().Aggregate((x, y) => + foreach (FunctionDefinitionAst foundAst in foundAsts.Cast()) { - if (x.Extent.StartOffset >= y.Extent.StartOffset && x.Extent.EndOffset <= x.Extent.EndOffset) + if (funcDefnAst == null) { - return x; + funcDefnAst = foundAst; + continue; } - return y; - }); + if (funcDefnAst.Extent.StartOffset >= foundAst.Extent.StartOffset + && funcDefnAst.Extent.EndOffset <= foundAst.Extent.EndOffset) + { + funcDefnAst = foundAst; + } + } // TODO use tokens to check for non empty character instead of just checking for line offset if (funcDefnAst.Body.Extent.StartLineNumber == lineNumber - 1) @@ -779,30 +784,28 @@ private SymbolReference FindDeclarationForBuiltinCommand( SymbolReference foundSymbol, Workspace workspace) { - SymbolReference foundDefinition = null; - if (commandInfo != null) + if (commandInfo == null) { - int index = 0; - ScriptFile[] nestedModuleFiles; - - nestedModuleFiles = - GetBuiltinCommandScriptFiles( - commandInfo.Module, - workspace); + return null; + } - while (foundDefinition == null && index < nestedModuleFiles.Length) - { - foundDefinition = - AstOperations.FindDefinitionOfSymbol( - nestedModuleFiles[index].ScriptAst, - foundSymbol); + ScriptFile[] nestedModuleFiles = + GetBuiltinCommandScriptFiles( + commandInfo.Module, + workspace); - if (foundDefinition != null) - { - foundDefinition.FilePath = nestedModuleFiles[index].FilePath; - } + SymbolReference foundDefinition = null; + for (int i = 0; i < nestedModuleFiles.Length; i++) + { + foundDefinition = + AstOperations.FindDefinitionOfSymbol( + nestedModuleFiles[i].ScriptAst, + foundSymbol); - index++; + if (foundDefinition != null) + { + foundDefinition.FilePath = nestedModuleFiles[i].FilePath; + break; } } From e9f86d2b7dd61a8930c126858895c4774d272a35 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 3 Sep 2018 10:16:50 +1000 Subject: [PATCH 4/9] [Style] Change LanguageService fields to underscore style --- .../Language/LanguageService.cs | 93 ++++++++++--------- 1 file changed, 51 insertions(+), 42 deletions(-) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index 0135f40d3..0241f629a 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -26,19 +26,28 @@ public class LanguageService { #region Private Fields - private ILogger logger; - private bool areAliasesLoaded; - private PowerShellContext powerShellContext; - private CompletionResults mostRecentCompletions; - private int mostRecentRequestLine; - private int mostRecentRequestOffest; - private string mostRecentRequestFile; - private Dictionary> CmdletToAliasDictionary; - private Dictionary AliasToCmdletDictionary; - private IDocumentSymbolProvider[] documentSymbolProviders; - const int DefaultWaitTimeoutMilliseconds = 5000; + private readonly ILogger _logger; + + private readonly PowerShellContext _powerShellContext; + + private readonly Dictionary> _cmdletToAliasDictionary; + + private readonly Dictionary _aliasToCmdletDictionary; + + private readonly IDocumentSymbolProvider[] _documentSymbolProviders; + + private bool _areAliasesLoaded; + + private CompletionResults _mostRecentCompletions; + + private int _mostRecentRequestLine; + + private int _mostRecentRequestOffest; + + private string _mostRecentRequestFile; + #endregion #region Constructors @@ -57,12 +66,12 @@ public LanguageService( { Validate.IsNotNull("powerShellContext", powerShellContext); - this.powerShellContext = powerShellContext; - this.logger = logger; + _powerShellContext = powerShellContext; + _logger = logger; - this.CmdletToAliasDictionary = new Dictionary>(StringComparer.OrdinalIgnoreCase); - this.AliasToCmdletDictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); - this.documentSymbolProviders = new IDocumentSymbolProvider[] + _cmdletToAliasDictionary = new Dictionary>(StringComparer.OrdinalIgnoreCase); + _aliasToCmdletDictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); + _documentSymbolProviders = new IDocumentSymbolProvider[] { new ScriptDocumentSymbolProvider(powerShellContext.LocalPowerShellVersion.Version), new PsdDocumentSymbolProvider(), @@ -109,8 +118,8 @@ await AstOperations.GetCompletions( scriptFile.ScriptAst, scriptFile.ScriptTokens, fileOffset, - this.powerShellContext, - this.logger, + _powerShellContext, + _logger, new CancellationTokenSource(DefaultWaitTimeoutMilliseconds).Token); if (commandCompletion == null) @@ -126,10 +135,10 @@ await AstOperations.GetCompletions( commandCompletion); // save state of most recent completion - mostRecentCompletions = completionResults; - mostRecentRequestFile = scriptFile.Id; - mostRecentRequestLine = lineNumber; - mostRecentRequestOffest = columnNumber; + _mostRecentCompletions = completionResults; + _mostRecentRequestFile = scriptFile.Id; + _mostRecentRequestLine = lineNumber; + _mostRecentRequestOffest = columnNumber; return completionResults; } @@ -137,7 +146,7 @@ await AstOperations.GetCompletions( { // Bad completion results could return an invalid // replacement range, catch that here - this.logger.Write( + _logger.Write( LogLevel.Error, $"Caught exception while trying to create CompletionResults:\n\n{e.ToString()}"); @@ -155,12 +164,12 @@ public CompletionDetails GetCompletionDetailsInFile( ScriptFile file, string entryName) { - if (!file.Id.Equals(this.mostRecentRequestFile)) + if (!file.Id.Equals(_mostRecentRequestFile)) { return null; } - foreach (CompletionDetails completion in this.mostRecentCompletions.Completions) + foreach (CompletionDetails completion in _mostRecentCompletions.Completions) { if (completion.CompletionText.Equals(entryName)) { @@ -258,7 +267,7 @@ public async Task FindSymbolDetailsAtLocation( symbolDetails = await SymbolDetails.Create( symbolReference, - this.powerShellContext); + _powerShellContext); return symbolDetails; } @@ -273,7 +282,7 @@ public FindOccurrencesResult FindSymbolsInFile(ScriptFile scriptFile) Validate.IsNotNull("scriptFile", scriptFile); var foundOccurrences = new List(); - foreach (IDocumentSymbolProvider symbolProvider in documentSymbolProviders) + foreach (IDocumentSymbolProvider symbolProvider in _documentSymbolProviders) { foreach (SymbolReference reference in symbolProvider.ProvideDocumentSymbols(scriptFile)) { @@ -355,8 +364,8 @@ public async Task FindReferencesOfSymbol( IEnumerable references = AstOperations.FindReferencesOfSymbol( file.ScriptAst, foundSymbol, - CmdletToAliasDictionary, - AliasToCmdletDictionary); + _cmdletToAliasDictionary, + _aliasToCmdletDictionary); foreach (SymbolReference reference in references) { @@ -367,7 +376,7 @@ public async Task FindReferencesOfSymbol( catch (ArgumentOutOfRangeException e) { reference.SourceLine = string.Empty; - this.logger.WriteException("Found reference is out of range in script file", e); + _logger.WriteException("Found reference is out of range in script file", e); } reference.FilePath = file.FilePath; symbolReferences.Add(reference); @@ -462,7 +471,7 @@ public async Task GetDefinitionOfSymbol( CommandInfo cmdInfo = await CommandHelpers.GetCommandInfo( foundSymbol.SymbolName, - this.powerShellContext); + _powerShellContext); foundDefinition = FindDeclarationForBuiltinCommand( @@ -540,7 +549,7 @@ public async Task FindParameterSetsInFile( CommandInfo commandInfo = await CommandHelpers.GetCommandInfo( foundSymbol.SymbolName, - this.powerShellContext); + _powerShellContext); if (commandInfo == null) { @@ -557,7 +566,7 @@ await CommandHelpers.GetCommandInfo( // A RuntimeException will be thrown when an invalid attribute is // on a parameter binding block and then that command/script has // its signatures resolved by typing it into a script. - this.logger.WriteException("RuntimeException encountered while accessing command parameter sets", e); + _logger.WriteException("RuntimeException encountered while accessing command parameter sets", e); return null; } @@ -694,7 +703,7 @@ public FunctionDefinitionAst GetFunctionDefinitionForHelpComment( /// private async Task GetAliases() { - if (this.areAliasesLoaded) + if (_areAliasesLoaded) { return; } @@ -702,7 +711,7 @@ private async Task GetAliases() try { RunspaceHandle runspaceHandle = - await this.powerShellContext.GetRunspaceHandle( + await _powerShellContext.GetRunspaceHandle( new CancellationTokenSource(DefaultWaitTimeoutMilliseconds).Token); CommandInvocationIntrinsics invokeCommand = runspaceHandle.Runspace.SessionStateProxy.InvokeCommand; @@ -712,28 +721,28 @@ await this.powerShellContext.GetRunspaceHandle( foreach (AliasInfo aliasInfo in aliases) { - if (!CmdletToAliasDictionary.ContainsKey(aliasInfo.Definition)) + if (!_cmdletToAliasDictionary.ContainsKey(aliasInfo.Definition)) { - CmdletToAliasDictionary.Add(aliasInfo.Definition, new List() { aliasInfo.Name }); + _cmdletToAliasDictionary.Add(aliasInfo.Definition, new List() { aliasInfo.Name }); } else { - CmdletToAliasDictionary[aliasInfo.Definition].Add(aliasInfo.Name); + _cmdletToAliasDictionary[aliasInfo.Definition].Add(aliasInfo.Name); } - AliasToCmdletDictionary.Add(aliasInfo.Name, aliasInfo.Definition); + _aliasToCmdletDictionary.Add(aliasInfo.Name, aliasInfo.Definition); } - this.areAliasesLoaded = true; + _areAliasesLoaded = true; } catch (PSNotSupportedException e) { - this.logger.Write( + _logger.Write( LogLevel.Warning, $"Caught PSNotSupportedException while attempting to get aliases from remote session:\n\n{e.ToString()}"); // Prevent the aliases from being fetched again - no point if the remote doesn't support InvokeCommand. - this.areAliasesLoaded = true; + _areAliasesLoaded = true; } catch (TaskCanceledException) { From 20e207b7570f2e126b5ff927e0b464ae4cc80378 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 3 Sep 2018 10:18:37 +1000 Subject: [PATCH 5/9] [Style] Convert non-obvious var usage --- .../Language/LanguageService.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index 0241f629a..89d90fbc8 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -439,8 +439,8 @@ public async Task GetDefinitionOfSymbol( if (foundDefinition == null) { // Get a list of all powershell files in the workspace path - var allFiles = workspace.EnumeratePSFiles(); - foreach (var file in allFiles) + IEnumerable allFiles = workspace.EnumeratePSFiles(); + foreach (string file in allFiles) { if (filesSearched.Contains(file)) { @@ -592,7 +592,7 @@ public ScriptRegion FindSmallestStatementAstRegion( int lineNumber, int columnNumber) { - var ast = FindSmallestStatementAst(scriptFile, lineNumber, columnNumber); + Ast ast = FindSmallestStatementAst(scriptFile, lineNumber, columnNumber); if (ast == null) { return null; @@ -611,7 +611,7 @@ public FunctionDefinitionAst GetFunctionDefinitionAtLine( ScriptFile scriptFile, int lineNumber) { - var functionDefinitionAst = scriptFile.ScriptAst.Find( + Ast functionDefinitionAst = scriptFile.ScriptAst.Find( ast => ast is FunctionDefinitionAst && ast.Extent.StartLineNumber == lineNumber, true); @@ -631,7 +631,7 @@ public FunctionDefinitionAst GetFunctionDefinitionForHelpComment( out string helpLocation) { // check if the next line contains a function definition - var funcDefnAst = GetFunctionDefinitionAtLine(scriptFile, lineNumber + 1); + FunctionDefinitionAst funcDefnAst = GetFunctionDefinitionAtLine(scriptFile, lineNumber + 1); if (funcDefnAst != null) { helpLocation = "before"; @@ -639,7 +639,7 @@ public FunctionDefinitionAst GetFunctionDefinitionForHelpComment( } // find all the script definitions that contain the line `lineNumber` - var foundAsts = scriptFile.ScriptAst.FindAll( + IEnumerable foundAsts = scriptFile.ScriptAst.FindAll( ast => { var fdAst = ast as FunctionDefinitionAst; From 95dc5896964cf8902137f494ef0bb6c7455e90c1 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 3 Sep 2018 11:01:20 +1000 Subject: [PATCH 6/9] [Style] Use nameof for parameter validation --- .../Language/LanguageService.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index 89d90fbc8..1510dd6d6 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -64,7 +64,7 @@ public LanguageService( PowerShellContext powerShellContext, ILogger logger) { - Validate.IsNotNull("powerShellContext", powerShellContext); + Validate.IsNotNull(nameof(powerShellContext), powerShellContext); _powerShellContext = powerShellContext; _logger = logger; @@ -104,7 +104,7 @@ public async Task GetCompletionsInFile( int lineNumber, int columnNumber) { - Validate.IsNotNull("scriptFile", scriptFile); + Validate.IsNotNull(nameof(scriptFile), scriptFile); // Get the offset at the specified position. This method // will also validate the given position. @@ -279,7 +279,7 @@ await SymbolDetails.Create( /// public FindOccurrencesResult FindSymbolsInFile(ScriptFile scriptFile) { - Validate.IsNotNull("scriptFile", scriptFile); + Validate.IsNotNull(nameof(scriptFile), scriptFile); var foundOccurrences = new List(); foreach (IDocumentSymbolProvider symbolProvider in _documentSymbolProviders) @@ -406,9 +406,9 @@ public async Task GetDefinitionOfSymbol( SymbolReference foundSymbol, Workspace workspace) { - Validate.IsNotNull("sourceFile", sourceFile); - Validate.IsNotNull("foundSymbol", foundSymbol); - Validate.IsNotNull("workspace", workspace); + Validate.IsNotNull(nameof(sourceFile), sourceFile); + Validate.IsNotNull(nameof(foundSymbol), foundSymbol); + Validate.IsNotNull(nameof(workspace), workspace); ScriptFile[] referencedFiles = workspace.ExpandScriptReferences( From f072a91d279d392cdee62b53ca9431100bb1105b Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Wed, 5 Sep 2018 15:22:04 +1000 Subject: [PATCH 7/9] [Style] Address PR feedback from @tylerl0706 --- .../Language/LanguageService.cs | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index 1510dd6d6..8fda680c5 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -516,11 +516,10 @@ public FindOccurrencesResult FindOccurrencesInFile( foundSymbol, false); - return - new FindOccurrencesResult - { - FoundOccurrences = symbolOccurrences - }; + return new FindOccurrencesResult + { + FoundOccurrences = symbolOccurrences + }; } /// @@ -723,7 +722,7 @@ await _powerShellContext.GetRunspaceHandle( { if (!_cmdletToAliasDictionary.ContainsKey(aliasInfo.Definition)) { - _cmdletToAliasDictionary.Add(aliasInfo.Definition, new List() { aliasInfo.Name }); + _cmdletToAliasDictionary.Add(aliasInfo.Definition, new List{ aliasInfo.Name }); } else { @@ -804,16 +803,15 @@ private SymbolReference FindDeclarationForBuiltinCommand( workspace); SymbolReference foundDefinition = null; - for (int i = 0; i < nestedModuleFiles.Length; i++) + foreach (ScriptFile nestedModuleFile in nestedModuleFiles) { - foundDefinition = - AstOperations.FindDefinitionOfSymbol( - nestedModuleFiles[i].ScriptAst, - foundSymbol); + foundDefinition = AstOperations.FindDefinitionOfSymbol( + nestedModuleFile.ScriptAst, + foundSymbol); if (foundDefinition != null) { - foundDefinition.FilePath = nestedModuleFiles[i].FilePath; + foundDefinition.FilePath = nestedModuleFile.FilePath; break; } } From 152ebb472b26e7bdf3bd9d35962331c4e9130797 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Thu, 6 Sep 2018 16:58:23 +1000 Subject: [PATCH 8/9] Fix duplicate addition of symbols --- src/PowerShellEditorServices/Language/LanguageService.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index 8fda680c5..028ef32a1 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -381,8 +381,6 @@ public async Task FindReferencesOfSymbol( reference.FilePath = file.FilePath; symbolReferences.Add(reference); } - - symbolReferences.AddRange(symbolReferences); } return new FindReferencesResult From cf9b853cf6ebefb1779b7bf0eafccffb196fe22e Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 17 Sep 2018 14:24:06 -0700 Subject: [PATCH 9/9] re-instate comment for min ast --- src/PowerShellEditorServices/Language/LanguageService.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index 028ef32a1..70979cd2c 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -824,6 +824,7 @@ private Ast FindSmallestStatementAst(ScriptFile scriptFile, int lineNumber, int return ast is StatementAst && ast.Extent.Contains(lineNumber, columnNumber); }, true); + // Find the Ast with the smallest extent Ast minAst = scriptFile.ScriptAst; foreach (Ast ast in asts) {