From d36a4ca328b59ca631ad5b1309b6eb7407129934 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 18 Apr 2019 11:17:01 +0500 Subject: [PATCH 01/15] Step1 --- .../CoreCLR/CorePsAssemblyLoadContext.cs | 2 +- .../CoreCLR/CorePsStub.cs | 23 ++++++---- .../DscSupport/CimDSCParser.cs | 6 +-- .../MethodParametersCollection.cs | 6 +-- .../cim/WildcardPatternToCimQueryParser.cs | 6 +-- ...mdlets-over-objects.objectModel.autogen.cs | 44 ++----------------- ...lets-over-objects.xmlSerializer.autogen.cs | 13 +++--- .../engine/CmdletInfo.cs | 3 +- .../CommandCompletion/CompletionCompleters.cs | 2 +- .../CommandCompletion/CompletionResult.cs | 4 +- .../engine/CommandInfo.cs | 6 +-- .../engine/CoreAdapter.cs | 10 ++--- .../engine/DscResourceInfo.cs | 2 +- .../engine/EventManager.cs | 6 ++- .../engine/ExecutionContext.cs | 5 ++- .../ExperimentalFeature.cs | 2 +- .../engine/debugger/Breakpoint.cs | 20 ++++----- .../engine/debugger/debugger.cs | 4 +- 18 files changed, 68 insertions(+), 96 deletions(-) diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index e7cdc3debdc..a8f79175d4a 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -272,7 +272,7 @@ private Assembly Resolve(AssemblyLoadContext loadContext, AssemblyName assemblyN // Try loading from GAC if (!TryFindInGAC(assemblyName, out asmFilePath)) { - return null; + return null; } #else return null; diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index b5df89fafc2..51a035cc31e 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -276,18 +276,22 @@ internal static Type GetTypeForVarEnum(VarEnum vt) /// 2. There is no Type to represent COM types. __ComObject is a private type, and Object is too /// general. /// - internal static Type GetManagedMarshalType(VarEnum varEnum) { + internal static Type GetManagedMarshalType(VarEnum varEnum) + { Debug.Assert((varEnum & VarEnum.VT_BYREF) == 0); - if (varEnum == VarEnum.VT_CY) { + if (varEnum == VarEnum.VT_CY) + { return typeof(CurrencyWrapper); } - if (IsPrimitiveType(varEnum)) { + if (IsPrimitiveType(varEnum)) + { return _ComToManagedPrimitiveTypes[varEnum]; } - switch (varEnum) { + switch (varEnum) + { case VarEnum.VT_EMPTY: case VarEnum.VT_NULL: case VarEnum.VT_UNKNOWN: @@ -299,7 +303,7 @@ internal static Type GetManagedMarshalType(VarEnum varEnum) { return typeof(ErrorWrapper); default: - throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, ParserStrings.UnexpectedVarEnum, varEnum));; + throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, ParserStrings.UnexpectedVarEnum, varEnum)); ; } } @@ -341,9 +345,10 @@ private static Dictionary CreateComToManagedPrimitiveTypes() /// Primitive types are the basic COM types. It includes valuetypes like ints, but also reference types /// like BStrs. It does not include composite types like arrays and user-defined COM types (IUnknown/IDispatch). /// - internal static bool IsPrimitiveType(VarEnum varEnum) { - switch (varEnum) { - + internal static bool IsPrimitiveType(VarEnum varEnum) + { + switch (varEnum) + { // *** BEGIN GENERATED CODE *** // generated by function: gen_IsPrimitiveType from: generate_comdispatch.py @@ -366,7 +371,7 @@ internal static bool IsPrimitiveType(VarEnum varEnum) { case VarEnum.VT_DATE: case VarEnum.VT_BSTR: - // *** END GENERATED CODE *** + // *** END GENERATED CODE *** return true; } diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 8c57b70a38c..5af22d7a513 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -684,9 +684,9 @@ public static void Initialize(Collection errors, List moduleP if (!Directory.Exists(systemResourceRoot)) { - configSystemPath = Platform.GetFolderPath(Environment.SpecialFolder.System); - systemResourceRoot = Path.Combine(configSystemPath, "Configuration"); - inboxModulePath = InboxDscResourceModulePath; + configSystemPath = Platform.GetFolderPath(Environment.SpecialFolder.System); + systemResourceRoot = Path.Combine(configSystemPath, "Configuration"); + inboxModulePath = InboxDscResourceModulePath; } var programFilesDirectory = Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles); diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs index 1bb13247d32..098303c2118 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections.ObjectModel; + namespace Microsoft.PowerShell.Cmdletization { - using System; - using System.Collections.ObjectModel; - /// /// Collection of method parameters and their arguments /// used to invoke a method in an object model wrapped by diff --git a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs index d54bfd85fee..e9de925e3da 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System.Management.Automation; +using System.Text; + // TODO/FIXME: move this to Microsoft.PowerShell.Cim namespace (and move in source depot folder as well) namespace Microsoft.PowerShell.Cmdletization.Cim { - using System.Management.Automation; - using System.Text; - /// /// Translates a into a like-operand for WQL. /// diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs index 228288fc1b2..e6425a51056 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs @@ -1,5 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. + +using System.Xml.Serialization; + #pragma warning disable //------------------------------------------------------------------------------ // @@ -14,10 +17,9 @@ // // This source code was auto-generated by xsd, Version=4.0.30319.17929. // + namespace Microsoft.PowerShell.Cmdletization.Xml { - using System.Xml.Serialization; - /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] @@ -25,7 +27,6 @@ namespace Microsoft.PowerShell.Cmdletization.Xml [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IsNullable = false)] internal partial class PowerShellMetadata { - private ClassMetadata _classField; private EnumMetadataEnum[] _enumsField; @@ -66,7 +67,6 @@ public EnumMetadataEnum[] Enums [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ClassMetadata { - private string _versionField; private string _defaultNounField; @@ -207,7 +207,6 @@ public string ClassVersion [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ClassMetadataInstanceCmdlets { - private GetCmdletParameters _getCmdletParametersField; private GetCmdletMetadata _getCmdletField; @@ -264,7 +263,6 @@ public InstanceCmdletMetadata[] Cmdlet [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class GetCmdletParameters { - private PropertyMetadata[] _queryablePropertiesField; private Association[] _queryableAssociationsField; @@ -340,7 +338,6 @@ public string DefaultCmdletParameterSet [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class PropertyMetadata { - private TypeMetadata _typeField; private PropertyQuery[] _itemsField; @@ -420,7 +417,6 @@ public string PropertyName [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class TypeMetadata { - private string _pSTypeField; private string _eTSTypeField; @@ -462,7 +458,6 @@ public string ETSType [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class Association { - private AssociationAssociatedInstance _associatedInstanceField; private string _association1Field; @@ -537,7 +532,6 @@ public string ResultRole [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class AssociationAssociatedInstance { - private TypeMetadata _typeField; private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField; @@ -577,7 +571,6 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForGetCmdletFilteringParameter : CmdletParameterMetadataForGetCmdletParameter { - private bool _errorOnNoMatchField; private bool _errorOnNoMatchFieldSpecified; @@ -620,7 +613,6 @@ public bool ErrorOnNoMatchSpecified [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForGetCmdletParameter : CmdletParameterMetadata { - private bool _valueFromPipelineField; private bool _valueFromPipelineFieldSpecified; @@ -717,7 +709,6 @@ public string[] CmdletParameterSets [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadata { - private object _allowEmptyCollectionField; private object _allowEmptyStringField; @@ -971,7 +962,6 @@ public string Position [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataValidateCount { - private string _minField; private string _maxField; @@ -1013,7 +1003,6 @@ public string Max [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataValidateLength { - private string _minField; private string _maxField; @@ -1055,7 +1044,6 @@ public string Max [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataValidateRange { - private string _minField; private string _maxField; @@ -1097,7 +1085,6 @@ public string Max [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ObsoleteAttributeMetadata { - private string _messageField; /// @@ -1122,7 +1109,6 @@ public string Message [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForInstanceMethodParameter : CmdletParameterMetadata { - private bool _valueFromPipelineByPropertyNameField; private bool _valueFromPipelineByPropertyNameFieldSpecified; @@ -1164,7 +1150,6 @@ public bool ValueFromPipelineByPropertyNameSpecified [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForStaticMethodParameter : CmdletParameterMetadata { - private bool _valueFromPipelineField; private bool _valueFromPipelineFieldSpecified; @@ -1240,7 +1225,6 @@ public bool ValueFromPipelineByPropertyNameSpecified [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class QueryOption { - private TypeMetadata _typeField; private CmdletParameterMetadataForGetCmdletParameter _cmdletParameterMetadataField; @@ -1297,7 +1281,6 @@ public string OptionName [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class GetCmdletMetadata { - private CommonCmdletMetadata _cmdletMetadataField; private GetCmdletParameters _getCmdletParametersField; @@ -1337,7 +1320,6 @@ public GetCmdletParameters GetCmdletParameters [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonCmdletMetadata { - private ObsoleteAttributeMetadata _obsoleteField; private string _verbField; @@ -1462,7 +1444,6 @@ public string HelpUri [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] public enum ConfirmImpact { - /// None, @@ -1482,7 +1463,6 @@ public enum ConfirmImpact [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticCmdletMetadata { - private StaticCmdletMetadataCmdletMetadata _cmdletMetadataField; private StaticMethodMetadata[] _methodField; @@ -1523,7 +1503,6 @@ public StaticMethodMetadata[] Method [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticCmdletMetadataCmdletMetadata : CommonCmdletMetadata { - private string _defaultCmdletParameterSetField; /// @@ -1548,7 +1527,6 @@ public string DefaultCmdletParameterSet [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticMethodMetadata : CommonMethodMetadata { - private StaticMethodParameterMetadata[] _parametersField; private string _cmdletParameterSetField; @@ -1590,7 +1568,6 @@ public string CmdletParameterSet [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticMethodParameterMetadata : CommonMethodParameterMetadata { - private CmdletParameterMetadataForStaticMethodParameter _cmdletParameterMetadataField; private CmdletOutputMetadata _cmdletOutputMetadataField; @@ -1630,7 +1607,6 @@ public CmdletOutputMetadata CmdletOutputMetadata [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletOutputMetadata { - private object _errorCodeField; private string _pSNameField; @@ -1673,7 +1649,6 @@ public string PSName [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonMethodParameterMetadata { - private TypeMetadata _typeField; private string _parameterNameField; @@ -1731,7 +1706,6 @@ public string DefaultValue [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class InstanceMethodParameterMetadata : CommonMethodParameterMetadata { - private CmdletParameterMetadataForInstanceMethodParameter _cmdletParameterMetadataField; private CmdletOutputMetadata _cmdletOutputMetadataField; @@ -1773,7 +1747,6 @@ public CmdletOutputMetadata CmdletOutputMetadata [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonMethodMetadata { - private CommonMethodMetadataReturnValue _returnValueField; private string _methodNameField; @@ -1814,7 +1787,6 @@ public string MethodName [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonMethodMetadataReturnValue { - private TypeMetadata _typeField; private CmdletOutputMetadata _cmdletOutputMetadataField; @@ -1854,7 +1826,6 @@ public CmdletOutputMetadata CmdletOutputMetadata [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class InstanceMethodMetadata : CommonMethodMetadata { - private InstanceMethodParameterMetadata[] _parametersField; /// @@ -1879,7 +1850,6 @@ public InstanceMethodParameterMetadata[] Parameters [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class InstanceCmdletMetadata { - private CommonCmdletMetadata _cmdletMetadataField; private InstanceMethodMetadata _methodField; @@ -1936,7 +1906,6 @@ public GetCmdletParameters GetCmdletParameters [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class PropertyQuery { - private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField; /// @@ -1960,7 +1929,6 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class WildcardablePropertyQuery : PropertyQuery { - private bool _allowGlobbingField; private bool _allowGlobbingFieldSpecified; @@ -2001,7 +1969,6 @@ public bool AllowGlobbingSpecified [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IncludeInSchema = false)] public enum ItemsChoiceType { - /// ExcludeQuery, @@ -2021,7 +1988,6 @@ public enum ItemsChoiceType [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ClassMetadataData { - private string _nameField; private string _valueField; @@ -2063,7 +2029,6 @@ public string Value [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class EnumMetadataEnum { - private EnumMetadataEnumValue[] _valueField; private string _enumNameField; @@ -2156,7 +2121,6 @@ public bool BitwiseFlagsSpecified [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class EnumMetadataEnumValue { - private string _nameField; private string _valueField; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index 69fbe8217e9..1c9a66549ad 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -3,17 +3,16 @@ #if CORECLR +using System; +using System.Collections; +using System.Globalization; +using System.Xml; +using System.Xml.Schema; + #pragma warning disable namespace Microsoft.PowerShell.Cmdletization.Xml { - - using System; - using System.Collections; - using System.Globalization; - using System.Xml; - using System.Xml.Schema; - internal class XmlSerializationReader1 { #region Copy_From_XmlSerializationReader diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index a06c5307a82..e54838822e5 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -533,7 +533,8 @@ internal string FullName /// internal override CommandMetadata CommandMetadata { - get { + get + { return _cmdletMetadata ?? (_cmdletMetadata = CommandMetadata.Get(this.Name, this.ImplementingType, Context)); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index d117e09428a..6e3a364e5ff 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -6050,7 +6050,7 @@ internal static List CompleteHelpTopics(CompletionContext cont // Add the user scope path first, since it is searched in order. var userHelpRoot = Path.Combine(HelpUtils.GetUserHomeHelpSearchPath(), currentCulture); - if(Directory.Exists(userHelpRoot)) + if (Directory.Exists(userHelpRoot)) { searchPaths.Add(userHelpRoot); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs index 15647ed3279..50f3e946d3f 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; + namespace System.Management.Automation { - using System; - /// /// Possible types of CompletionResults. /// diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index 37797460db9..8787a3f1f98 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -180,14 +180,14 @@ internal CommandInfo(string name, CommandInfo other) /// public string Name { get; private set; } = string.Empty; -// Name + // Name /// /// Gets the type of the command. /// public CommandTypes CommandType { get; private set; } = CommandTypes.Application; -// CommandType + // CommandType /// /// Gets the source of the command (shown by default in Get-Command) @@ -938,7 +938,7 @@ internal static PSSyntheticTypeName Create(PSTypeName typename, IList(); members.AddRange(membersTypes); - members.Sort((c1,c2) => string.Compare(c1.Name, c2.Name, StringComparison.OrdinalIgnoreCase)); + members.Sort((c1, c2) => string.Compare(c1.Name, c2.Name, StringComparison.OrdinalIgnoreCase)); return new PSSyntheticTypeName(typeName, typename.Type, members); } diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 442da89fd3a..0fda88e80c1 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -2140,7 +2140,7 @@ internal object Invoke(object target, object[] arguments) return ctor.Invoke(arguments); } - var methodInfo = (MethodInfo) method; + var methodInfo = (MethodInfo)method; if (methodInfo.ReturnType.IsByRefLike) { throw new MethodException( @@ -3577,10 +3577,10 @@ private T GetDotNetPropertyImpl(object obj, string propertyName, MemberNamePr { case null: return null; case PropertyCacheEntry cacheEntry when lookingForProperties: - { - var isHidden = cacheEntry.member.GetCustomAttributes(typeof(HiddenAttribute), false).Any(); - return new PSProperty(cacheEntry.member.Name, this, obj, cacheEntry) { IsHidden = isHidden } as T; - } + { + var isHidden = cacheEntry.member.GetCustomAttributes(typeof(HiddenAttribute), false).Any(); + return new PSProperty(cacheEntry.member.Name, this, obj, cacheEntry) { IsHidden = isHidden } as T; + } case ParameterizedPropertyCacheEntry paramCacheEntry when lookingForParameterizedProperties: // TODO: check for HiddenAttribute diff --git a/src/System.Management.Automation/engine/DscResourceInfo.cs b/src/System.Management.Automation/engine/DscResourceInfo.cs index 1a874c755fb..a94cef1eb1b 100644 --- a/src/System.Management.Automation/engine/DscResourceInfo.cs +++ b/src/System.Management.Automation/engine/DscResourceInfo.cs @@ -118,7 +118,7 @@ public void UpdateProperties(IList properties) /// public string HelpFile { get; internal set; } = string.Empty; -// HelpFile + // HelpFile } /// diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 7e9a007e10e..4c704bccb13 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -2289,8 +2289,10 @@ internal PSEventArgs(string computerName, Guid runspaceId, int eventIdentifier, /// /// Gets the time and date that this event was generated. /// - public DateTime TimeGenerated { get; internal set; -// internal setter using during deserialization + public DateTime TimeGenerated + { + // internal setter using during deserialization + get; internal set; } /// diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 33ac31dce58..2f7d0a7a448 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -715,9 +715,10 @@ internal CommandDiscovery CommandDiscovery /// /// Interface that should be used for interaction with host. /// - internal InternalHost EngineHostInterface { get; private set; - + internal InternalHost EngineHostInterface + { // set not provided: it's not meaningful to change the host post-construction. + get; private set; } /// diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 443720eb4f3..5c47fe73f3a 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -317,7 +317,7 @@ public ExperimentalAttribute(string experimentName, ExperimentAction experimentA /// /// Initialize an instance that represents the none-value. /// - private ExperimentalAttribute() {} + private ExperimentalAttribute() { } /// /// An instance that represents the none-value. diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index f7372a27520..a09f9300387 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -64,7 +64,7 @@ internal bool IsScriptBreakpoint /// protected Breakpoint(string script) : this(script, null) - {} + { } /// /// Creates a new instance of a @@ -83,7 +83,7 @@ protected Breakpoint(string script, ScriptBlock action) /// protected Breakpoint(string script, int id) : this(script, null, id) - {} + { } /// /// Creates a new instance of a @@ -161,8 +161,8 @@ public class CommandBreakpoint : Breakpoint /// public CommandBreakpoint(string script, WildcardPattern command, string commandString) : this(script, command, commandString, null) - {} - + { } + /// /// Creates a new instance of a /// @@ -178,7 +178,7 @@ public CommandBreakpoint(string script, WildcardPattern command, string commandS /// public CommandBreakpoint(string script, WildcardPattern command, string commandString, int id) : this(script, command, commandString, null, id) - {} + { } /// /// Creates a new instance of a @@ -284,7 +284,7 @@ public class VariableBreakpoint : Breakpoint /// public VariableBreakpoint(string script, string variable, VariableAccessMode accessMode) : this(script, variable, accessMode, null) - {} + { } /// /// Creates a new instance of a . @@ -301,7 +301,7 @@ public VariableBreakpoint(string script, string variable, VariableAccessMode acc /// public VariableBreakpoint(string script, string variable, VariableAccessMode accessMode, int id) : this(script, variable, accessMode, null, id) - {} + { } /// /// Creates a new instance of a . @@ -366,7 +366,7 @@ public class LineBreakpoint : Breakpoint /// public LineBreakpoint(string script, int line) : this(script, line, null) - {} + { } /// /// Creates a new instance of a @@ -385,7 +385,7 @@ public LineBreakpoint(string script, int line, ScriptBlock action) /// public LineBreakpoint(string script, int line, int column) : this(script, line, column, null) - {} + { } /// /// Creates a new instance of a @@ -404,7 +404,7 @@ public LineBreakpoint(string script, int line, int column, ScriptBlock action) /// public LineBreakpoint(string script, int line, int column, int id) : this(script, line, column, null, id) - {} + { } /// /// Creates a new instance of a diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 1d2c1624d0f..26401c815a3 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -2680,7 +2680,7 @@ internal static void SetDebugJobAsync(IJobDebugger debuggableJob, bool isAsync) internal override void DebugRunspace(Runspace runspace) { - DebugRunspace(runspace, disableBreakAll:false); + DebugRunspace(runspace, disableBreakAll: false); } /// @@ -4028,7 +4028,7 @@ public override void SetBreakpoints(IEnumerable breakpoints) /// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets. /// /// Id of the breakpoint you want. - public override Breakpoint GetBreakpoint(int id) => + public override Breakpoint GetBreakpoint(int id) => _wrappedDebugger.GetBreakpoint(id); /// From e9b049a59427b56fc947658e4e4a23b21f912ba4 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 18 Apr 2019 11:20:40 +0500 Subject: [PATCH 02/15] Step 2 --- .../engine/GetCommandCommand.cs | 1 - .../engine/GetEvent_Types_Ps1Xml.cs | 2 +- .../engine/InformationRecord.cs | 2 +- .../engine/InternalCommands.cs | 2 +- .../engine/InvocationInfo.cs | 3 +- .../engine/Modules/ModuleCmdletBase.cs | 41 ++++++++++--------- .../engine/Modules/ModuleUtils.cs | 2 +- .../Modules/NewModuleManifestCommand.cs | 3 +- .../engine/MshCmdlet.cs | 12 +++--- .../engine/MshMemberInfo.cs | 24 +++++------ .../engine/hostifaces/ChoiceDescription.cs | 1 - .../engine/hostifaces/Connection.cs | 7 +++- .../engine/hostifaces/ListModifier.cs | 10 ++--- .../engine/hostifaces/MshHostUserInterface.cs | 6 +-- .../engine/interpreter/AddInstruction.cs | 4 +- .../engine/interpreter/DivInstruction.cs | 2 +- .../engine/interpreter/EqualInstruction.cs | 2 +- .../interpreter/GreaterThanInstruction.cs | 2 +- .../engine/interpreter/LessThanInstruction.cs | 2 +- .../engine/interpreter/MulInstruction.cs | 4 +- .../engine/interpreter/NotEqualInstruction.cs | 2 +- .../engine/interpreter/SubInstruction.cs | 4 +- .../engine/lang/parserutils.cs | 5 ++- 23 files changed, 74 insertions(+), 69 deletions(-) diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 832134039e1..58bd1ab30a5 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -571,7 +571,6 @@ private void OutputResultsHelper(IEnumerable results) Telemetry.Internal.TelemetryAPI.ReportGetCommandFailed(Name, _timer.ElapsedMilliseconds); } #endif - } /// diff --git a/src/System.Management.Automation/engine/GetEvent_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/GetEvent_Types_Ps1Xml.cs index 16d38a9d1cb..06d8d12be45 100644 --- a/src/System.Management.Automation/engine/GetEvent_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/GetEvent_Types_Ps1Xml.cs @@ -9,6 +9,7 @@ // the code is regenerated. // //------------------------------------------------------------------------------ + using System.Collections.Generic; using System.Management.Automation; using System.Reflection; @@ -39,7 +40,6 @@ static ScriptBlock GetScriptBlock(string s) public static IEnumerable Get() { - var td1 = new TypeData(@"System.Diagnostics.Eventing.Reader.EventLogConfiguration", true); td1.DefaultDisplayPropertySet = new PropertySetData(new[] { "LogName", "MaximumSizeInBytes", "RecordCount", "LogMode" }) { Name = "DefaultDisplayPropertySet" }; diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index 712b2c3acb4..3eb92db371e 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -138,7 +138,7 @@ public uint ProcessId { if (!this._processId.HasValue) { - this._processId = (uint) System.Diagnostics.Process.GetCurrentProcess().Id; + this._processId = (uint)System.Diagnostics.Process.GetCurrentProcess().Id; } return this._processId.Value; diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 1492fe96091..1a709ce102c 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -42,7 +42,7 @@ public object GetValue(PSObject inputObject, string propertyName) _getValueDynamicSite = CallSite>.Create( PSGetMemberBinder.Get( propertyName, - classScope: (Type) null, + classScope: (Type)null, @static: false)); } diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index 45fcc921ac2..a610f2829a4 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -199,7 +199,8 @@ internal InvocationInfo(PSObject psObject) /// public Dictionary BoundParameters { - get { + get + { return _boundParameters ?? (_boundParameters = new Dictionary(StringComparer.OrdinalIgnoreCase)); } diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index ac7da934a9e..337ad2e2357 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -25,6 +25,7 @@ // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { #region ModuleCmdletBase class @@ -314,27 +315,27 @@ internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumer { fileBaseName = moduleName; #endif - string qualifiedPath = Path.Combine(path, fileBaseName); - module = LoadUsingMultiVersionModuleBase(qualifiedPath, manifestProcessingFlags, options, out found); - if (!found) - { - if (name.IndexOfAny(Utils.Separators.Directory) == -1) - { - qualifiedPath = Path.Combine(qualifiedPath, fileBaseName); - } - else if (Directory.Exists(qualifiedPath)) - { - // if it points to a directory, add the basename back onto the path... - qualifiedPath = Path.Combine(qualifiedPath, Path.GetFileName(fileBaseName)); - } + string qualifiedPath = Path.Combine(path, fileBaseName); + module = LoadUsingMultiVersionModuleBase(qualifiedPath, manifestProcessingFlags, options, out found); + if (!found) + { + if (name.IndexOfAny(Utils.Separators.Directory) == -1) + { + qualifiedPath = Path.Combine(qualifiedPath, fileBaseName); + } + else if (Directory.Exists(qualifiedPath)) + { + // if it points to a directory, add the basename back onto the path... + qualifiedPath = Path.Combine(qualifiedPath, Path.GetFileName(fileBaseName)); + } - module = LoadUsingExtensions(parentModule, name, qualifiedPath, extension, null, this.BasePrefix, ss, options, manifestProcessingFlags, out found); - } + module = LoadUsingExtensions(parentModule, name, qualifiedPath, extension, null, this.BasePrefix, ss, options, manifestProcessingFlags, out found); + } - if (found) - { - break; - } + if (found) + { + break; + } #if UNIX } } @@ -686,7 +687,7 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module parentModule, moduleSpecification.Name, rootedPath, // fileBaseName - /*extension*/null, + /*extension*/null, moduleBase, // not using base from tempModuleInfoFromVerification as we are looking under moduleBase directory prefix, ss, diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index 004bfc81bc6..b54549f38ba 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -607,7 +607,7 @@ internal struct CommandScore public CommandScore(CommandInfo command, int score) { Command = command; - Score = score; + Score = score; } public CommandInfo Command; diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 05330b7f9dc..24bfe88b8bc 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -18,6 +18,7 @@ // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { #region New-ModuleManifest @@ -1260,5 +1261,5 @@ private void ValidateUriParameterValue(Uri uri, string parameterName) } } -#endregion + #endregion } diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 081e0d46c69..32a030c9666 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -83,7 +83,7 @@ public bool IsPresent /// /// The SwitchParameter object to convert to bool. /// The corresponding boolean value. - public static implicit operator bool (SwitchParameter switchParameter) + public static implicit operator bool(SwitchParameter switchParameter) { return switchParameter.IsPresent; } @@ -719,11 +719,11 @@ public Collection InvokeScript( { _context.EngineSessionState = sessionState.Internal; return InvokeScript( - sb:scriptBlock, - useNewScope:false, - writeToPipeline:PipelineResultTypes.None, - input:null, - args:args); + sb: scriptBlock, + useNewScope: false, + writeToPipeline: PipelineResultTypes.None, + input: null, + args: args); } finally { diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index d6dfd19b681..d7d78d802de 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -438,7 +438,7 @@ public PSAliasProperty(string name, string referencedMemberName, Type conversion /// A new PSMemberInfo that is a copy of this PSMemberInfo. public override PSMemberInfo Copy() { - PSAliasProperty alias = new PSAliasProperty(name, ReferencedMemberName) {ConversionType = ConversionType}; + PSAliasProperty alias = new PSAliasProperty(name, ReferencedMemberName) { ConversionType = ConversionType }; CloneBaseProperties(alias); return alias; } @@ -1757,7 +1757,7 @@ internal PSScriptProperty(string name, string getterScript, string setterScript, /// A new PSMemberInfo that is a copy of this PSMemberInfo. public override PSMemberInfo Copy() { - var property = new PSScriptProperty(name, this.GetterScript, this.SetterScript) {_shouldCloneOnAccess = _shouldCloneOnAccess}; + var property = new PSScriptProperty(name, this.GetterScript, this.SetterScript) { _shouldCloneOnAccess = _shouldCloneOnAccess }; CloneBaseProperties(property); return property; } @@ -1824,7 +1824,7 @@ internal object InvokeSetter(object scriptThis, object value) dollarUnder: AutomationNull.Value, input: AutomationNull.Value, scriptThis: scriptThis, - args: new[] {value}); + args: new[] { value }); return value; } catch (RuntimeException e) @@ -1985,7 +1985,7 @@ public override bool Equals(object obj) return false; } - return Equals((PSMethodInvocationConstraints) obj); + return Equals((PSMethodInvocationConstraints)obj); } public override int GetHashCode() @@ -2241,7 +2241,7 @@ public override object Invoke(params object[] arguments) if (_codeReferenceMethodInformation == null) { - _codeReferenceMethodInformation = DotNetAdapter.GetMethodInformationArray(new[] {CodeReference}); + _codeReferenceMethodInformation = DotNetAdapter.GetMethodInformationArray(new[] { CodeReference }); } Adapter.GetBestMethodAndArguments(CodeReference.Name, _codeReferenceMethodInformation, newArguments, out object[] convertedArguments); @@ -2420,7 +2420,7 @@ public override Collection OverloadDefinitions { get { - Collection retValue = new Collection {this.ToString()}; + Collection retValue = new Collection { this.ToString() }; return retValue; } } @@ -2431,7 +2431,7 @@ public override Collection OverloadDefinitions /// A new PSMemberInfo that is a copy of this PSMemberInfo. public override PSMemberInfo Copy() { - var method = new PSScriptMethod(this.name, _script) {_shouldCloneOnAccess = _shouldCloneOnAccess}; + var method = new PSScriptMethod(this.name, _script) { _shouldCloneOnAccess = _shouldCloneOnAccess }; CloneBaseProperties(method); return method; } @@ -2693,13 +2693,13 @@ private static Func var types = new Type[methods.Length]; for (int i = 0; i < methods.Length; i++) { - types[i] = GetMethodGroupType((MethodInfo) methods[i].method); + types[i] = GetMethodGroupType((MethodInfo)methods[i].method); } var methodGroupType = CreateMethodGroup(types, 0, types.Length); Type psMethodType = typeof(PSMethod<>).MakeGenericType(methodGroupType); var delegateType = typeof(Func); - return (Func) Delegate.CreateDelegate(delegateType, + return (Func)Delegate.CreateDelegate(delegateType, psMethodType.GetMethod("Create", BindingFlags.NonPublic | BindingFlags.Static)); } @@ -4780,7 +4780,7 @@ public override T this[string name] foreach (CollectionEntry collection in Collections) { Diagnostics.Assert(delegateOwner != null, "all integrating collections with non empty collections have an associated PSObject"); - T memberAsT = collection.GetMember((PSObject) delegateOwner, name); + T memberAsT = collection.GetMember((PSObject)delegateOwner, name); if (memberAsT != null) { return collection.CloneOrReplicateObject(delegateOwner, memberAsT); @@ -4834,7 +4834,7 @@ private PSMemberInfoInternalCollection GetIntegratedMembers(MshMemberMatchOpt delegateOwner = PSObject.AsPSObject(delegateOwner); foreach (CollectionEntry collection in Collections) { - PSMemberInfoInternalCollection members = collection.GetMembers((PSObject) delegateOwner); + PSMemberInfoInternalCollection members = collection.GetMembers((PSObject)delegateOwner); foreach (T member in members) { PSMemberInfo previousMember = returnValue[member.Name]; @@ -5066,7 +5066,7 @@ S IEnumerator.Current } } - object IEnumerator.Current => ((IEnumerator) this).Current; + object IEnumerator.Current => ((IEnumerator)this).Current; void IEnumerator.Reset() { diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index d7979a3dd59..82c35951f4c 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -13,7 +13,6 @@ namespace System.Management.Automation.Host public sealed class ChoiceDescription { - #region DO NOT REMOVE OR RENAME THESE FIELDS - it will break remoting compatibility with Windows PowerShell compatibility with Windows PowerShell private readonly string label = null; diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 6b861728716..f4f1ee4fd13 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -684,12 +684,15 @@ public abstract InitialSessionState InitialSessionState /// Get unique id for this instance of runspace. It is primarily used /// for logging purposes. /// - public Guid InstanceId { get; + public Guid InstanceId + { + get; // This id is also used to identify proxy and remote runspace objects. // We need to set this when reconstructing a remote runspace to connect // to an existing remote runspace. - internal set; } = Guid.NewGuid(); + internal set; + } = Guid.NewGuid(); /// /// Gets execution context. diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index f09376c488a..ecf72c456eb 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; + namespace System.Management.Automation { - using System; - using System.Collections.ObjectModel; - using System.Collections.Generic; - using System.Collections; - /// /// PSListModifier is a simple helper class created by the update-list cmdlet. /// The update-list cmdlet will either return an instance of this class, or diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 7924902f0cf..e867bb8449c 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -399,7 +399,7 @@ private sealed class TranscribeOnlyCookie : IDisposable private bool _disposed = false; public TranscribeOnlyCookie(PSHostUserInterface ui) { - _ui=ui; + _ui = ui; Interlocked.Increment(ref _ui._transcribeOnlyCount); } @@ -725,12 +725,12 @@ private void FlushPendingOutput() throw new ArgumentException(errorMessage); } - if(!Directory.Exists(baseDirectory)) + if (!Directory.Exists(baseDirectory)) { Directory.CreateDirectory(baseDirectory); } - if(!File.Exists(transcript.Path)) + if (!File.Exists(transcript.Path)) { File.Create(transcript.Path).Dispose(); } diff --git a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs index 5af328509d1..d4c648855aa 100644 --- a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class AddInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } @@ -152,7 +152,7 @@ public override string ToString() internal abstract class AddOvfInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs index 53a6e13316c..616a9cb8b02 100644 --- a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class DivInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs index 68c9ef1dc9c..dae62d33d47 100644 --- a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs @@ -20,7 +20,7 @@ namespace System.Management.Automation.Interpreter internal abstract class EqualInstruction : Instruction { // Perf: EqualityComparer but is 3/2 to 2 times slower. - private static Instruction s_reference,s_boolean,s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_reference, s_boolean, s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs index f5e433b8e89..24a4d5ba5bc 100644 --- a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class GreaterThanInstruction : Instruction { - private static Instruction s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs index 971b2f79040..dcb682f7473 100644 --- a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class LessThanInstruction : Instruction { - private static Instruction s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs index 4f67b5be486..16f8d6393ae 100644 --- a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class MulInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } @@ -152,7 +152,7 @@ public override string ToString() internal abstract class MulOvfInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs index d2dc09e8fc7..2262f19e0b2 100644 --- a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs @@ -20,7 +20,7 @@ namespace System.Management.Automation.Interpreter internal abstract class NotEqualInstruction : Instruction { // Perf: EqualityComparer but is 3/2 to 2 times slower. - private static Instruction s_reference,s_boolean,s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_reference, s_boolean, s_SByte, s_int16, s_char, s_int32, s_int64, s_byte, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs index 37503783107..4d64b0640ab 100644 --- a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { internal abstract class SubInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } @@ -152,7 +152,7 @@ public override string ToString() internal abstract class SubOvfInstruction : Instruction { - private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; + private static Instruction s_int16, s_int32, s_int64, s_UInt16, s_UInt32, s_UInt64, s_single, s_double; public override int ConsumedStack { get { return 2; } } diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index a55561d60d0..3108bfbc468 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -983,7 +983,8 @@ private static object ReplaceOperatorImpl(ExecutionContext context, string input return regex.Replace(input, replacementString); case ScriptBlock sb: - MatchEvaluator me = match => { + MatchEvaluator me = match => + { var result = sb.DoInvokeReturnAsIs( useLocalScope: false, /* Use current scope to be consistent with 'ForEach/Where-Object {}' and 'collection.ForEach{}/Where{}' */ errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, @@ -992,7 +993,7 @@ private static object ReplaceOperatorImpl(ExecutionContext context, string input scriptThis: AutomationNull.Value, args: Array.Empty()); - return PSObject.ToStringParser(context, result);; + return PSObject.ToStringParser(context, result); ; }; return regex.Replace(input, me); From f715af631ba74e9978943ab425d0d29239e9e8aa Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 18 Apr 2019 11:22:44 +0500 Subject: [PATCH 03/15] Step 3 --- .../engine/NativeCommandParameterBinder.cs | 22 +- .../engine/NativeCommandProcessor.cs | 1 - .../engine/PSConfiguration.cs | 2 +- .../engine/PSVersionInfo.cs | 20 +- .../engine/ParameterBinderBase.cs | 3 +- .../engine/ProcessCodeMethods.cs | 6 +- .../engine/parser/PSType.cs | 4 +- .../engine/parser/TypeInferenceVisitor.cs | 358 +++++++++--------- .../engine/parser/ast.cs | 6 +- .../engine/remoting/client/Job.cs | 2 +- .../engine/remoting/client/remoterunspace.cs | 10 +- .../remoting/commands/CustomShellCommands.cs | 4 +- .../remoting/commands/InvokeCommandCommand.cs | 1 - .../remoting/commands/PSRemotingCmdlet.cs | 1 - .../engine/remoting/commands/StartJob.cs | 2 +- .../remoting/common/RunspaceConnectionInfo.cs | 2 +- .../engine/remoting/common/throttlemanager.cs | 1 - 17 files changed, 221 insertions(+), 224 deletions(-) diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index d150dd956d3..4bdaae94a8b 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -110,15 +110,15 @@ internal void BindParameters(Collection parameters) ArrayLiteralAst arrayLiteralAst = null; switch (parameter?.ArgumentAst) { - case StringConstantExpressionAst sce: - usedQuotes = sce.StringConstantType != StringConstantType.BareWord; - break; - case ExpandableStringExpressionAst ese: - usedQuotes = ese.StringConstantType != StringConstantType.BareWord; - break; - case ArrayLiteralAst ala: - arrayLiteralAst = ala; - break; + case StringConstantExpressionAst sce: + usedQuotes = sce.StringConstantType != StringConstantType.BareWord; + break; + case ExpandableStringExpressionAst ese: + usedQuotes = ese.StringConstantType != StringConstantType.BareWord; + break; + case ArrayLiteralAst ala: + arrayLiteralAst = ala; + break; } appendOneNativeArgument(Context, argValue, @@ -220,7 +220,7 @@ private void appendOneNativeArgument(ExecutionContext context, object obj, Array // need to escape all trailing backslashes so the native command receives it correctly // according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC _arguments.Append(arg); - for (int i = arg.Length-1; i >= 0 && arg[i] == '\\'; i--) + for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--) { _arguments.Append('\\'); } @@ -383,6 +383,6 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, /// The native command to bind to. /// private NativeCommand _nativeCommand; -#endregion private members + #endregion private members } } diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 01327a1af1a..8883cb8c2db 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -557,7 +557,6 @@ private void InitNativeProcess() catch (Win32Exception e) { exceptionToRethrow = e; - } catch (PipelineStoppedException) { diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index 630bda9333f..fea5ed578d5 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -475,7 +475,7 @@ private void UpdateValueInFile(ConfigScope scope, string key, T value, bool a if (isReadSuccess) { // Read the stream into a root JObject for manipulation - jsonObject = (JObject) JToken.ReadFrom(jsonReader); + jsonObject = (JObject)JToken.ReadFrom(jsonReader); JProperty propertyToModify = jsonObject.Property(key); if (propertyToModify == null) diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 2910509b868..0f51e913af7 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -516,7 +516,7 @@ public SemanticVersion(int major, int minor, int patch) /// /// If or is less than 0. /// - public SemanticVersion(int major, int minor) : this(major, minor, 0) {} + public SemanticVersion(int major, int minor) : this(major, minor, 0) { } /// /// Construct a SemanticVersion. @@ -525,7 +525,7 @@ public SemanticVersion(int major, int minor) : this(major, minor, 0) {} /// /// If is less than 0. /// - public SemanticVersion(int major) : this(major, 0, 0) {} + public SemanticVersion(int major) : this(major, 0, 0) { } /// /// Construct a from a , @@ -671,9 +671,9 @@ private static bool TryParseVersion(string version, ref VersionResult result) } string versionSansLabel = null; - var major=0; - var minor=0; - var patch=0; + var major = 0; + var minor = 0; + var patch = 0; string preLabel = null; string buildLabel = null; @@ -688,14 +688,14 @@ private static bool TryParseVersion(string version, ref VersionResult result) { // No buildLabel: buildLabel == null // Format is 'major.minor.patch-PreReleaseLabel' - preLabel = version.Substring(dashIndex+1); + preLabel = version.Substring(dashIndex + 1); versionSansLabel = version.Substring(0, dashIndex); } else { // No PreReleaseLabel: preLabel == null // Format is 'major.minor.patch+BuildLabel' - buildLabel = version.Substring(plusIndex+1); + buildLabel = version.Substring(plusIndex + 1); versionSansLabel = version.Substring(0, plusIndex); dashIndex = -1; } @@ -713,13 +713,13 @@ private static bool TryParseVersion(string version, ref VersionResult result) else { // Format is 'major.minor.patch-PreReleaseLabel+BuildLabel' - preLabel = version.Substring(dashIndex+1, plusIndex-dashIndex-1); - buildLabel = version.Substring(plusIndex+1); + preLabel = version.Substring(dashIndex + 1, plusIndex - dashIndex - 1); + buildLabel = version.Substring(plusIndex + 1); versionSansLabel = version.Substring(0, dashIndex); } } - if ((dashIndex != -1 && string.IsNullOrEmpty(preLabel)) || + if ((dashIndex != -1 && string.IsNullOrEmpty(preLabel)) || (plusIndex != -1 && string.IsNullOrEmpty(buildLabel)) || string.IsNullOrEmpty(versionSansLabel)) { diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index e25d6df5063..b294f6db607 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -777,7 +777,8 @@ private void ValidateNullOrEmptyArgument( // because a value-type value cannot be null. if (!isEmpty && !isElementValueType) { - do { + do + { object element = ParserOps.Current(null, ienum); ValidateNullOrEmptyArgument( parameter, diff --git a/src/System.Management.Automation/engine/ProcessCodeMethods.cs b/src/System.Management.Automation/engine/ProcessCodeMethods.cs index 9d8e92a0d3f..298bd0d1f1e 100644 --- a/src/System.Management.Automation/engine/ProcessCodeMethods.cs +++ b/src/System.Management.Automation/engine/ProcessCodeMethods.cs @@ -1,11 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. + using System; using System.Diagnostics; using System.Management.Automation; using System.Runtime.InteropServices; -namespace Microsoft.PowerShell { +namespace Microsoft.PowerShell +{ /// /// Helper functions for process info. /// @@ -86,5 +88,5 @@ static extern int NtQueryInformationProcess( out int returnLength); #endif - } + } } diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 50ed92dbae3..4dcbf7a9305 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -1281,7 +1281,8 @@ private static IEnumerable GetAssemblyAttributeBuilders( var ctor = typeof(DynamicClassImplementationAssemblyAttribute).GetConstructor(Type.EmptyTypes); var emptyArgs = Array.Empty(); - if (string.IsNullOrEmpty(scriptFile)) { + if (string.IsNullOrEmpty(scriptFile)) + { yield return new CustomAttributeBuilder(ctor, emptyArgs); yield break; } @@ -1292,7 +1293,6 @@ private static IEnumerable GetAssemblyAttributeBuilders( yield return new CustomAttributeBuilder(ctor, emptyArgs, propertyInfo, propertyArgs, Array.Empty(), emptyArgs); - } private static int counter = 0; diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 6e0d02d1c14..452c8847092 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -564,23 +564,23 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) switch (expression) { case ConstantExpressionAst constantExpression: - { - value = constantExpression.Value; - break; - } + { + value = constantExpression.Value; + break; + } default: - { - typeName = InferTypes(kv.Item2).FirstOrDefault()?.Name; - if (typeName == null) { - if (SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out object safeValue)) + typeName = InferTypes(kv.Item2).FirstOrDefault()?.Name; + if (typeName == null) { - value = safeValue; + if (SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out object safeValue)) + { + value = safeValue; + } } - } - break; - } + break; + } } } @@ -789,33 +789,33 @@ object ICustomAstVisitor.VisitParameter(ParameterAst parameterAst) switch (attrib) { case TypeConstraintAst typeConstraint: - { - if (!typeConstraintAdded) { - res.Add(new PSTypeName(typeConstraint.TypeName)); - typeConstraintAdded = true; - } + if (!typeConstraintAdded) + { + res.Add(new PSTypeName(typeConstraint.TypeName)); + typeConstraintAdded = true; + } - break; - } - case AttributeAst attributeAst: - { - PSTypeNameAttribute attribute = null; - try - { - attribute = attributeAst.GetAttribute() as PSTypeNameAttribute; + break; } - catch (RuntimeException) + case AttributeAst attributeAst: { - } + PSTypeNameAttribute attribute = null; + try + { + attribute = attributeAst.GetAttribute() as PSTypeNameAttribute; + } + catch (RuntimeException) + { + } - if (attribute != null) - { - res.Add(new PSTypeName(attribute.PSTypeName)); - } + if (attribute != null) + { + res.Add(new PSTypeName(attribute.PSTypeName)); + } - break; - } + break; + } } } @@ -1184,21 +1184,21 @@ private void InferTypesFromGroupCommand(PseudoBindingInfo pseudoBinding, Command switch (astPair.Argument) { case StringConstantExpressionAst stringConstant: - { - properties = new[] { stringConstant.Value }; - break; - } + { + properties = new[] { stringConstant.Value }; + break; + } case ArrayLiteralAst arrayLiteral: - { - properties = arrayLiteral.Elements.OfType().Select(c => c.Value).ToArray(); - scriptBlockProperty = arrayLiteral.Elements.OfType().Any(); + { + properties = arrayLiteral.Elements.OfType().Select(c => c.Value).ToArray(); + scriptBlockProperty = arrayLiteral.Elements.OfType().Any(); break; - } + } case CommandElementAst _: - { - scriptBlockProperty = true; - break; - } + { + scriptBlockProperty = true; + break; + } } } } @@ -1313,15 +1313,15 @@ void InferFromSelectProperties(AstParameterArgumentPair astParameterArgumentPair switch (astPair.Argument) { case StringConstantExpressionAst stringConstant: - { - properties = new[] { ToWildCardOrString(stringConstant.Value) }; - break; - } + { + properties = new[] { ToWildCardOrString(stringConstant.Value) }; + break; + } case ArrayLiteralAst arrayLiteral: - { - properties = arrayLiteral.Elements.OfType().Select(c => ToWildCardOrString(c.Value)).ToArray(); - break; - } + { + properties = arrayLiteral.Elements.OfType().Select(c => ToWildCardOrString(c.Value)).ToArray(); + break; + } } if (properties == null) @@ -1347,23 +1347,23 @@ bool IsInPropertyArgument(object o) switch (propertyNameOrPattern) { case string propertyName: - { - if (string.Compare(name, propertyName, StringComparison.OrdinalIgnoreCase) == 0) { - return includeMatchedProperties; - } + if (string.Compare(name, propertyName, StringComparison.OrdinalIgnoreCase) == 0) + { + return includeMatchedProperties; + } - break; - } + break; + } case WildcardPattern pattern: - { - if (pattern.IsMatch(name)) { - return includeMatchedProperties; - } + if (pattern.IsMatch(name)) + { + return includeMatchedProperties; + } - break; - } + break; + } } } @@ -1591,155 +1591,155 @@ private bool TryGetTypeFromMember( switch (member) { case PropertyInfo propertyInfo: // .net property - { - if (propertyInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) { - result.Add(new PSTypeName(propertyInfo.PropertyType)); - return true; - } + if (propertyInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) + { + result.Add(new PSTypeName(propertyInfo.PropertyType)); + return true; + } - return false; - } + return false; + } case FieldInfo fieldInfo: // .net field - { - if (fieldInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) { - result.Add(new PSTypeName(fieldInfo.FieldType)); - return true; - } + if (fieldInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) + { + result.Add(new PSTypeName(fieldInfo.FieldType)); + return true; + } - return false; - } + return false; + } case DotNetAdapter.MethodCacheEntry methodCacheEntry: // .net method - { - if (methodCacheEntry[0].method.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { - maybeWantDefaultCtor = false; - AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); - return true; - } + if (methodCacheEntry[0].method.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) + { + maybeWantDefaultCtor = false; + AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); + return true; + } - return false; - } + return false; + } case MemberAst memberAst: // this is for members defined by PowerShell classes - { - if (memberAst.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { - if (isInvokeMemberExpressionAst) - { - if (memberAst is FunctionMemberAst functionMemberAst && !functionMemberAst.IsReturnTypeVoid()) - { - result.Add(new PSTypeName(functionMemberAst.ReturnType.TypeName)); - return true; - } - } - else + if (memberAst.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { - if (memberAst is PropertyMemberAst propertyMemberAst) + if (isInvokeMemberExpressionAst) { - result.Add( - propertyMemberAst.PropertyType != null - ? new PSTypeName(propertyMemberAst.PropertyType.TypeName) - : new PSTypeName(typeof(object))); - - return true; + if (memberAst is FunctionMemberAst functionMemberAst && !functionMemberAst.IsReturnTypeVoid()) + { + result.Add(new PSTypeName(functionMemberAst.ReturnType.TypeName)); + return true; + } } else { - // Accessing a method as a property, we'd return a wrapper over the method. - result.Add(new PSTypeName(typeof(PSMethod))); - return true; + if (memberAst is PropertyMemberAst propertyMemberAst) + { + result.Add( + propertyMemberAst.PropertyType != null + ? new PSTypeName(propertyMemberAst.PropertyType.TypeName) + : new PSTypeName(typeof(object))); + + return true; + } + else + { + // Accessing a method as a property, we'd return a wrapper over the method. + result.Add(new PSTypeName(typeof(PSMethod))); + return true; + } } } - } - return false; - } - case PSMemberInfo memberInfo: - { - if (!memberInfo.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) - { return false; } - - ScriptBlock scriptBlock = null; - switch (memberInfo) + case PSMemberInfo memberInfo: { - case PSMethod m: + if (!memberInfo.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { - if (m.adapterData is DotNetAdapter.MethodCacheEntry methodCacheEntry) - { - AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); - return true; - } - return false; } - case PSProperty p: - { - result.Add(new PSTypeName(p.Value.GetType())); - return true; - } - case PSNoteProperty noteProperty: - { - result.Add(new PSTypeName(noteProperty.Value.GetType())); - return true; - } - case PSAliasProperty aliasProperty: - { - memberNamesToCheck.Add(aliasProperty.ReferencedMemberName); - return true; - } - case PSCodeProperty codeProperty: - { - if (codeProperty.GetterCodeReference != null) - { - result.Add(new PSTypeName(codeProperty.GetterCodeReference.ReturnType)); - } - return true; - } - case PSScriptProperty scriptProperty: - { - scriptBlock = scriptProperty.GetterScript; - break; - } - case PSScriptMethod scriptMethod: - { - scriptBlock = scriptMethod.Script; - break; - } - case PSInferredProperty inferredProperty: + ScriptBlock scriptBlock = null; + switch (memberInfo) { - result.Add(inferredProperty.TypeName); - break; + case PSMethod m: + { + if (m.adapterData is DotNetAdapter.MethodCacheEntry methodCacheEntry) + { + AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); + return true; + } + + return false; + } + case PSProperty p: + { + result.Add(new PSTypeName(p.Value.GetType())); + return true; + } + case PSNoteProperty noteProperty: + { + result.Add(new PSTypeName(noteProperty.Value.GetType())); + return true; + } + case PSAliasProperty aliasProperty: + { + memberNamesToCheck.Add(aliasProperty.ReferencedMemberName); + return true; + } + case PSCodeProperty codeProperty: + { + if (codeProperty.GetterCodeReference != null) + { + result.Add(new PSTypeName(codeProperty.GetterCodeReference.ReturnType)); + } + + return true; + } + case PSScriptProperty scriptProperty: + { + scriptBlock = scriptProperty.GetterScript; + break; + } + case PSScriptMethod scriptMethod: + { + scriptBlock = scriptMethod.Script; + break; + } + case PSInferredProperty inferredProperty: + { + result.Add(inferredProperty.TypeName); + break; + } } - } - if (scriptBlock != null) - { - var thisToRestore = _context.CurrentThisType; - try + if (scriptBlock != null) { - _context.CurrentThisType = currentType; - var outputType = scriptBlock.OutputType; - if (outputType != null && outputType.Count != 0) + var thisToRestore = _context.CurrentThisType; + try { - result.AddRange(outputType); - return true; + _context.CurrentThisType = currentType; + var outputType = scriptBlock.OutputType; + if (outputType != null && outputType.Count != 0) + { + result.AddRange(outputType); + return true; + } + else + { + result.AddRange(InferTypes(scriptBlock.Ast)); + return true; + } } - else + finally { - result.AddRange(InferTypes(scriptBlock.Ast)); - return true; + _context.CurrentThisType = thisToRestore; } } - finally - { - _context.CurrentThisType = thisToRestore; - } } - } return false; } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index dd5504c5927..0ba4a21cd78 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -5415,9 +5415,8 @@ public PipelineAst(IScriptExtent extent, IEnumerable pipelineEle /// /// If is null or is an empty collection. /// - public PipelineAst(IScriptExtent extent, IEnumerable pipelineElements) :this (extent, pipelineElements, background: false) + public PipelineAst(IScriptExtent extent, IEnumerable pipelineElements) : this(extent, pipelineElements, background: false) { - } /// @@ -5450,9 +5449,8 @@ public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst, bool backgro /// /// If or is null. /// - public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst) :this (extent, commandAst, background: false) + public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst) : this(extent, commandAst, background: false) { - } /// diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 78397a2d906..9d7d539090d 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -3920,7 +3920,7 @@ public override void SetBreakpoints(IEnumerable breakpoints) /// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets. /// /// Id of the breakpoint you want. - public override Breakpoint GetBreakpoint(int id) => + public override Breakpoint GetBreakpoint(int id) => _wrappedDebugger.GetBreakpoint(id); /// diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 9d673b5a24c..895e9a6d886 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -2020,7 +2020,7 @@ public override void SetBreakpoints(IEnumerable breakpoints) /// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets. /// /// Id of the breakpoint you want. - public override Breakpoint GetBreakpoint(int id) => + public override Breakpoint GetBreakpoint(int id) => _runspace.Debugger?.GetBreakpoint(id); /// @@ -2612,12 +2612,12 @@ private void SetIsActive(int breakpointCount) } } -#endregion + #endregion } -#endregion + #endregion -#region RemoteSessionStateProxy + #region RemoteSessionStateProxy internal class RemoteSessionStateProxy : SessionStateProxy { @@ -3022,5 +3022,5 @@ public override ProviderIntrinsics InvokeProvider } } -#endregion + #endregion } diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 6d59d474f30..0fad6b71989 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -500,7 +500,7 @@ protected override void BeginProcessing() { PSInvalidOperationException ioe = new PSInvalidOperationException( StringUtil.Format(RemotingErrorIdStrings.PluginDllMissing, RemotingConstants.PSPluginDLLName)); - ThrowTerminatingError(ioe.ErrorRecord); + ThrowTerminatingError(ioe.ErrorRecord); } } @@ -1538,7 +1538,7 @@ internal static string GetWinrmPluginShellName() internal static string GetWinrmPluginDllPath() { // PowerShell Core uses its versioned directory instead of system32 - string pluginDllDirectory = System.IO.Path.Combine("%windir%\\system32\\PowerShell", PSVersionInfo.GitCommitId); + string pluginDllDirectory = System.IO.Path.Combine("%windir%\\system32\\PowerShell", PSVersionInfo.GitCommitId); return System.IO.Path.Combine(pluginDllDirectory, RemotingConstants.PSPluginDLLName); } diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 163ab16067f..a4e83ef7ad5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -1250,7 +1250,6 @@ protected override void EndProcessing() // finally dispose the job. _job.Dispose(); - } } } diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index d27be984575..482836dc600 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -3278,7 +3278,6 @@ private void HandleDebuggerStop(object sender, DebuggerStopEventArgs args) } #endregion - } /// diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index 1b43b75840d..52930ab46ee 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -335,7 +335,7 @@ public override string FilePath Mandatory = true, ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)] [ValidateTrustedData] - [Alias("PSPath","LP")] + [Alias("PSPath", "LP")] public string LiteralPath { get diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 17a1faa08d0..2040c9b82ac 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -3045,7 +3045,7 @@ internal class ContainerProcess private const uint FileNotFoundHResult = 0x80070002; // The list of executable to try in order - private static readonly string[] Executables = new string[] { "pwsh.exe", "powershell.exe"}; + private static readonly string[] Executables = new string[] { "pwsh.exe", "powershell.exe" }; #endregion diff --git a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs index 42566593f80..44c1423d8f4 100644 --- a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs +++ b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs @@ -167,7 +167,6 @@ internal void RaiseRunspaceDebugStopEvent(System.Management.Automation.Runspaces } #endregion - } #endregion IThrottleOperation From 6bf6082e0c564987dea7c1adb9bd3a6f5e56b6a9 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 18 Apr 2019 11:27:52 +0500 Subject: [PATCH 04/15] Step 4 --- .../FormatAndOutput/common/ListWriter.cs | 2 +- .../FormatAndOutput/common/TableWriter.cs | 4 +-- .../common/Utilities/Mshexpression.cs | 3 +- .../FormatAndOutput/out-console/OutConsole.cs | 15 ++++----- .../engine/SecurityManagerBase.cs | 8 ++--- .../engine/SessionStateContainer.cs | 31 +++++++++---------- .../engine/TypeTable.cs | 1 - .../engine/TypesV3_Ps1Xml.cs | 4 +-- .../engine/Types_Ps1Xml.cs | 12 +++---- .../engine/Utils.cs | 26 ++++++++-------- .../WireDataFormat/RemoteSessionCapability.cs | 2 +- .../engine/remoting/fanin/PSPrincipal.cs | 16 +++++++--- .../remoting/server/ServerPowerShellDriver.cs | 10 +++--- .../server/ServerRunspacePoolDriver.cs | 4 +-- .../remoting/server/serverremotesession.cs | 18 +++++------ .../engine/runtime/Binding/Binders.cs | 1 - .../engine/runtime/MutableTuple.cs | 2 +- .../engine/runtime/Operations/MiscOps.cs | 13 ++++---- .../engine/serialization.cs | 6 ++-- .../help/CabinetNativeApi.cs | 2 +- .../help/HelpFileHelpProvider.cs | 6 ++-- .../help/SaveHelpCommand.cs | 2 +- .../help/UpdatableHelpCommandBase.cs | 2 +- .../help/UpdateHelpCommand.cs | 6 ++-- .../namespaces/AliasProvider.cs | 1 - .../namespaces/EnvironmentProvider.cs | 3 +- 26 files changed, 104 insertions(+), 96 deletions(-) diff --git a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs index 21ad20bb5cd..03742dc79ff 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs @@ -64,7 +64,7 @@ internal void Initialize(string[] propertyNames, int screenColumnWidth, DisplayC _propertyLabelsDisplayLength = 0; // reset max // cache the cell lengths for each property - Span propertyNameCellCounts = propertyNames.Length <= OutCommandInner.StackAllocThreshold ? stackalloc int[propertyNames.Length] : new int[propertyNames.Length];; + Span propertyNameCellCounts = propertyNames.Length <= OutCommandInner.StackAllocThreshold ? stackalloc int[propertyNames.Length] : new int[propertyNames.Length]; for (int k = 0; k < propertyNames.Length; k++) { Debug.Assert(propertyNames[k] != null, "propertyNames[k] is null"); diff --git a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs index 952e716b2a6..53032ac019a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs @@ -258,7 +258,7 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, for (int k = 0; k < scArray.Length; k++) { // for the last column, don't pad it with trailing spaces - if (k == scArray.Length-1) + if (k == scArray.Length - 1) { addPadding = false; } @@ -408,7 +408,7 @@ private string GenerateRow(string[] values, ReadOnlySpan alignment, Display for (int k = 0; k < _si.columnInfo.Length; k++) { // don't pad the last column - if (k == _si.columnInfo.Length -1) + if (k == _si.columnInfo.Length - 1) { addPadding = false; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index 286cc9e14bd..54ae35c7772 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -17,7 +17,6 @@ namespace Microsoft.PowerShell.Commands /// public class PSPropertyExpressionResult { - /// /// Create a property expression result containing the original object, matching property expression /// and any exception generated during the match process. @@ -323,7 +322,7 @@ private PSPropertyExpressionResult GetValue(PSObject target, bool eatExceptions) CallSite>.Create( PSGetMemberBinder.Get( _stringValue, - classScope: (Type) null, + classScope: (Type)null, @static: false)); } diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs index 625ba2157d6..d8dca91267b 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs @@ -1,15 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Management.Automation.Internal; + +using Microsoft.PowerShell.Commands.Internal.Format; + namespace Microsoft.PowerShell.Commands { - using System; - using System.Collections; - using System.Management.Automation; - using System.Management.Automation.Host; - using System.Management.Automation.Internal; - using Microsoft.PowerShell.Commands.Internal.Format; - /// /// Null sink to absorb pipeline output. /// diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index 57dd32a3caf..18f358018a0 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -86,9 +86,9 @@ internal void ShouldRunInternal(CommandInfo commandInfo, #if DEBUG // If we are debugging, let the unit tests swap the file from beneath us - if(commandInfo.CommandType == CommandTypes.ExternalScript) + if (commandInfo.CommandType == CommandTypes.ExternalScript) { - while(Environment.GetEnvironmentVariable("PSCommandDiscoveryPreDelay") != null) { System.Threading.Thread.Sleep(100); } + while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPreDelay") != null) { System.Threading.Thread.Sleep(100); } } #endif @@ -105,9 +105,9 @@ internal void ShouldRunInternal(CommandInfo commandInfo, #if DEBUG // If we are debugging, let the unit tests swap the file from beneath us - if(commandInfo.CommandType == CommandTypes.ExternalScript) + if (commandInfo.CommandType == CommandTypes.ExternalScript) { - while(Environment.GetEnvironmentVariable("PSCommandDiscoveryPostDelay") != null) { System.Threading.Thread.Sleep(100); } + while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPostDelay") != null) { System.Threading.Thread.Sleep(100); } } #endif } diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index 546965c83cf..ac650368c74 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -1332,7 +1332,7 @@ internal void GetChildItems( bool isFileOrDirectoryPresent = false; - if(context.DynamicParameters is Microsoft.PowerShell.Commands.GetChildDynamicParameters dynParam) + if (context.DynamicParameters is Microsoft.PowerShell.Commands.GetChildDynamicParameters dynParam) { isFileOrDirectoryPresent = dynParam.File.IsPresent || dynParam.Directory.IsPresent; } @@ -1624,17 +1624,17 @@ private bool IsPathContainer( string path, CmdletProviderContext context) { - bool itemContainer = false; - try - { - itemContainer = IsItemContainer(providerInstance, path, context); - } - catch (UnauthorizedAccessException accessException) - { - context.WriteError(new ErrorRecord(accessException, "GetItemUnauthorizedAccessError", ErrorCategory.PermissionDenied, path)); - } - catch (ProviderInvocationException accessException) - { + bool itemContainer = false; + try + { + itemContainer = IsItemContainer(providerInstance, path, context); + } + catch (UnauthorizedAccessException accessException) + { + context.WriteError(new ErrorRecord(accessException, "GetItemUnauthorizedAccessError", ErrorCategory.PermissionDenied, path)); + } + catch (ProviderInvocationException accessException) + { // if providerinvocationexception is wrapping access denied error, it is ok to not terminate the pipeline if (accessException.InnerException != null && accessException.InnerException.GetType().Equals(typeof(System.UnauthorizedAccessException))) @@ -1645,10 +1645,9 @@ private bool IsPathContainer( { throw; } - } - - return itemContainer; + } + return itemContainer; } /// @@ -3428,7 +3427,7 @@ internal void NewItem( else { // To be compatible with Linux OS. Which will be either '/' or '\' depends on the OS type. - char[] charsToTrim = {' ', Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar}; + char[] charsToTrim = { ' ', Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar }; resolvePath = path.TrimEnd(charsToTrim); } diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index d807885caff..c77e80dea21 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -4531,6 +4531,5 @@ internal void Update( } #endregion internal methods - } } diff --git a/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs b/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs index 347ede9d8e6..071c4e17919 100644 --- a/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypesV3_Ps1Xml.cs @@ -8,6 +8,7 @@ // the code is regenerated. // //------------------------------------------------------------------------------ + using System.Collections.Generic; using System.Management.Automation; using System.Reflection; @@ -37,7 +38,6 @@ static ScriptBlock GetScriptBlock(string s) public static IEnumerable Get() { - var td1 = new TypeData(@"System.Security.Cryptography.X509Certificates.X509Certificate2", true); td1.Members.Add("EnhancedKeyUsageList", new ScriptPropertyData(@"EnhancedKeyUsageList", GetScriptBlock(@",(new-object Microsoft.Powershell.Commands.EnhancedKeyUsageProperty -argumentlist $this).EnhancedKeyUsageList;"), null)); @@ -107,7 +107,7 @@ public static IEnumerable Get() new CodePropertyData("SerializedInvocationInfo", GetMethodInfo(typeof(Microsoft.PowerShell.DeserializingTypeConverter), "GetInvocationInfo"), null) { IsHidden = true }); td14.SerializationMethod = "SpecificProperties"; td14.SerializationDepth = 2; - td14.PropertySerializationSet = + td14.PropertySerializationSet = new PropertySetData(new[] { "Breakpoints", "ResumeAction", "SerializedInvocationInfo" }) { Name = "PropertySerializationSet" }; yield return td14; diff --git a/src/System.Management.Automation/engine/Types_Ps1Xml.cs b/src/System.Management.Automation/engine/Types_Ps1Xml.cs index 5b28c7bc5eb..3bebaed7a32 100644 --- a/src/System.Management.Automation/engine/Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/Types_Ps1Xml.cs @@ -986,7 +986,7 @@ public static IEnumerable Get() new ScriptPropertyData(@"State", GetScriptBlock(@"$this.JobStateInfo.State.ToString()"), null)); td108.SerializationMethod = "SpecificProperties"; td108.SerializationDepth = 2; - td108.PropertySerializationSet = + td108.PropertySerializationSet = new PropertySetData(new[] { "HasMoreData", "StatusMessage", "Location", "Command", "JobStateInfo", "InstanceId", "Id", "Name", "State", "ChildJobs", "PSJobTypeName", "PSBeginTime", "PSEndTime" }) { Name = "PropertySerializationSet" }; yield return td108; @@ -1013,7 +1013,7 @@ public static IEnumerable Get() var td114 = new TypeData(@"System.Globalization.CultureInfo", true); td114.SerializationMethod = "SpecificProperties"; td114.SerializationDepth = 1; - td114.PropertySerializationSet = + td114.PropertySerializationSet = new PropertySetData(new[] { "LCID", "Name", "DisplayName", "IetfLanguageTag", "ThreeLetterISOLanguageName", "ThreeLetterWindowsLanguageName", "TwoLetterISOLanguageName" }) { Name = "PropertySerializationSet" }; yield return td114; @@ -1056,7 +1056,7 @@ public static IEnumerable Get() var td124 = new TypeData(@"System.Security.Cryptography.X509Certificates.X509Certificate2", true); td124.SerializationMethod = "SpecificProperties"; td124.SerializationDepth = 1; - td124.PropertySerializationSet = + td124.PropertySerializationSet = new PropertySetData(new[] { "RawData" }) { Name = "PropertySerializationSet" }; yield return td124; @@ -1067,7 +1067,7 @@ public static IEnumerable Get() var td126 = new TypeData(@"System.Security.Cryptography.X509Certificates.X500DistinguishedName", true); td126.SerializationMethod = "SpecificProperties"; td126.SerializationDepth = 1; - td126.PropertySerializationSet = + td126.PropertySerializationSet = new PropertySetData(new[] { "RawData" }) { Name = "PropertySerializationSet" }; yield return td126; @@ -1102,7 +1102,7 @@ public static IEnumerable Get() var td134 = new TypeData(@"System.Management.Automation.ParameterMetadata", true); td134.SerializationMethod = "SpecificProperties"; - td134.PropertySerializationSet = + td134.PropertySerializationSet = new PropertySetData(new[] { "Name", "ParameterType", "Aliases", "IsDynamic", "SwitchParameter" }) { Name = "PropertySerializationSet" }; yield return td134; @@ -1127,7 +1127,7 @@ public static IEnumerable Get() td136.Members.Add("Flags", new CodePropertyData("Flags", GetMethodInfo(typeof(Microsoft.PowerShell.DeserializingTypeConverter), "GetParameterSetMetadataFlags"), null) { IsHidden = true }); td136.SerializationMethod = "SpecificProperties"; - td136.PropertySerializationSet = + td136.PropertySerializationSet = new PropertySetData(new[] { "Position", "Flags", "HelpMessage" }) { Name = "PropertySerializationSet" }; yield return td136; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index ed3e737a63e..b114fb79c50 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -232,13 +232,13 @@ internal static BigInteger ParseBinary(ReadOnlySpan digits, bool unsigned) // circumstance was it faster or more effective than this unrolled version. outputBytes[outputByteIndex--] = (byte)( - ( (digits[byteWalker - 7] << 7) + ((digits[byteWalker - 7] << 7) | (digits[byteWalker - 6] << 6) | (digits[byteWalker - 5] << 5) | (digits[byteWalker - 4] << 4) ) | ( - ( (digits[byteWalker - 3] << 3) + ((digits[byteWalker - 3] << 3) | (digits[byteWalker - 2] << 2) | (digits[byteWalker - 1] << 1) | (digits[byteWalker]) @@ -762,17 +762,17 @@ internal static bool IsValidPSEditionValue(string editionValue) PolicyBase result = null; switch (typeof(T).Name) { - case nameof(ScriptExecution): result = policies.ScriptExecution; break; - case nameof(ScriptBlockLogging): result = policies.ScriptBlockLogging; break; - case nameof(ModuleLogging): result = policies.ModuleLogging; break; - case nameof(ProtectedEventLogging): result = policies.ProtectedEventLogging; break; - case nameof(Transcription): result = policies.Transcription; break; - case nameof(UpdatableHelp): result = policies.UpdatableHelp; break; + case nameof(ScriptExecution): result = policies.ScriptExecution; break; + case nameof(ScriptBlockLogging): result = policies.ScriptBlockLogging; break; + case nameof(ModuleLogging): result = policies.ModuleLogging; break; + case nameof(ProtectedEventLogging): result = policies.ProtectedEventLogging; break; + case nameof(Transcription): result = policies.Transcription; break; + case nameof(UpdatableHelp): result = policies.UpdatableHelp; break; case nameof(ConsoleSessionConfiguration): result = policies.ConsoleSessionConfiguration; break; default: Diagnostics.Assert(false, "Should be unreachable code. Update this switch block when new PowerShell policy types are added."); break; } - if (result != null) { return (T) result; } + if (result != null) { return (T)result; } } } @@ -889,7 +889,7 @@ internal static bool IsValidPSEditionValue(string editionValue) } // If no property is set, then we consider this policy as undefined - return isAnyPropertySet ? (T) tInstance : null; + return isAnyPropertySet ? (T)tInstance : null; } } @@ -917,7 +917,7 @@ internal static bool IsValidPSEditionValue(string editionValue) } } - if (policy != null) { return (T) policy; } + if (policy != null) { return (T)policy; } } return null; @@ -1956,8 +1956,8 @@ public static class InternalTestHooks internal static bool TestStopComputer; internal static bool TestWaitStopComputer; internal static bool TestRenameComputer; - internal static int TestStopComputerResults; - internal static int TestRenameComputerResults; + internal static int TestStopComputerResults; + internal static int TestRenameComputerResults; // It's useful to test that we don't depend on the ScriptBlock and AST objects and can use a re-parsed version. internal static bool IgnoreScriptBlockCache; diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index 304e6b817b2..15a008cba53 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -59,7 +59,7 @@ internal RemoteSessionCapability(RemotingDestination remotingDestination) // PS Version 3 is fully backward compatible with Version 2 // In the remoting protocol sense, nothing is changing between PS3 and PS2 // For negotiation to succeed with old client/servers we have to use 2. - _psversion = new Version(2,0); // PSVersionInfo.PSVersion; + _psversion = new Version(2, 0); // PSVersionInfo.PSVersion; _serversion = PSVersionInfo.SerializationVersion; _remotingDestination = remotingDestination; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs index d5b3013e778..32ce3834bce 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs @@ -118,7 +118,9 @@ public PSSenderInfo(PSPrincipal userPrincipal, string httpUrl) /// /// Contains information related to the user connecting to the server. /// - public PSPrincipal UserInfo { get; + public PSPrincipal UserInfo + { + get; // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. @@ -137,7 +139,9 @@ public TimeZoneInfo ClientTimeZone /// Connection string used by the client to connect to the server. This is /// directly taken from WSMAN_SENDER_DETAILS struct (from wsman.h) /// - public string ConnectionString { get; + public string ConnectionString + { + get; // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. @@ -173,7 +177,9 @@ public sealed class PSPrincipal : IPrincipal /// /// Gets the identity of the current user principal. /// - public PSIdentity Identity { get; + public PSIdentity Identity + { + get; // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. @@ -185,7 +191,9 @@ public sealed class PSPrincipal : IPrincipal /// a domain etc. This property tries to convert the Identity to WindowsIdentity /// using the user token supplied. /// - public WindowsIdentity WindowsIdentity { get; + public WindowsIdentity WindowsIdentity + { + get; // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index 701b7316c8d..2f55a8c5d9b 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -21,11 +21,11 @@ internal class ServerPowerShellDriver private bool _extraPowerShellAlreadyScheduled; private PowerShell _extraPowerShell; // extra PowerShell at the server to be run after localPowerShell private PSDataCollection _localPowerShellOutput; // output buffer for the local PowerShell - // that is associated with this - // powershell driver - // associated with this powershell - // data structure handler object to handle all - // communications with the client + // that is associated with this + // powershell driver + // associated with this powershell + // data structure handler object to handle all + // communications with the client private bool[] _datasent = new bool[2]; // if the remaining data has been sent // to the client before sending state // information diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 29ecb409455..e0256662fab 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -1780,7 +1780,7 @@ public override void SetBreakpoints(IEnumerable breakpoints) /// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets. /// /// Id of the breakpoint you want. - public override Breakpoint GetBreakpoint(int id) => + public override Breakpoint GetBreakpoint(int id) => _wrappedDebugger.Value.GetBreakpoint(id); /// @@ -2152,7 +2152,7 @@ internal void DoInvoke() { _results = WindowsIdentity.RunImpersonated( _identityToImpersonate.AccessToken, - () =>_wrappedDebugger.ProcessCommand(_command, _output)); + () => _wrappedDebugger.ProcessCommand(_command, _output)); return; } #endif diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index 940bcec1342..780bc622b4d 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -160,9 +160,9 @@ internal ServerRemoteSession(PSSenderInfo senderInfo, transportManager.ReceivedDataCollection.MaximumReceivedDataSize = null; } -#endregion Constructors + #endregion Constructors -#region Creation Factory + #region Creation Factory /// /// Creates a server remote session for the supplied @@ -241,9 +241,9 @@ internal static ServerRemoteSession CreateServerRemoteSession(PSSenderInfo sende return result; } -#endregion + #endregion -#region Overrides + #region Overrides /// /// This indicates the remote session object is Client, Server or Listener. @@ -458,9 +458,9 @@ internal void SendEncryptedSessionKey() SessionDataStructureHandler.StateMachine.RaiseEvent(args); } -#endregion Overrides + #endregion Overrides -#region Properties + #region Properties /// /// This property returns the ServerRemoteSessionContext object created inside @@ -474,9 +474,9 @@ internal void SendEncryptedSessionKey() /// internal ServerRemoteSessionDataStructureHandler SessionDataStructureHandler { get; } -#endregion + #endregion -#region Private/Internal Methods + #region Private/Internal Methods /// /// Let the session clear its resources. @@ -1162,6 +1162,6 @@ internal void ApplyQuotaOnCommandTransportManager(AbstractServerTransportManager cmdTransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize; } -#endregion + #endregion } } diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 94e6fd4e686..55c34275123 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -7157,7 +7157,6 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, } else { - argExprs[i] = args[i].CastOrConvertMethodArgument( parameterType, paramName, diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index 703d76b6050..2982cdf53d6 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -53,7 +53,7 @@ internal bool IsValueSet(int index) nestedTuple = (MutableTuple)nestedTuple.GetValueImpl(accessPath[i]); } - return nestedTuple._valuesSet[accessPath[length-1]]; + return nestedTuple._valuesSet[accessPath[length - 1]]; } internal void SetAutomaticVariable(AutomaticVariable auto, object value, ExecutionContext context) diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index d4c6f8f10a6..a483d54c89b 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -456,7 +456,7 @@ internal static void InvokePipeline(object input, { pipelineProcessor.Commands.RemoveAt(commandsCount - 1); commandProcessor = nextToLastCommand; - nextToLastCommand.CommandRuntime.OutputPipe = new Pipe {NullPipe = true}; + nextToLastCommand.CommandRuntime.OutputPipe = new Pipe { NullPipe = true }; } } @@ -524,14 +524,14 @@ internal static void InvokePipelineInBackground( // Prefix variables in the scriptblock with $using: foreach (var v in variables) { - var vName = ((VariableExpressionAst) v).VariablePath.UserPath; + var vName = ((VariableExpressionAst)v).VariablePath.UserPath; // Skip variables that don't exist if (funcContext._executionContext.EngineSessionState.GetVariable(vName) == null) continue; // Skip PowerShell magic variables if (Regex.Match(vName, "^(global:){0,1}(PID|PSVersionTable|PSEdition|PSHOME|HOST|TRUE|FALSE|NULL)$", - RegexOptions.IgnoreCase|RegexOptions.CultureInvariant).Success == false + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant).Success == false ) { updatedScriptblock.Append(scriptblockBodyString.Substring(position, v.Extent.StartOffset - pipelineOffset - position)); @@ -825,7 +825,7 @@ internal static void CheckForInterrupts(ExecutionContext context) internal static void Nop() { } } -#region Redirections + #region Redirections internal abstract class CommandRedirection { @@ -1234,7 +1234,7 @@ private void Dispose(bool disposing) } } -#endregion Redirections + #endregion Redirections internal static class FunctionOps { @@ -1456,7 +1456,8 @@ internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte int[] ranks = RankExceptionTypes(types); var current = new HandlerSearchResult(); - do { + do + { // Always assume no need to repeat the search for another interation continueToSearch = false; // The 'ErrorRecord' of the current RuntimeException would be passed to $_ diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 048a7491d75..c2f35a7671f 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -1888,7 +1888,8 @@ int depth private Collection> _extendedMembersCollection; private Collection> ExtendedMembersCollection { - get { + get + { return _extendedMembersCollection ?? (_extendedMembersCollection = PSObject.GetMemberCollection(PSMemberViewTypes.Extended, _typeTable)); @@ -1898,7 +1899,8 @@ private Collection> ExtendedMembersCollection private Collection> _allPropertiesCollection; private Collection> AllPropertiesCollection { - get { + get + { return _allPropertiesCollection ?? (_allPropertiesCollection = PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable)); } diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index a22ad7f3dc8..db5a3ec7452 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -232,7 +232,7 @@ internal static IntPtr FdiOpen(string filename, int oflag, int pmode) // This method is used for opening the cab file as well as saving the extracted files. // When we are opening the cab file we only need read permissions. // We force read permissions so that non-elevated users can extract cab files. - if(mode == FileMode.Open || mode == FileMode.OpenOrCreate) + if (mode == FileMode.Open || mode == FileMode.OpenOrCreate) { access = FileAccess.Read; share = FileShare.Read; diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 32066611ac8..b83385205a5 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -166,18 +166,18 @@ private Collection FilterToLatestModuleVersion(Collection filesM // This is done after the version check filtering to ensure we do not remove later version files. HashSet fileNameHash = new HashSet(); - foreach(var file in filesMatched) + foreach (var file in filesMatched) { string fileName = Path.GetFileName(file); - if(!fileNameHash.Contains(fileName)) + if (!fileNameHash.Contains(fileName)) { fileNameHash.Add(fileName); } else { // If the file need to be removed, add it to matchedFilesToRemove, if not already present. - if(!matchedFilesToRemove.Contains(file)) + if (!matchedFilesToRemove.Contains(file)) { matchedFilesToRemove.Add(file); } diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index 407aae5b788..a1bb355ab9d 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -62,7 +62,7 @@ public string[] DestinationPath /// Specifies the literal path to save updates to. /// [Parameter(Mandatory = true, ParameterSetName = LiteralPathParameterSetName)] - [Alias("PSPath","LP")] + [Alias("PSPath", "LP")] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 05634917a56..0127f5518be 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -883,7 +883,7 @@ internal void ProcessException(string moduleName, string culture, Exception e) #endregion } - /// + /// /// Scope to which the help should be saved. /// public enum UpdateHelpScope diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 9fb1a059b3f..e5514ff6e42 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -94,7 +94,7 @@ public string[] SourcePath /// Specifies the literal path to save updates to. /// [Parameter(ParameterSetName = LiteralPathParameterSetName, ValueFromPipelineByPropertyName = true)] - [Alias("PSPath","LP")] + [Alias("PSPath", "LP")] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath @@ -223,7 +223,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string moduleBase = module.ModuleBase; - if(this.Scope == UpdateHelpScope.CurrentUser) + if (this.Scope == UpdateHelpScope.CurrentUser) { moduleBase = HelpUtils.GetModuleBaseForUserHelp(moduleBase, module.ModuleName); } @@ -391,7 +391,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, // Gather destination paths Collection destPaths = new Collection(); - if(!Directory.Exists(moduleBase)) + if (!Directory.Exists(moduleBase)) { Directory.CreateDirectory(moduleBase); } diff --git a/src/System.Management.Automation/namespaces/AliasProvider.cs b/src/System.Management.Automation/namespaces/AliasProvider.cs index 3ce1bc8a219..aafed93a880 100644 --- a/src/System.Management.Automation/namespaces/AliasProvider.cs +++ b/src/System.Management.Automation/namespaces/AliasProvider.cs @@ -318,7 +318,6 @@ internal override bool CanRenameItem(object item) } #endregion protected members - } /// diff --git a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs index 6a9227030e0..a8c03994869 100644 --- a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs +++ b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs @@ -200,7 +200,8 @@ internal override IDictionary GetSessionStateTable() // (If, by contrast, we just used `entry` as-is every time a duplicate is encountered, // it could - intermittently - represent a value *other* than the effective one.) string effectiveValue = Environment.GetEnvironmentVariable((string)entry.Key); - if (((string)entry.Value).Equals(effectiveValue, StringComparison.Ordinal)) { // We've found the effective definition. + if (((string)entry.Value).Equals(effectiveValue, StringComparison.Ordinal)) + { // We've found the effective definition. // Note: We *recreate* the entry so that the specific name casing of the // effective definition is also reflected. However, if the case variants // define the same value, it is unspecified which name variant is reflected From f48fd6f88f5e53c9b03bbeca77edb11e08862e3a Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 18 Apr 2019 11:31:56 +0500 Subject: [PATCH 05/15] Step 5 --- .../namespaces/FileSystemProvider.cs | 9 ++- .../namespaces/LocationGlobber.cs | 18 +++--- .../security/SecuritySupport.cs | 58 +++++++++---------- .../utils/EncodingUtils.cs | 8 +-- .../utils/ExecutionExceptions.cs | 3 +- .../utils/IObjectWriter.cs | 8 +-- .../utils/ObjectReader.cs | 14 ++--- .../utils/PSTelemetryMethods.cs | 4 +- .../utils/PlatformInvokes.cs | 1 - .../utils/PowerShellETWTracer.cs | 4 +- .../utils/PsUtils.cs | 2 +- .../utils/Verbs.cs | 10 ++-- .../EtwActivityReverterMethodInvoker.cs | 16 ++--- .../utils/tracing/PSEtwLog.cs | 1 - .../utils/tracing/SysLogProvider.cs | 8 +-- 15 files changed, 80 insertions(+), 84 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 278049098c1..8427c2ed82e 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -355,7 +355,7 @@ public string GetHelpMaml(string helpItemName, string path) protected override ProviderInfo Start(ProviderInfo providerInfo) { // Set the home folder for the user - if (providerInfo != null && string.IsNullOrEmpty(providerInfo.Home)) + if (providerInfo != null && string.IsNullOrEmpty(providerInfo.Home)) { // %USERPROFILE% - indicate where a user's home directory is located in the file system. string homeDirectory = Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home); @@ -1910,10 +1910,10 @@ string ToModeString(FileSystemInfo fileSystemInfo) ReadOnlySpan mode = stackalloc char[] { isLink ? 'l' : isDirectory ? 'd' : '-', - fileAttributes.HasFlag(FileAttributes.Archive) ? 'a' : '-', + fileAttributes.HasFlag(FileAttributes.Archive) ? 'a' : '-', fileAttributes.HasFlag(FileAttributes.ReadOnly) ? 'r' : '-', - fileAttributes.HasFlag(FileAttributes.Hidden) ? 'h' : '-', - fileAttributes.HasFlag(FileAttributes.System) ? 's' : '-', + fileAttributes.HasFlag(FileAttributes.Hidden) ? 'h' : '-', + fileAttributes.HasFlag(FileAttributes.System) ? 's' : '-', }; return new string(mode); } @@ -7435,7 +7435,6 @@ public Encoding Encoding /// if the stream was opened with a user-specified encoding, false otherwise. /// public bool WasStreamTypeSpecified { get; private set; } - } /// diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 4621681764a..efb9ac1298b 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -1524,10 +1524,10 @@ internal static bool IsAbsolutePath(string path) { // see if there are any path separators before the colon which would mean the // colon is part of a file or folder name and not a drive: ./foo:bar vs foo:bar - int separator = path.IndexOf(StringLiterals.DefaultPathSeparator, 0, index-1); + int separator = path.IndexOf(StringLiterals.DefaultPathSeparator, 0, index - 1); if (separator == -1) { - separator = path.IndexOf(StringLiterals.AlternatePathSeparator, 0, index-1); + separator = path.IndexOf(StringLiterals.AlternatePathSeparator, 0, index - 1); } if (separator == -1 || index < separator) @@ -1930,13 +1930,13 @@ internal string GetDriveRootRelativePathFromPSPath( string relativePath = string.Empty; - relativePath = - GenerateRelativePath( - workingDriveForPath, - path, - escapeCurrentLocation, - providerInstance, - context); + relativePath = + GenerateRelativePath( + workingDriveForPath, + path, + escapeCurrentLocation, + providerInstance, + context); return relativePath; } diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 23a10505162..142fbd48a9a 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -157,43 +157,43 @@ internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPol switch (scope) { case ExecutionPolicyScope.Process: - { - if (policy == ExecutionPolicy.Undefined) - executionPolicy = null; + { + if (policy == ExecutionPolicy.Undefined) + executionPolicy = null; - Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); - break; - } + Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); + break; + } case ExecutionPolicyScope.CurrentUser: - { - // They want to remove it - if (policy == ExecutionPolicy.Undefined) { - PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.CurrentUser, shellId); - } - else - { - PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.CurrentUser, shellId, executionPolicy); - } + // They want to remove it + if (policy == ExecutionPolicy.Undefined) + { + PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.CurrentUser, shellId); + } + else + { + PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.CurrentUser, shellId, executionPolicy); + } - break; - } + break; + } case ExecutionPolicyScope.LocalMachine: - { - // They want to remove it - if (policy == ExecutionPolicy.Undefined) { - PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.AllUsers, shellId); - } - else - { - PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.AllUsers, shellId, executionPolicy); - } + // They want to remove it + if (policy == ExecutionPolicy.Undefined) + { + PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.AllUsers, shellId); + } + else + { + PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.AllUsers, shellId, executionPolicy); + } - break; - } + break; + } } #endif } @@ -477,7 +477,7 @@ private static string GetLocalPreferenceValue(string shellId, ExecutionPolicySco return null; } -#endregion execution policy + #endregion execution policy private static bool _saferIdentifyLevelApiSupported = true; diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index 2ac22b11c4c..26a1b6a60ac 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation { - internal static class EncodingConversion { internal const string Unknown = "unknown"; @@ -29,7 +28,7 @@ internal static class EncodingConversion Ascii, BigEndianUnicode, OEM, Unicode, Utf7, Utf8, Utf8Bom, Utf8NoBom, Utf32 }; - internal static Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) + internal static Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { { Ascii, System.Text.Encoding.ASCII }, { BigEndianUnicode, System.Text.Encoding.BigEndianUnicode }, @@ -79,7 +78,6 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) return null; } - } /// @@ -103,7 +101,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input return System.Text.Encoding.GetEncoding(stringName); } case int intName: - return System.Text.Encoding.GetEncoding(intName); + return System.Text.Encoding.GetEncoding(intName); } return inputData; @@ -126,6 +124,6 @@ public ArgumentEncodingCompletionsAttribute() : base( EncodingConversion.Utf8NoBom, EncodingConversion.Utf32 ) - {} + { } } } diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index bb970e8aee1..297105a1c17 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -710,7 +710,8 @@ protected ParentContainsErrorRecordException( /// public override string Message { - get { + get + { return _message ?? (_message = (_wrapperException != null) ? _wrapperException.Message : string.Empty); } } diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index fe91dc2173c..c3367ee77f3 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections; +using System.Threading; + namespace System.Management.Automation.Runspaces { - using System; - using System.Threading; - using System.Collections; - /// /// PipelineWriter allows the caller to provide an asynchronous stream of objects /// as input to a . diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index 8cfcaa49e5f..37f27e059c1 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -1,15 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Runtime.InteropServices; +using System.Threading; + namespace System.Management.Automation.Internal { - using System; - using System.Threading; - using System.Runtime.InteropServices; - using System.Collections.ObjectModel; - using System.Management.Automation.Runspaces; - using System.Management.Automation; - /// /// A PipelineReader for an ObjectStream. /// diff --git a/src/System.Management.Automation/utils/PSTelemetryMethods.cs b/src/System.Management.Automation/utils/PSTelemetryMethods.cs index 820d5aa742c..a131a7bfef4 100644 --- a/src/System.Management.Automation/utils/PSTelemetryMethods.cs +++ b/src/System.Management.Automation/utils/PSTelemetryMethods.cs @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public static class TelemetryAPI { - #region Public API +#region Public API /// /// Public API to expose Telemetry in PowerShell @@ -31,7 +31,7 @@ public static void TraceMessage(string message, T arguments) TelemetryWrapper.TraceMessage(message, arguments); } - #endregion +#endregion private static int s_anyPowerShellSessionOpen; private static DateTime s_sessionStartTime; diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index ab8ac2dc40a..9f7977dcc86 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -611,7 +611,6 @@ public STARTUPINFO() this.hStdOutput = new SafeFileHandle(IntPtr.Zero, false); this.hStdError = new SafeFileHandle(IntPtr.Zero, false); this.cb = Marshal.SizeOf(this); - } public void Dispose(bool disposing) diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index cfea7b4ac9e..d9945d4cc0f 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -11,7 +11,7 @@ namespace System.Management.Automation.Tracing { // pragma warning disable 16001,16003 -#region Constants + #region Constants /// /// Defines enumerations for event ids. @@ -682,7 +682,7 @@ public enum PowerShellTraceKeywords : ulong UseAlwaysAnalytic = 0x4000000000000000, } -#endregion + #endregion /// /// BaseChannelWriter is the abstract base class defines event specific methods that are used to write a trace. diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index 422e634228d..f9d1e9c066b 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -187,7 +187,7 @@ internal static string GetTemporaryDirectory() string tempPath = Path.GetTempPath(); do { - tempDir = Path.Combine(tempPath,System.Guid.NewGuid().ToString()); + tempDir = Path.Combine(tempPath, System.Guid.NewGuid().ToString()); } while (Directory.Exists(tempDir)); diff --git a/src/System.Management.Automation/utils/Verbs.cs b/src/System.Management.Automation/utils/Verbs.cs index caa7497c6d3..1bfefa963ad 100644 --- a/src/System.Management.Automation/utils/Verbs.cs +++ b/src/System.Management.Automation/utils/Verbs.cs @@ -1103,7 +1103,7 @@ internal static class VerbAliasPrefixes public static string GetVerbAliasPrefix(string verb) { FieldInfo aliasField = typeof(VerbAliasPrefixes).GetField(verb); - if(aliasField != null) + if (aliasField != null) { return (string)aliasField.GetValue(null); } @@ -1124,7 +1124,7 @@ public class VerbInfo /// public string Verb { - get;set; + get; set; } /// @@ -1132,7 +1132,7 @@ public string Verb /// public string AliasPrefix { - get;set; + get; set; } /// @@ -1140,7 +1140,7 @@ public string AliasPrefix /// public string Group { - get;set; + get; set; } /// @@ -1148,7 +1148,7 @@ public string Group /// public string Description { - get;set; + get; set; } } diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs index ac4440d7ded..3a753e59182 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs @@ -9,14 +9,14 @@ namespace System.Management.Automation.Tracing internal class EtwActivityReverterMethodInvoker : IMethodInvoker { -#region Instance Data + #region Instance Data private readonly IEtwEventCorrelator _eventCorrelator; private readonly Func _invoker; -#endregion + #endregion -#region Creation/Cleanup + #region Creation/Cleanup public EtwActivityReverterMethodInvoker(IEtwEventCorrelator eventCorrelator) { @@ -29,9 +29,9 @@ public EtwActivityReverterMethodInvoker(IEtwEventCorrelator eventCorrelator) _invoker = DoInvoke; } -#endregion + #endregion -#region Instance Access + #region Instance Access public Delegate Invoker { @@ -51,9 +51,9 @@ public object[] CreateInvokerArgs(Delegate methodToInvoke, object[] methodToInvo return retInvokerArgs; } -#endregion + #endregion -#region Instance Utilities + #region Instance Utilities private object DoInvoke(Guid relatedActivityId, Delegate method, object[] methodArgs) { @@ -63,7 +63,7 @@ private object DoInvoke(Guid relatedActivityId, Delegate method, object[] method } } -#endregion + #endregion } } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index 9f1f1415c4a..895e9a0309f 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -41,7 +41,6 @@ internal static void LogConsoleStartup() PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational); - } /// diff --git a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs index 56e64f9cfc3..59b2c0055cf 100755 --- a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs @@ -191,7 +191,7 @@ private bool ShouldLog(PSLevel level, PSKeyword keywords, PSChannel channel) IsEnabled(level, keywords)); } - #region resource manager +#region resource manager private static global::System.Resources.ResourceManager _resourceManager; private static global::System.Globalization.CultureInfo _resourceCulture; @@ -239,7 +239,7 @@ private static string GetResourceString(string resourceName) return value; } - #endregion resource manager +#endregion resource manager /// /// Gets the EventMessage for a given event. @@ -272,7 +272,7 @@ private static void GetEventMessage(StringBuilder sb, PSEventId eventId, params } } - #region logging +#region logging // maps a LogLevel to an associated SysLogPriority. static NativeMethods.SysLogPriority[] _levels = @@ -359,7 +359,7 @@ public void Log(PSEventId eventId, PSChannel channel, PSTask task, PSOpcode opco } } - #endregion logging +#endregion logging } internal enum LogLevel : uint From 4eac412e612e0b60aae7b39b80b5e95006b0828c Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 18 Apr 2019 11:48:54 +0500 Subject: [PATCH 06/15] Manual style fixes --- src/System.Management.Automation/CoreCLR/CorePsStub.cs | 2 +- src/System.Management.Automation/engine/lang/parserutils.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index 51a035cc31e..d132be21361 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -303,7 +303,7 @@ internal static Type GetManagedMarshalType(VarEnum varEnum) return typeof(ErrorWrapper); default: - throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, ParserStrings.UnexpectedVarEnum, varEnum)); ; + throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, ParserStrings.UnexpectedVarEnum, varEnum)); } } diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index 3108bfbc468..338efdb5f7f 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -993,7 +993,7 @@ private static object ReplaceOperatorImpl(ExecutionContext context, string input scriptThis: AutomationNull.Value, args: Array.Empty()); - return PSObject.ToStringParser(context, result); ; + return PSObject.ToStringParser(context, result); }; return regex.Replace(input, me); From e7fd5b66c7e3e55e4dfe51c1682c5bb6ba56ca54 Mon Sep 17 00:00:00 2001 From: Ilya Date: Mon, 22 Apr 2019 13:43:23 +0500 Subject: [PATCH 07/15] Fix switch in CoreAdapter.cs --- src/System.Management.Automation/engine/CoreAdapter.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 0fda88e80c1..f78777c840b 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -3575,12 +3575,11 @@ private T GetDotNetPropertyImpl(object obj, string propertyName, MemberNamePr : typeTable[propertyName]; switch (entry) { - case null: return null; + case null: + return null; case PropertyCacheEntry cacheEntry when lookingForProperties: - { - var isHidden = cacheEntry.member.GetCustomAttributes(typeof(HiddenAttribute), false).Any(); - return new PSProperty(cacheEntry.member.Name, this, obj, cacheEntry) { IsHidden = isHidden } as T; - } + var isHidden = cacheEntry.member.GetCustomAttributes(typeof(HiddenAttribute), false).Any(); + return new PSProperty(cacheEntry.member.Name, this, obj, cacheEntry) { IsHidden = isHidden } as T; case ParameterizedPropertyCacheEntry paramCacheEntry when lookingForParameterizedProperties: // TODO: check for HiddenAttribute From f99041550871dfa4acadee1443526a423c26b8bd Mon Sep 17 00:00:00 2001 From: Ilya Date: Mon, 22 Apr 2019 13:50:12 +0500 Subject: [PATCH 08/15] Fix /ModuleCmdletBase.cs --- .../engine/Modules/ModuleCmdletBase.cs | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 337ad2e2357..2d09bbeed9c 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -315,27 +315,27 @@ internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumer { fileBaseName = moduleName; #endif - string qualifiedPath = Path.Combine(path, fileBaseName); - module = LoadUsingMultiVersionModuleBase(qualifiedPath, manifestProcessingFlags, options, out found); - if (!found) - { - if (name.IndexOfAny(Utils.Separators.Directory) == -1) - { - qualifiedPath = Path.Combine(qualifiedPath, fileBaseName); - } - else if (Directory.Exists(qualifiedPath)) - { - // if it points to a directory, add the basename back onto the path... - qualifiedPath = Path.Combine(qualifiedPath, Path.GetFileName(fileBaseName)); - } + string qualifiedPath = Path.Combine(path, fileBaseName); + module = LoadUsingMultiVersionModuleBase(qualifiedPath, manifestProcessingFlags, options, out found); + if (!found) + { + if (name.IndexOfAny(Utils.Separators.Directory) == -1) + { + qualifiedPath = Path.Combine(qualifiedPath, fileBaseName); + } + else if (Directory.Exists(qualifiedPath)) + { + // if it points to a directory, add the basename back onto the path... + qualifiedPath = Path.Combine(qualifiedPath, Path.GetFileName(fileBaseName)); + } - module = LoadUsingExtensions(parentModule, name, qualifiedPath, extension, null, this.BasePrefix, ss, options, manifestProcessingFlags, out found); - } + module = LoadUsingExtensions(parentModule, name, qualifiedPath, extension, null, this.BasePrefix, ss, options, manifestProcessingFlags, out found); + } - if (found) - { - break; - } + if (found) + { + break; + } #if UNIX } } @@ -686,8 +686,8 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module module = LoadUsingExtensions( parentModule, moduleSpecification.Name, - rootedPath, // fileBaseName - /*extension*/null, + fileBaseName: rootedPath, + extension: null, moduleBase, // not using base from tempModuleInfoFromVerification as we are looking under moduleBase directory prefix, ss, From 022f52051bb924147ca3317156aa31ffc3301f0d Mon Sep 17 00:00:00 2001 From: Ilya Date: Mon, 22 Apr 2019 13:57:54 +0500 Subject: [PATCH 09/15] Fix Utils.cs --- .../engine/Utils.cs | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index b114fb79c50..808596e6f79 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -762,14 +762,30 @@ internal static bool IsValidPSEditionValue(string editionValue) PolicyBase result = null; switch (typeof(T).Name) { - case nameof(ScriptExecution): result = policies.ScriptExecution; break; - case nameof(ScriptBlockLogging): result = policies.ScriptBlockLogging; break; - case nameof(ModuleLogging): result = policies.ModuleLogging; break; - case nameof(ProtectedEventLogging): result = policies.ProtectedEventLogging; break; - case nameof(Transcription): result = policies.Transcription; break; - case nameof(UpdatableHelp): result = policies.UpdatableHelp; break; - case nameof(ConsoleSessionConfiguration): result = policies.ConsoleSessionConfiguration; break; - default: Diagnostics.Assert(false, "Should be unreachable code. Update this switch block when new PowerShell policy types are added."); break; + case nameof(ScriptExecution): + result = policies.ScriptExecution; + break; + case nameof(ScriptBlockLogging): + result = policies.ScriptBlockLogging; + break; + case nameof(ModuleLogging): + result = policies.ModuleLogging; + break; + case nameof(ProtectedEventLogging): + result = policies.ProtectedEventLogging; + break; + case nameof(Transcription): + result = policies.Transcription; + break; + case nameof(UpdatableHelp): + result = policies.UpdatableHelp; + break; + case nameof(ConsoleSessionConfiguration): + result = policies.ConsoleSessionConfiguration; + break; + default: + Diagnostics.Assert(false, "Should be unreachable code. Update this switch block when new PowerShell policy types are added."); + break; } if (result != null) { return (T)result; } From c17f9aab02fa6bf83071834cbc3040f1108b41d3 Mon Sep 17 00:00:00 2001 From: Ilya Date: Mon, 22 Apr 2019 14:04:26 +0500 Subject: [PATCH 10/15] Reformat comments in ServerPowerShellDriver.cs --- .../remoting/server/ServerPowerShellDriver.cs | 46 +++++++++++-------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index 2f55a8c5d9b..abceadb40ac 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -19,28 +19,36 @@ internal class ServerPowerShellDriver #region Private Members private bool _extraPowerShellAlreadyScheduled; - private PowerShell _extraPowerShell; // extra PowerShell at the server to be run after localPowerShell - private PSDataCollection _localPowerShellOutput; // output buffer for the local PowerShell - // that is associated with this - // powershell driver - // associated with this powershell - // data structure handler object to handle all - // communications with the client - private bool[] _datasent = new bool[2]; // if the remaining data has been sent - // to the client before sending state - // information - private object _syncObject = new object(); // sync object for synchronizing sending - // data to client - private bool _noInput; // there is no input when this driver - // was created + + // extra PowerShell at the server to be run after localPowerShell + private PowerShell _extraPowerShell; + + // output buffer for the local PowerShell that is associated with this powershell driver + // associated with this powershell data structure handler object to handle all communications with the client + private PSDataCollection _localPowerShellOutput; + + // if the remaining data has been sent to the client before sending state information + private bool[] _datasent = new bool[2]; + + // sync object for synchronizing sending data to client + private object _syncObject = new object(); + + // there is no input when this driver was created + private bool _noInput; private bool _addToHistory; - private ServerRemoteHost _remoteHost; // the server remote host instance - // associated with this powershell -#if !CORECLR // No ApartmentState In CoreCLR - private ApartmentState apartmentState; // apartment state for this powershell + + // the server remote host instance + // associated with this powershell + private ServerRemoteHost _remoteHost; + +#if !CORECLR + // No ApartmentState In CoreCLR + // apartment state for this powershell + private ApartmentState apartmentState; #endif - private IRSPDriverInvoke _psDriverInvoker; // Handles nested invocation of PS drivers. + // Handles nested invocation of PS drivers. + private IRSPDriverInvoke _psDriverInvoker; #endregion Private Members From aa6c638c315084893f350b16b26985867e0ce9e7 Mon Sep 17 00:00:00 2001 From: Ilya Date: Mon, 22 Apr 2019 14:06:52 +0500 Subject: [PATCH 11/15] Fix SecuritySupport.cs --- .../security/SecuritySupport.cs | 53 +++++++++---------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 142fbd48a9a..434532b4430 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -157,43 +157,40 @@ internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPol switch (scope) { case ExecutionPolicyScope.Process: - { - if (policy == ExecutionPolicy.Undefined) - executionPolicy = null; - Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); - break; - } + if (policy == ExecutionPolicy.Undefined) + executionPolicy = null; + + Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); + break; case ExecutionPolicyScope.CurrentUser: - { - // They want to remove it - if (policy == ExecutionPolicy.Undefined) - { - PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.CurrentUser, shellId); - } - else - { - PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.CurrentUser, shellId, executionPolicy); - } - break; + // They want to remove it + if (policy == ExecutionPolicy.Undefined) + { + PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.CurrentUser, shellId); + } + else + { + PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.CurrentUser, shellId, executionPolicy); } + break; + case ExecutionPolicyScope.LocalMachine: - { - // They want to remove it - if (policy == ExecutionPolicy.Undefined) - { - PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.AllUsers, shellId); - } - else - { - PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.AllUsers, shellId, executionPolicy); - } - break; + // They want to remove it + if (policy == ExecutionPolicy.Undefined) + { + PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.AllUsers, shellId); } + else + { + PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.AllUsers, shellId, executionPolicy); + } + + break; } #endif } From a809045e7858518cca80c5d30e2c163cc5a71111 Mon Sep 17 00:00:00 2001 From: Ilya Date: Mon, 22 Apr 2019 14:10:45 +0500 Subject: [PATCH 12/15] Fix TypeInferenceVisitor.cs --- .../engine/parser/TypeInferenceVisitor.cs | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 452c8847092..897ddc71d5d 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -564,23 +564,19 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) switch (expression) { case ConstantExpressionAst constantExpression: - { - value = constantExpression.Value; - break; - } + value = constantExpression.Value; + break; default: + typeName = InferTypes(kv.Item2).FirstOrDefault()?.Name; + if (typeName == null) { - typeName = InferTypes(kv.Item2).FirstOrDefault()?.Name; - if (typeName == null) + if (SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out object safeValue)) { - if (SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out object safeValue)) - { - value = safeValue; - } + value = safeValue; } - - break; } + + break; } } From 0f48fd867709b5f491ef4f3577ef6ddd38630d78 Mon Sep 17 00:00:00 2001 From: Ilya Date: Mon, 22 Apr 2019 14:12:51 +0500 Subject: [PATCH 13/15] Fixed TypeInferenceVisitor.cs 2 --- .../engine/parser/TypeInferenceVisitor.cs | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 897ddc71d5d..e840f65293a 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -785,33 +785,29 @@ object ICustomAstVisitor.VisitParameter(ParameterAst parameterAst) switch (attrib) { case TypeConstraintAst typeConstraint: + if (!typeConstraintAdded) { - if (!typeConstraintAdded) - { - res.Add(new PSTypeName(typeConstraint.TypeName)); - typeConstraintAdded = true; - } - - break; + res.Add(new PSTypeName(typeConstraint.TypeName)); + typeConstraintAdded = true; } + + break; case AttributeAst attributeAst: + PSTypeNameAttribute attribute = null; + try { - PSTypeNameAttribute attribute = null; - try - { - attribute = attributeAst.GetAttribute() as PSTypeNameAttribute; - } - catch (RuntimeException) - { - } - - if (attribute != null) - { - res.Add(new PSTypeName(attribute.PSTypeName)); - } + attribute = attributeAst.GetAttribute() as PSTypeNameAttribute; + } + catch (RuntimeException) + { + } - break; + if (attribute != null) + { + res.Add(new PSTypeName(attribute.PSTypeName)); } + + break; } } From 96bf7f2cc6b00cd1f05284c5b33d232675823900 Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 23 Apr 2019 08:19:07 +0500 Subject: [PATCH 14/15] Fix TypeInferenceVisitor.cs 3 --- .../engine/parser/TypeInferenceVisitor.cs | 274 ++++++++---------- 1 file changed, 118 insertions(+), 156 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index e840f65293a..8739ddfdbb1 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -127,8 +127,7 @@ internal class TypeInferenceContext public static readonly PSTypeName[] EmptyPSTypeNameArray = Array.Empty(); private readonly PowerShell _powerShell; - public TypeInferenceContext() - : this(PowerShell.Create(RunspaceMode.CurrentRunspace)) + public TypeInferenceContext() : this(PowerShell.Create(RunspaceMode.CurrentRunspace)) { } @@ -1176,21 +1175,15 @@ private void InferTypesFromGroupCommand(PseudoBindingInfo pseudoBinding, Command switch (astPair.Argument) { case StringConstantExpressionAst stringConstant: - { - properties = new[] { stringConstant.Value }; - break; - } + properties = new[] { stringConstant.Value }; + break; case ArrayLiteralAst arrayLiteral: - { - properties = arrayLiteral.Elements.OfType().Select(c => c.Value).ToArray(); - scriptBlockProperty = arrayLiteral.Elements.OfType().Any(); - break; - } + properties = arrayLiteral.Elements.OfType().Select(c => c.Value).ToArray(); + scriptBlockProperty = arrayLiteral.Elements.OfType().Any(); + break; case CommandElementAst _: - { - scriptBlockProperty = true; - break; - } + scriptBlockProperty = true; + break; } } } @@ -1305,15 +1298,11 @@ void InferFromSelectProperties(AstParameterArgumentPair astParameterArgumentPair switch (astPair.Argument) { case StringConstantExpressionAst stringConstant: - { - properties = new[] { ToWildCardOrString(stringConstant.Value) }; - break; - } + properties = new[] { ToWildCardOrString(stringConstant.Value) }; + break; case ArrayLiteralAst arrayLiteral: - { - properties = arrayLiteral.Elements.OfType().Select(c => ToWildCardOrString(c.Value)).ToArray(); - break; - } + properties = arrayLiteral.Elements.OfType().Select(c => ToWildCardOrString(c.Value)).ToArray(); + break; } if (properties == null) @@ -1339,23 +1328,19 @@ bool IsInPropertyArgument(object o) switch (propertyNameOrPattern) { case string propertyName: + if (string.Compare(name, propertyName, StringComparison.OrdinalIgnoreCase) == 0) { - if (string.Compare(name, propertyName, StringComparison.OrdinalIgnoreCase) == 0) - { - return includeMatchedProperties; - } - - break; + return includeMatchedProperties; } + + break; case WildcardPattern pattern: + if (pattern.IsMatch(name)) { - if (pattern.IsMatch(name)) - { - return includeMatchedProperties; - } - - break; + return includeMatchedProperties; } + + break; } } @@ -1444,9 +1429,12 @@ private static bool IsProperty(object member) { switch (member) { - case PropertyInfo _: return true; - case PSMemberInfo memberInfo: return (memberInfo.MemberType & PSMemberTypes.Properties) == memberInfo.MemberType; - default: return false; + case PropertyInfo _: + return true; + case PSMemberInfo memberInfo: + return (memberInfo.MemberType & PSMemberTypes.Properties) == memberInfo.MemberType; + default: + return false; } } @@ -1583,154 +1571,128 @@ private bool TryGetTypeFromMember( switch (member) { case PropertyInfo propertyInfo: // .net property + if (propertyInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) { - if (propertyInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) - { - result.Add(new PSTypeName(propertyInfo.PropertyType)); - return true; - } - - return false; + result.Add(new PSTypeName(propertyInfo.PropertyType)); + return true; } + + return false; case FieldInfo fieldInfo: // .net field + if (fieldInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) { - if (fieldInfo.Name.EqualsOrdinalIgnoreCase(memberName) && !isInvokeMemberExpressionAst) - { - result.Add(new PSTypeName(fieldInfo.FieldType)); - return true; - } - - return false; + result.Add(new PSTypeName(fieldInfo.FieldType)); + return true; } + + return false; case DotNetAdapter.MethodCacheEntry methodCacheEntry: // .net method + if (methodCacheEntry[0].method.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { - if (methodCacheEntry[0].method.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) - { - maybeWantDefaultCtor = false; - AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); - return true; - } - - return false; + maybeWantDefaultCtor = false; + AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); + return true; } + + return false; case MemberAst memberAst: // this is for members defined by PowerShell classes + if (memberAst.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { - if (memberAst.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) + if (isInvokeMemberExpressionAst) { - if (isInvokeMemberExpressionAst) + if (memberAst is FunctionMemberAst functionMemberAst && !functionMemberAst.IsReturnTypeVoid()) { - if (memberAst is FunctionMemberAst functionMemberAst && !functionMemberAst.IsReturnTypeVoid()) - { - result.Add(new PSTypeName(functionMemberAst.ReturnType.TypeName)); - return true; - } + result.Add(new PSTypeName(functionMemberAst.ReturnType.TypeName)); + return true; } - else + } + else + { + if (memberAst is PropertyMemberAst propertyMemberAst) { - if (memberAst is PropertyMemberAst propertyMemberAst) - { - result.Add( - propertyMemberAst.PropertyType != null - ? new PSTypeName(propertyMemberAst.PropertyType.TypeName) - : new PSTypeName(typeof(object))); + result.Add( + propertyMemberAst.PropertyType != null + ? new PSTypeName(propertyMemberAst.PropertyType.TypeName) + : new PSTypeName(typeof(object))); - return true; - } - else - { - // Accessing a method as a property, we'd return a wrapper over the method. - result.Add(new PSTypeName(typeof(PSMethod))); - return true; - } + return true; + } + else + { + // Accessing a method as a property, we'd return a wrapper over the method. + result.Add(new PSTypeName(typeof(PSMethod))); + return true; } } - - return false; } + + return false; case PSMemberInfo memberInfo: + if (!memberInfo.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { - if (!memberInfo.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) - { - return false; - } + return false; + } - ScriptBlock scriptBlock = null; - switch (memberInfo) - { - case PSMethod m: - { - if (m.adapterData is DotNetAdapter.MethodCacheEntry methodCacheEntry) - { - AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); - return true; - } + ScriptBlock scriptBlock = null; + switch (memberInfo) + { + case PSMethod m: + if (m.adapterData is DotNetAdapter.MethodCacheEntry methodCacheEntry) + { + AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); + return true; + } - return false; - } - case PSProperty p: - { - result.Add(new PSTypeName(p.Value.GetType())); - return true; - } - case PSNoteProperty noteProperty: - { - result.Add(new PSTypeName(noteProperty.Value.GetType())); - return true; - } - case PSAliasProperty aliasProperty: - { - memberNamesToCheck.Add(aliasProperty.ReferencedMemberName); - return true; - } - case PSCodeProperty codeProperty: - { - if (codeProperty.GetterCodeReference != null) - { - result.Add(new PSTypeName(codeProperty.GetterCodeReference.ReturnType)); - } + return false; + case PSProperty p: + result.Add(new PSTypeName(p.Value.GetType())); + return true; + case PSNoteProperty noteProperty: + result.Add(new PSTypeName(noteProperty.Value.GetType())); + return true; + case PSAliasProperty aliasProperty: + memberNamesToCheck.Add(aliasProperty.ReferencedMemberName); + return true; + case PSCodeProperty codeProperty: + if (codeProperty.GetterCodeReference != null) + { + result.Add(new PSTypeName(codeProperty.GetterCodeReference.ReturnType)); + } - return true; - } - case PSScriptProperty scriptProperty: - { - scriptBlock = scriptProperty.GetterScript; - break; - } - case PSScriptMethod scriptMethod: - { - scriptBlock = scriptMethod.Script; - break; - } - case PSInferredProperty inferredProperty: - { - result.Add(inferredProperty.TypeName); - break; - } - } + return true; + case PSScriptProperty scriptProperty: + scriptBlock = scriptProperty.GetterScript; + break; + case PSScriptMethod scriptMethod: + scriptBlock = scriptMethod.Script; + break; + case PSInferredProperty inferredProperty: + result.Add(inferredProperty.TypeName); + break; + } - if (scriptBlock != null) + if (scriptBlock != null) + { + var thisToRestore = _context.CurrentThisType; + try { - var thisToRestore = _context.CurrentThisType; - try + _context.CurrentThisType = currentType; + var outputType = scriptBlock.OutputType; + if (outputType != null && outputType.Count != 0) { - _context.CurrentThisType = currentType; - var outputType = scriptBlock.OutputType; - if (outputType != null && outputType.Count != 0) - { - result.AddRange(outputType); - return true; - } - else - { - result.AddRange(InferTypes(scriptBlock.Ast)); - return true; - } + result.AddRange(outputType); + return true; } - finally + else { - _context.CurrentThisType = thisToRestore; + result.AddRange(InferTypes(scriptBlock.Ast)); + return true; } } + finally + { + _context.CurrentThisType = thisToRestore; + } } return false; From 3fa0fa7a44cb6c461e1a1371fbc0eb18fcf4f968 Mon Sep 17 00:00:00 2001 From: Ilya Date: Tue, 23 Apr 2019 08:20:13 +0500 Subject: [PATCH 15/15] Fix CorePsStub.cs 2 --- src/System.Management.Automation/CoreCLR/CorePsStub.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index d132be21361..47cffe47be2 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -349,9 +349,6 @@ internal static bool IsPrimitiveType(VarEnum varEnum) { switch (varEnum) { - // *** BEGIN GENERATED CODE *** - // generated by function: gen_IsPrimitiveType from: generate_comdispatch.py - case VarEnum.VT_I1: case VarEnum.VT_I2: case VarEnum.VT_I4: @@ -371,8 +368,6 @@ internal static bool IsPrimitiveType(VarEnum varEnum) case VarEnum.VT_DATE: case VarEnum.VT_BSTR: - // *** END GENERATED CODE *** - return true; }