From 07b7c258c0acadc113ac8d4c49932db6ff423a62 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 18:13:00 -0300 Subject: [PATCH 01/29] bulk removal of deprecated code (workflow cleanup) --- .../engine/ArgumentTypeConverterAttribute.cs | 5 - .../engine/CommandBase.cs | 2 - .../CommandCompletion/CompletionCompleters.cs | 2 +- .../engine/ExecutionContext.cs | 2 +- .../engine/LanguagePrimitives.cs | 3 +- .../engine/MshCommandRuntime.cs | 15 - .../engine/SessionStateStrings.cs | 4 +- .../engine/debugger/debugger.cs | 135 +-------- .../engine/lang/interface/PSToken.cs | 4 - .../engine/parser/Parser.cs | 122 ++------- .../engine/parser/SemanticChecks.cs | 40 +-- .../engine/parser/ast.cs | 80 +----- .../engine/parser/token.cs | 28 +- .../engine/parser/tokenizer.cs | 22 +- .../engine/remoting/client/JobManager.cs | 76 +++-- .../remoting/client/PowerShellStreams.cs | 259 ------------------ .../remoting/commands/CustomShellCommands.cs | 141 +--------- .../remoting/commands/PSRemotingCmdlet.cs | 2 +- .../engine/runtime/ScriptBlockToPowerShell.cs | 14 +- .../help/AliasHelpInfo.cs | 2 +- .../help/CommandHelpProvider.cs | 2 +- .../help/HelpCommands.cs | 2 +- .../help/HelpRequest.cs | 2 +- .../help/HelpSystem.cs | 5 - .../help/ScriptCommandHelpProvider.cs | 3 +- .../resources/Credential.resx | 5 +- .../resources/ErrorPackage.resx | 8 - .../resources/ParserStrings.resx | 12 +- .../security/wldpNativeMethods.cs | 3 - 29 files changed, 117 insertions(+), 883 deletions(-) delete mode 100644 src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index 19c383e6cd2..c7e373a06f3 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -152,11 +152,6 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b if (_convertTypes[i] == typeof(ActionPreference)) { ActionPreference resultPreference = (ActionPreference)result; - - if (resultPreference == ActionPreference.Suspend) - { - throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference); - } } } } diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index 08500961cfc..d7b6b023330 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -286,8 +286,6 @@ public enum ActionPreference Inquire, /// Ignore the event completely (not even logging it to the target stream) Ignore, - /// Suspend the command for further diagnosis. Supported only for workflows. - Suspend, } #endregion ActionPreference diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 2119e513259..b637a1a139f 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -207,7 +207,7 @@ List ExecuteGetCommandCommand(bool useModulePrefix) } private static readonly HashSet s_keywordsToExcludeFromAddingAmpersand - = new HashSet(StringComparer.OrdinalIgnoreCase) { TokenKind.InlineScript.ToString(), TokenKind.Configuration.ToString() }; + = new HashSet(StringComparer.OrdinalIgnoreCase) { TokenKind.Configuration.ToString() }; internal static CompletionResult GetCommandNameCompletionResult(string name, object command, bool addAmpersandIfNecessary, string quote) { string syntax = name, listItem = name; diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index ff06791f3a7..2084cd33d2c 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -580,7 +580,7 @@ internal T GetEnumPreference(VariablePath preferenceVariablePath, T defaultPr if (val is ActionPreference) { ActionPreference preference = (ActionPreference)val; - if ((preference == ActionPreference.Ignore) || (preference == ActionPreference.Suspend)) + if (preference == ActionPreference.Ignore) { // Reset the variable value EngineSessionState.SetVariableValue(preferenceVariablePath.UserPath, defaultPref); diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 618a23b9f51..47bb39ad349 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -559,7 +559,6 @@ public static IEnumerator GetEnumerator(object obj) /// /// This method takes a an arbitrary object and wraps it in a PSDataCollection of PSObject. - /// This simplifies interacting with the PowerShell workflow activities. /// /// /// @@ -1771,7 +1770,7 @@ public static object ConvertPSObjectToType(PSObject valueToConvert, Type resultT } /// - /// Generic convertto that simplifies working with workflow. + /// Generic conversion method. /// /// The type of object to return /// diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index ed7468cf56b..6ea14e0f23f 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -3037,11 +3037,6 @@ internal ActionPreference WarningPreference set { - if (value == ActionPreference.Suspend) - { - throw PSTraceSource.NewNotSupportedException(ErrorPackage.SuspendActionPreferenceErrorActionOnly); - } - _warningPreference = value; IsWarningActionSet = true; } @@ -3207,11 +3202,6 @@ internal ActionPreference ErrorAction set { - if (value == ActionPreference.Suspend) - { - throw PSTraceSource.NewNotSupportedException(ErrorPackage.SuspendActionPreferenceSupportedOnlyOnWorkflow); - } - _errorAction = value; IsErrorActionSet = true; } @@ -3274,11 +3264,6 @@ internal ActionPreference InformationPreference set { - if (value == ActionPreference.Suspend) - { - throw PSTraceSource.NewNotSupportedException(ErrorPackage.SuspendActionPreferenceErrorActionOnly); - } - _informationPreference = value; IsInformationActionSet = true; } diff --git a/src/System.Management.Automation/engine/SessionStateStrings.cs b/src/System.Management.Automation/engine/SessionStateStrings.cs index 741ab5f47cb..92462b03e10 100644 --- a/src/System.Management.Automation/engine/SessionStateStrings.cs +++ b/src/System.Management.Automation/engine/SessionStateStrings.cs @@ -116,12 +116,12 @@ internal static class StringLiterals internal const string PowerShellDataFileExtension = ".psd1"; /// - /// The file extension (including the dot) of an workflow dependent assembly. + /// The file extension (including the dot) of a binary module. /// internal const string PowerShellILAssemblyExtension = ".dll"; /// - /// The file extension (including the dot) of an workflow dependent Ngen assembly. + /// The file extension (including the dot) of a binary module Ngen assembly. /// internal const string PowerShellNgenAssemblyExtension = ".ni.dll"; diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 9697715f283..58f4585031e 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -304,12 +304,12 @@ public enum DebugModes Default = 0x1, /// - /// PowerShell script debugging including workflow script. + /// PowerShell script debugging. /// LocalScript = 0x2, /// - /// PowerShell remote script and workflow debugging. + /// PowerShell remote script debugging. /// RemoteScript = 0x4 }; @@ -3319,18 +3319,6 @@ private DebuggerCommandResults ProcessCommandForActiveDebugger(PSCommand command _lastActiveDebuggerAction = dbgCommand.ResumeAction.Value; return new DebuggerCommandResults(dbgCommand.ResumeAction, true); } - - // If active debugger is Workflow debugger then process command here (for "list" and "help"). - if (activeDebugger.GetType().FullName.Equals("Microsoft.PowerShell.Workflow.PSWorkflowDebugger", StringComparison.OrdinalIgnoreCase)) - { - DebuggerCommand results = _commandProcessor.ProcessCommand(null, commandText, stopArgs.InvocationInfo, output); - - if ((results != null) && - results.ExecutedByDebugger) - { - return new DebuggerCommandResults(results.ResumeAction, true); - } - } } return activeDebugger.ProcessCommand(command, output); @@ -3531,39 +3519,6 @@ private void HandleMonitorRunningRSDebuggerStop(object sender, DebuggerStopEvent PSMonitorRunspaceType runspaceType = nestedDebugger.RunspaceType; - // If this is a workflow debugger then ensure that there is a current active - // debugger that is the associated job debugger for this inline script WF runspace. - if (runspaceType == PSMonitorRunspaceType.WorkflowInlineScript) - { - bool needToPushAssociatedWFDebugger = true; - if (_activeDebuggers.TryPeek(out activeDebugger)) - { - needToPushAssociatedWFDebugger = (activeDebugger.InstanceId != nestedDebugger.ParentDebuggerId); - if (needToPushAssociatedWFDebugger) - { - // Pop incorrect active debugger. - PopActiveDebugger(); - } - } - - if (needToPushAssociatedWFDebugger) - { - PSJobStartEventArgs wfJobArgs = null; - lock (_syncObject) - { - _runningJobs.TryGetValue(nestedDebugger.ParentDebuggerId, out wfJobArgs); - } - - if (wfJobArgs == null) - { - Diagnostics.Assert(false, "We should never get a WF job InlineScript debugger without an associated WF parent job."); - return; - } - - PushActiveDebugger(wfJobArgs.Debugger, _jobCallStackOffset); - } - } - // Fix up invocation info script extents for embedded nested debuggers where the script source is // from the parent. args.InvocationInfo = nestedDebugger.FixupInvocationInfo(args.InvocationInfo); @@ -4225,7 +4180,7 @@ protected virtual bool HandleListCommand(PSDataCollection output) /// Attempts to fix up the debugger stop invocation information so that /// the correct stack and source can be displayed in the debugger, for /// cases where the debugged runspace is called inside a parent sccript, - /// such as with Workflow InlineScripts and script Invoke-Command cases. + /// such as with script Invoke-Command cases. /// /// /// InvocationInfo. @@ -4391,8 +4346,7 @@ private void RestoreRemoteOutput(object runningCmd) /// /// Wrapper class for runspace debugger where the runspace is being used in an - /// embedded scenario such as Workflow InlineScript or Invoke-Command command - /// inside script. + /// embedded scenario such as Invoke-Command command inside script. /// internal sealed class EmbeddedRunspaceDebugger : NestedRunspaceDebugger { @@ -4501,7 +4455,7 @@ protected override bool HandleListCommand(PSDataCollection output) /// Attempts to fix up the debugger stop invocation information so that /// the correct stack and source can be displayed in the debugger, for /// cases where the debugged runspace is called inside a parent sccript, - /// such as with Workflow InlineScripts and script Invoke-Command cases. + /// such as with script Invoke-Command cases. /// /// Invocation information from debugger stop. /// InvocationInfo. @@ -5346,65 +5300,6 @@ namespace System.Management.Automation.Internal [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Needed Internal use only")] public static class DebuggerUtils { - /// - /// Set-DebuggerVariable function. - /// - public const string SetVariableFunction = @"function Set-DebuggerVariable - { - [CmdletBinding()] - param( - [Parameter(Position=0)] - [HashTable] - $Variables - ) - - foreach($key in $Variables.Keys) - { - microsoft.powershell.utility\set-variable -Name $key -Value $Variables[$key] -Scope global - } - - Set-StrictMode -Off - }"; - - /// - /// Remove-DebuggerVariable function. - /// - public const string RemoveVariableFunction = @"function Remove-DebuggerVariable - { - [CmdletBinding()] - param( - [Parameter(Position=0)] - [string[]] - $Name - ) - - foreach ($item in $Name) - { - microsoft.powershell.utility\remove-variable -name $item -scope global - } - - Set-StrictMode -Off - }"; - - /// - /// Get-PSCallStack override function. - /// - public const string GetPSCallStackOverrideFunction = @"function Get-PSCallStack - { - [CmdletBinding()] - param() - - if ($null -ne $PSWorkflowDebugger) - { - foreach ($frame in $PSWorkflowDebugger.GetCallStack()) - { - Write-Output $frame - } - } - - Set-StrictMode -Off - }"; - internal const string SetDebugModeFunctionName = "__Set-PSDebugMode"; internal const string SetDebuggerActionFunctionName = "__Set-PSDebuggerAction"; internal const string GetDebuggerStopArgsFunctionName = "__Get-PSDebuggerStopArgs"; @@ -5439,21 +5334,6 @@ public static bool ShouldAddCommandToHistory(string command) } } - /// - /// Helper method to return an enumeration of workflow debugger - /// functions. - /// - /// - public static IEnumerable GetWorkflowDebuggerFunctions() - { - return new Collection() - { - SetVariableFunction, - RemoveVariableFunction, - GetPSCallStackOverrideFunction - }; - } - /// /// Start monitoring a runspace on the target debugger. /// @@ -5512,11 +5392,6 @@ public enum PSMonitorRunspaceType /// Runspace from remote Invoke-Command script. /// InvokeCommand, - - /// - /// Runspace from Workflow activity inline script. - /// - WorkflowInlineScript } /// diff --git a/src/System.Management.Automation/engine/lang/interface/PSToken.cs b/src/System.Management.Automation/engine/lang/interface/PSToken.cs index 712dc35ec54..49514187408 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSToken.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSToken.cs @@ -283,10 +283,6 @@ public static PSTokenType GetPSTokenType(Token token) /* Using */ PSTokenType.Keyword, /* Var */ PSTokenType.Keyword, /* While */ PSTokenType.Keyword, - /* Workflow */ PSTokenType.Keyword, - /* Parallel */ PSTokenType.Keyword, - /* Sequence */ PSTokenType.Keyword, - /* InlineScript */ PSTokenType.Keyword, /* Configuration */ PSTokenType.Keyword, /* DynamicKeyword */ PSTokenType.Keyword, /* Public */ PSTokenType.Keyword, diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index b48637cd108..f551bc936f2 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -2013,7 +2013,6 @@ private StatementAst StatementRule() break; case TokenKind.Function: case TokenKind.Filter: - case TokenKind.Workflow: statement = FunctionDeclarationRule(token); break; case TokenKind.Return: @@ -2040,10 +2039,6 @@ private StatementAst StatementRule() case TokenKind.Data: statement = DataStatementRule(token); break; - case TokenKind.Parallel: - case TokenKind.Sequence: - statement = BlockStatementRule(token); - break; case TokenKind.Configuration: statement = ConfigurationStatementRule(attributes != null ? attributes.OfType() : null, token); break; @@ -2320,45 +2315,6 @@ private StatementAst BlockStatementRule(Token kindToken) return new BlockStatementAst(ExtentOf(kindToken, body), kindToken, body); } - /// - /// Handle the InlineScript syntax in the script workflow. - /// - /// - /// - /// - /// true -- InlineScript parsing successful - /// false -- InlineScript parsing unsuccessful - /// - private bool InlineScriptRule(Token inlineScriptToken, List elements) - { - // G Command - // G InlineScript scriptblock-expression - - Diagnostics.Assert(elements != null && elements.Count == 0, "The CommandElement list should be empty"); - var commandName = new StringConstantExpressionAst(inlineScriptToken.Extent, inlineScriptToken.Text, StringConstantType.BareWord); - inlineScriptToken.TokenFlags |= TokenFlags.CommandName; - elements.Add(commandName); - - SkipNewlines(); - Token lCurly = NextToken(); - - if (lCurly.Kind != TokenKind.LCurly) - { - // ErrorRecovery: If there is no opening curly, assume it hasn't been entered yet and don't consume anything. - - UngetToken(lCurly); - ReportIncompleteInput(After(inlineScriptToken), - nameof(ParserStrings.MissingStatementAfterKeyword), - ParserStrings.MissingStatementAfterKeyword, - inlineScriptToken.Text); - return false; - } - - var expr = ScriptBlockExpressionRule(lCurly); - elements.Add(expr); - return true; - } - private StatementAst IfStatementRule(Token ifToken) { // G if-statement: @@ -2589,15 +2545,6 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke specifiedFlags.Add("casesensitive", new Tuple(switchParameterToken, null)); } } - else if (IsSpecificParameter(switchParameterToken, "parallel")) - { - flags |= SwitchFlags.Parallel; - - if (!specifiedFlags.ContainsKey("parallel")) - { - specifiedFlags.Add("parallel", new Tuple(switchParameterToken, null)); - } - } else if (IsSpecificParameter(switchParameterToken, "file")) { flags |= SwitchFlags.File; @@ -5222,7 +5169,7 @@ private StatementAst MethodDeclarationRule(Token functionNameToken, string class SetTokenizerMode(TokenizerMode.Command); ScriptBlockAst scriptBlock = ScriptBlockRule(lCurly, false, baseCtorCallStatement); var result = new FunctionDefinitionAst(ExtentOf(functionNameToken, scriptBlock), - /*isFilter:*/false, /*isWorkflow:*/false, functionNameToken, parameters, scriptBlock); + /*isFilter:*/false, functionNameToken, parameters, scriptBlock); return result; } @@ -5237,7 +5184,6 @@ private StatementAst FunctionDeclarationRule(Token functionToken) // G function-statement: // G 'function' new-lines:opt function-name function-parameter-declaration:opt '{' script-block '}' // G 'filter' new-lines:opt function-name function-parameter-declaration:opt '{' script-block '}' - // G 'workflow' new-lines:opt function-name function-parameter-declaration:opt '{' script-block '}' // G // G function-name: // G command-argument @@ -5309,26 +5255,15 @@ private StatementAst FunctionDeclarationRule(Token functionToken) } bool isFilter = functionToken.Kind == TokenKind.Filter; - bool isWorkflow = functionToken.Kind == TokenKind.Workflow; - - bool oldTokenizerWorkflowContext = _tokenizer.InWorkflowContext; - try - { - _tokenizer.InWorkflowContext = isWorkflow; - ScriptBlockAst scriptBlock = ScriptBlockRule(lCurly, isFilter); - var functionName = (functionNameToken.Kind == TokenKind.Generic) - ? ((StringToken)functionNameToken).Value - : functionNameToken.Text; + ScriptBlockAst scriptBlock = ScriptBlockRule(lCurly, isFilter); + var functionName = (functionNameToken.Kind == TokenKind.Generic) + ? ((StringToken)functionNameToken).Value + : functionNameToken.Text; - FunctionDefinitionAst result = new FunctionDefinitionAst(ExtentOf(functionToken, scriptBlock), - isFilter, isWorkflow, functionNameToken, parameters, scriptBlock); - return result; - } - finally - { - _tokenizer.InWorkflowContext = oldTokenizerWorkflowContext; - } + FunctionDefinitionAst result = new FunctionDefinitionAst(ExtentOf(functionToken, scriptBlock), + isFilter, functionNameToken, parameters, scriptBlock); + return result; } private List FunctionParameterDeclarationRule(out IScriptExtent endErrorStatement, out Token rParen) @@ -6344,42 +6279,31 @@ internal Ast CommandRule(bool forDynamicKeyword) break; default: - if (token.Kind == TokenKind.InlineScript && context == CommandArgumentContext.CommandName) - { - scanning = InlineScriptRule(token, elements); - Diagnostics.Assert(elements.Count >= 1, "We should at least have the command name: inlinescript"); - endExtent = elements.Last().Extent; + var ast = GetCommandArgument(context, token); - if (!scanning) { continue; } - } - else + // If this is the special verbatim argument syntax, look for the next element + StringToken argumentToken = token as StringToken; + if ((argumentToken != null) && string.Equals(argumentToken.Value, VERBATIM_ARGUMENT, StringComparison.OrdinalIgnoreCase)) { - var ast = GetCommandArgument(context, token); + elements.Add(ast); + endExtent = ast.Extent; - // If this is the special verbatim argument syntax, look for the next element - StringToken argumentToken = token as StringToken; - if ((argumentToken != null) && string.Equals(argumentToken.Value, VERBATIM_ARGUMENT, StringComparison.OrdinalIgnoreCase)) + var verbatimToken = GetVerbatimCommandArgumentToken(); + if (verbatimToken != null) { + foundVerbatimArgument = true; + scanning = false; + ast = new StringConstantExpressionAst(verbatimToken.Extent, verbatimToken.Value, StringConstantType.BareWord); elements.Add(ast); endExtent = ast.Extent; - - var verbatimToken = GetVerbatimCommandArgumentToken(); - if (verbatimToken != null) - { - foundVerbatimArgument = true; - scanning = false; - ast = new StringConstantExpressionAst(verbatimToken.Extent, verbatimToken.Value, StringConstantType.BareWord); - elements.Add(ast); - endExtent = ast.Extent; - } - - break; } - endExtent = ast.Extent; - elements.Add(ast); + break; } + endExtent = ast.Extent; + elements.Add(ast); + break; } diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 54c211e6043..9e158e9294e 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -443,30 +443,11 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun CheckForDuplicateParameters(functionDefinitionAst.Parameters); } - if (functionDefinitionAst.IsWorkflow) - { - _parser.ReportError(functionDefinitionAst.Extent, - nameof(ParserStrings.WorkflowNotSupportedInPowerShellCore), - ParserStrings.WorkflowNotSupportedInPowerShellCore); - } - return AstVisitAction.Continue; } public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) { - // Parallel flag not allowed - if ((switchStatementAst.Flags & SwitchFlags.Parallel) == SwitchFlags.Parallel) - { - bool reportError = !switchStatementAst.IsInWorkflow(); - if (reportError) - { - _parser.ReportError(switchStatementAst.Extent, - nameof(ParserStrings.ParallelNotSupported), - ParserStrings.ParallelNotSupported); - } - } - return AstVisitAction.Continue; } @@ -491,18 +472,6 @@ public override AstVisitAction VisitDataStatement(DataStatementAst dataStatement public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { - // Parallel flag not allowed - if ((forEachStatementAst.Flags & ForEachFlags.Parallel) == ForEachFlags.Parallel) - { - bool reportError = !forEachStatementAst.IsInWorkflow(); - if (reportError) - { - _parser.ReportError(forEachStatementAst.Extent, - nameof(ParserStrings.ParallelNotSupported), - ParserStrings.ParallelNotSupported); - } - } - // Throttle limit must be combined with Parallel flag if ((forEachStatementAst.ThrottleLimit != null) && ((forEachStatementAst.Flags & ForEachFlags.Parallel) != ForEachFlags.Parallel)) @@ -1134,11 +1103,6 @@ public override AstVisitAction VisitAttributedExpression(AttributedExpressionAst public override AstVisitAction VisitBlockStatement(BlockStatementAst blockStatementAst) { - if (blockStatementAst.IsInWorkflow()) - { - return AstVisitAction.Continue; - } - _parser.ReportError(blockStatementAst.Kind.Extent, nameof(ParserStrings.UnexpectedKeyword), ParserStrings.UnexpectedKeyword, @@ -2354,8 +2318,8 @@ public override AstVisitAction VisitBlockStatement(BlockStatementAst blockStatem { // Keyword blocks are not allowed ReportError(blockStatementAst, - nameof(ParserStrings.ParallelAndSequenceBlockNotSupportedInDataSection), - ParserStrings.ParallelAndSequenceBlockNotSupportedInDataSection); + nameof(ParserStrings.BlockStatementNotSupportedInDataSection), + ParserStrings.BlockStatementNotSupportedInDataSection); return AstVisitAction.Continue; } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 434b5a6b5e6..999d8604db3 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -288,42 +288,6 @@ internal void ClearParent() internal static PSTypeName[] EmptyPSTypeNameArray = Array.Empty(); - internal bool IsInWorkflow() - { - // Scan up the AST's parents, looking for a script block that is either - // a workflow, or has a job definition attribute. - // Stop scanning when we encounter a FunctionDefinitionAst - Ast current = this; - bool stopScanning = false; - - while (current != null && !stopScanning) - { - ScriptBlockAst scriptBlock = current as ScriptBlockAst; - if (scriptBlock != null) - { - // See if this uses the workflow keyword - FunctionDefinitionAst functionDefinition = scriptBlock.Parent as FunctionDefinitionAst; - if ((functionDefinition != null)) - { - stopScanning = true; - if (functionDefinition.IsWorkflow) { return true; } - } - } - - CommandAst commandAst = current as CommandAst; - if (commandAst != null && - string.Equals(TokenKind.InlineScript.Text(), commandAst.GetCommandName(), StringComparison.OrdinalIgnoreCase) && - this != commandAst) - { - return false; - } - - current = current.Parent; - } - - return false; - } - internal bool HasSuspiciousContent { get; set; } #region Search Ancestor Ast @@ -894,7 +858,7 @@ public ScriptBlockAst(IScriptExtent extent, /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// /// If or is null. /// @@ -913,7 +877,7 @@ public ScriptBlockAst(IScriptExtent extent, List usingStateme /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// /// If or is null. /// @@ -932,7 +896,7 @@ public ScriptBlockAst(IScriptExtent extent, ParamBlockAst paramBlock, StatementB /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// True if the script block is a configuration. /// /// If or is null. @@ -953,7 +917,7 @@ public ScriptBlockAst(IScriptExtent extent, ParamBlockAst paramBlock, StatementB /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// True if the script block is a configuration. /// /// If or is null. @@ -974,7 +938,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable using /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// True if the script block is a configuration. /// /// If or is null. @@ -996,7 +960,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable attributes /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// True if the script block is a configuration. /// /// If or is null. @@ -3562,7 +3526,6 @@ public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider /// The extent of the function definition, starting with the function or filter keyword, ending at the closing curly. /// /// True if the filter keyword was used. - /// True if the workflow keyword was used. /// The name of the function. /// /// The parameters specified after the function name. This does not include parameters specified with a param statement. @@ -3574,7 +3537,6 @@ public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider /// public FunctionDefinitionAst(IScriptExtent extent, bool isFilter, - bool isWorkflow, string name, IEnumerable parameters, ScriptBlockAst body) @@ -3590,13 +3552,7 @@ public FunctionDefinitionAst(IScriptExtent extent, throw PSTraceSource.NewArgumentNullException("body"); } - if (isFilter && isWorkflow) - { - throw PSTraceSource.NewArgumentException("isFilter"); - } - this.IsFilter = isFilter; - this.IsWorkflow = isWorkflow; this.Name = name; if (parameters != null && parameters.Any()) @@ -3611,13 +3567,11 @@ public FunctionDefinitionAst(IScriptExtent extent, internal FunctionDefinitionAst(IScriptExtent extent, bool isFilter, - bool isWorkflow, Token functionNameToken, IEnumerable parameters, ScriptBlockAst body) : this(extent, isFilter, - isWorkflow, (functionNameToken.Kind == TokenKind.Generic) ? ((StringToken)functionNameToken).Value : functionNameToken.Text, parameters, body) @@ -3630,11 +3584,6 @@ internal FunctionDefinitionAst(IScriptExtent extent, /// public bool IsFilter { get; private set; } - /// - /// If true, the workflow keyword was used. - /// - public bool IsWorkflow { get; private set; } - /// /// The name of the function or filter. This property is never null or empty. /// @@ -3707,7 +3656,7 @@ public override Ast Copy() var newParameters = CopyElements(this.Parameters); var newBody = CopyElement(this.Body); - return new FunctionDefinitionAst(this.Extent, this.IsFilter, this.IsWorkflow, this.Name, newParameters, newBody) { NameExtent = this.NameExtent }; + return new FunctionDefinitionAst(this.Extent, this.IsFilter, this.Name, newParameters, newBody) { NameExtent = this.NameExtent }; } internal string GetParamTextFromParameterList(Tuple, string> usingVariablesTuple = null) @@ -4589,11 +4538,6 @@ public enum SwitchFlags /// CaseSensitive = 0x10, - /// - /// The -parallel flag. - /// - Parallel = 0x20, - // If any flags are added that influence evaluation of switch elements, // then the caching strategy in SwitchClauseEvalBinder needs to be updated, // and possibly its _binderCache. @@ -7304,8 +7248,8 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } /// - /// The ast that represents a scriptblock with a keyword name. This is normally allowed only for script workflow. - /// e.g. parallel { ... } or sequence { ... }. + /// The ast that represents a scriptblock with a keyword name. + /// e.g. The parallel and sequence block statements that were deprecated along with workflow in PowerShell 7. /// public class BlockStatementAst : StatementAst { @@ -7323,7 +7267,7 @@ public BlockStatementAst(IScriptExtent extent, Token kind, StatementBlockAst bod throw PSTraceSource.NewArgumentNullException(kind == null ? "kind" : "body"); } - if (kind.Kind != TokenKind.Sequence && kind.Kind != TokenKind.Parallel) + if (!tokenKindsThatSupportBlockStatements.Contains(kind.Kind)) { throw PSTraceSource.NewArgumentException("kind"); } @@ -7333,6 +7277,10 @@ public BlockStatementAst(IScriptExtent extent, Token kind, StatementBlockAst bod SetParent(body); } + // This should remain empty until block statements are needed in PowerShell. The only tokens that supported + // them in the past were deprecated along with workflow in PowerShell 7. + private static SortedSet tokenKindsThatSupportBlockStatements = new SortedSet {}; + /// /// The scriptblockexpression that has a keyword applied to it. This property is nerver null. /// diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index def6b8d0dc1..50d8d92823f 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -516,17 +516,7 @@ public enum TokenKind /// The 'while' keyword. While = 150, - /// The 'workflow' keyword. - Workflow = 151, - - /// The 'parallel' keyword. - Parallel = 152, - - /// The 'sequence' keyword. - Sequence = 153, - - /// The 'InlineScript' keyword - InlineScript = 154, + // Keywords 151-154 were part of the workflow functionality that was removed in PowerShell 7. /// The "configuration" keyword Configuration = 155, @@ -903,10 +893,6 @@ public static class TokenTraits /* Using */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* Var */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* While */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* Workflow */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* Parallel */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* Sequence */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* InlineScript */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* Configuration */ TokenFlags.Keyword, /* */ TokenFlags.Keyword, /* Public */ TokenFlags.Keyword, @@ -1101,10 +1087,6 @@ public static class TokenTraits /* Using */ "using", /* Var */ "var", /* While */ "while", - /* Workflow */ "workflow", - /* Parallel */ "parallel", - /* Sequence */ "sequence", - /* InlineScript */ "inlinescript", /* Configuration */ "configuration", /* */ "", /* Public */ "public", @@ -1133,10 +1115,10 @@ static TokenTraits() // Some random assertions to make sure the enum and the traits are in sync Diagnostics.Assert(GetTraits(TokenKind.Begin) == (TokenFlags.Keyword | TokenFlags.ScriptBlockBlockName), "Table out of sync with enum - flags Begin"); - Diagnostics.Assert(GetTraits(TokenKind.Workflow) == (TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes), - "Table out of sync with enum - flags Workflow"); - Diagnostics.Assert(GetTraits(TokenKind.Sequence) == (TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes), - "Table out of sync with enum - flags Sequence"); + Diagnostics.Assert(GetTraits(TokenKind.While) == (TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes), + "Table out of sync with enum - flags While"); + Diagnostics.Assert(GetTraits(TokenKind.Configuration) == TokenFlags.Keyword, + "Table out of sync with enum - flags Configuration"); Diagnostics.Assert(GetTraits(TokenKind.Shr) == (TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison | TokenFlags.CanConstantFold), "Table out of sync with enum - flags Shr"); Diagnostics.Assert(s_tokenText[(int)TokenKind.Shr].Equals("-shr", StringComparison.OrdinalIgnoreCase), diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 328417a8eae..6158e242c87 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -624,11 +624,10 @@ private static readonly Dictionary s_operatorTable /*6*/ "throw", "begin", "process", "end", /*6*/ /*7*/ "dynamicparam", "function", "filter", "param", /*7*/ /*8*/ "class", "define", "var", "using", /*8*/ - /*9*/ "workflow", "parallel", "sequence", "inlinescript", /*9*/ - /*A*/ "configuration", "public", "private", "static", /*A*/ - /*B*/ "interface", "enum", "namespace", "module", /*B*/ - /*C*/ "type", "assembly", "command", "hidden", /*C*/ - /*D*/ "base", /*D*/ + /*9*/ "configuration", "public", "private", "static", /*9*/ + /*A*/ "interface", "enum", "namespace", "module", /*A*/ + /*B*/ "type", "assembly", "command", "hidden", /*B*/ + /*C*/ "base", /*C*/ }; private static readonly TokenKind[] s_keywordTokenKind = new TokenKind[] { @@ -640,11 +639,10 @@ private static readonly Dictionary s_operatorTable /*6*/ TokenKind.Throw, TokenKind.Begin, TokenKind.Process, TokenKind.End, /*6*/ /*7*/ TokenKind.Dynamicparam, TokenKind.Function, TokenKind.Filter, TokenKind.Param, /*7*/ /*8*/ TokenKind.Class, TokenKind.Define, TokenKind.Var, TokenKind.Using, /*8*/ - /*9*/ TokenKind.Workflow, TokenKind.Parallel, TokenKind.Sequence, TokenKind.InlineScript, /*9*/ - /*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/ - /*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*B*/ - /*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/ - /*D*/ TokenKind.Base, /*D*/ + /*9*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*9*/ + /*A*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*A*/ + /*B*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*B*/ + /*C*/ TokenKind.Base, /*C*/ }; internal static readonly string[] _operatorText = new string[] { @@ -722,7 +720,6 @@ internal Tokenizer(Parser parser) internal TokenizerMode Mode { get; set; } internal bool AllowSignedNumbers { get; set; } internal bool WantSimpleName { get; set; } - internal bool InWorkflowContext { get; set; } internal List TokenList { get; set; } internal Token FirstToken { get; private set; } @@ -4392,8 +4389,7 @@ private Token ScanIdentifier(char firstChar) sb = null; if (s_keywordTable.TryGetValue(ident, out tokenKind)) { - if (tokenKind != TokenKind.InlineScript || InWorkflowContext) - return NewToken(tokenKind); + return NewToken(tokenKind); } if (DynamicKeyword.ContainsKeyword(ident) && !DynamicKeyword.IsHiddenKeyword(ident)) diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index 8006ed1dbdb..9d1073c8006 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -81,51 +81,43 @@ internal void RegisterJobSourceAdapter(Type jobSourceAdapterType) Dbg.Assert(jobSourceAdapterType != null, "JobSourceAdapterType should never be called with null value."); object instance = null; - if (jobSourceAdapterType.FullName != null && jobSourceAdapterType.FullName.EndsWith("WorkflowJobSourceAdapter", StringComparison.OrdinalIgnoreCase)) + ConstructorInfo constructor = jobSourceAdapterType.GetConstructor(Type.EmptyTypes); + if (!constructor.IsPublic) { - MethodInfo method = jobSourceAdapterType.GetMethod("GetInstance"); - instance = method.Invoke(null, null); + string message = string.Format(CultureInfo.CurrentCulture, + RemotingErrorIdStrings.JobManagerRegistrationConstructorError, + jobSourceAdapterType.FullName); + throw new InvalidOperationException(message); } - else - { - ConstructorInfo constructor = jobSourceAdapterType.GetConstructor(Type.EmptyTypes); - if (!constructor.IsPublic) - { - string message = string.Format(CultureInfo.CurrentCulture, - RemotingErrorIdStrings.JobManagerRegistrationConstructorError, - jobSourceAdapterType.FullName); - throw new InvalidOperationException(message); - } - try - { - instance = constructor.Invoke(null); - } - catch (MemberAccessException exception) - { - _tracer.TraceException(exception); - throw; - } - catch (TargetInvocationException exception) - { - _tracer.TraceException(exception); - throw; - } - catch (TargetParameterCountException exception) - { - _tracer.TraceException(exception); - throw; - } - catch (NotSupportedException exception) - { - _tracer.TraceException(exception); - throw; - } - catch (SecurityException exception) - { - _tracer.TraceException(exception); - throw; - } + try + { + instance = constructor.Invoke(null); + } + catch (MemberAccessException exception) + { + _tracer.TraceException(exception); + throw; + } + catch (TargetInvocationException exception) + { + _tracer.TraceException(exception); + throw; + } + catch (TargetParameterCountException exception) + { + _tracer.TraceException(exception); + throw; + } + catch (NotSupportedException exception) + { + _tracer.TraceException(exception); + throw; + } + catch (SecurityException exception) + { + _tracer.TraceException(exception); + throw; } if (instance != null) diff --git a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs b/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs deleted file mode 100644 index 038a8fc1763..00000000000 --- a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -namespace System.Management.Automation -{ - /// - /// Define all the output streams and one input stream for a workflow. - /// - public sealed class PowerShellStreams : IDisposable - { - /// - /// Input stream for incoming objects. - /// - private PSDataCollection _inputStream; - - /// - /// Output stream for returned objects. - /// - private PSDataCollection _outputStream; - - /// - /// Error stream for error messages. - /// - private PSDataCollection _errorStream; - - /// - /// Warning stream for warning messages. - /// - private PSDataCollection _warningStream; - - /// - /// Progress stream for progress messages. - /// - private PSDataCollection _progressStream; - - /// - /// Verbose stream for verbose messages. - /// - private PSDataCollection _verboseStream; - - /// - /// Debug stream for debug messages. - /// - private PSDataCollection _debugStream; - - /// - /// Information stream for Information messages. - /// - private PSDataCollection _informationStream; - - /// - /// If the object is already disposed or not. - /// - private bool _disposed; - - /// - /// Private object for thread-safe execution. - /// - private readonly object _syncLock = new object(); - - /// - /// Default constructor. - /// - public PowerShellStreams() - { - _inputStream = null; - _outputStream = null; - _errorStream = null; - _warningStream = null; - _progressStream = null; - _verboseStream = null; - _debugStream = null; - _informationStream = null; - - _disposed = false; - } - - /// - /// Default constructor. - /// - public PowerShellStreams(PSDataCollection pipelineInput) - { - // Populate the input collection if there is any... - _inputStream = pipelineInput ?? new PSDataCollection(); - - _inputStream.Complete(); - - _outputStream = new PSDataCollection(); - _errorStream = new PSDataCollection(); - _warningStream = new PSDataCollection(); - _progressStream = new PSDataCollection(); - _verboseStream = new PSDataCollection(); - _debugStream = new PSDataCollection(); - _informationStream = new PSDataCollection(); - - _disposed = false; - } - - /// - /// Dispose implementation. - /// - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Protected virtual implementation of Dispose. - /// - /// - private void Dispose(bool disposing) - { - if (_disposed) - return; - - lock (_syncLock) - { - if (!_disposed) - { - if (disposing) - { - _inputStream.Dispose(); - _outputStream.Dispose(); - _errorStream.Dispose(); - _warningStream.Dispose(); - _progressStream.Dispose(); - _verboseStream.Dispose(); - _debugStream.Dispose(); - _informationStream.Dispose(); - - _inputStream = null; - _outputStream = null; - _errorStream = null; - _warningStream = null; - _progressStream = null; - _verboseStream = null; - _debugStream = null; - _informationStream = null; - } - - _disposed = true; - } - } - } - - /// - /// Gets input stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection InputStream - { - get { return _inputStream; } - - set { _inputStream = value; } - } - - /// - /// Gets output stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection OutputStream - { - get { return _outputStream; } - - set { _outputStream = value; } - } - - /// - /// Gets error stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection ErrorStream - { - get { return _errorStream; } - - set { _errorStream = value; } - } - - /// - /// Gets warning stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection WarningStream - { - get { return _warningStream; } - - set { _warningStream = value; } - } - - /// - /// Gets progress stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection ProgressStream - { - get { return _progressStream; } - - set { _progressStream = value; } - } - - /// - /// Gets verbose stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection VerboseStream - { - get { return _verboseStream; } - - set { _verboseStream = value; } - } - - /// - /// Get debug stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection DebugStream - { - get { return _debugStream; } - - set { _debugStream = value; } - } - - /// - /// Gets Information stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection InformationStream - { - get { return _informationStream; } - - set { _informationStream = value; } - } - - /// - /// Marking all the streams as completed so that no further data can be added and - /// jobs will know that there is no more data coming in. - /// - public void CloseAll() - { - if (_disposed == false) - { - lock (_syncLock) - { - if (_disposed == false) - { - _outputStream.Complete(); - _errorStream.Complete(); - _warningStream.Complete(); - _progressStream.Complete(); - _verboseStream.Complete(); - _debugStream.Complete(); - _informationStream.Complete(); - } - } - } - } - } -} diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 986e2ae1eb3..e1509ec2661 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -2719,28 +2719,6 @@ function ExtractPluginProperties([string]$pluginDir, $objectToWriteTo) Get-Details $pluginDir $h - # Workflow is not supported in PowerShell 6+. Attempting to load the - # assembly results in a FileNotFoundException. - if (![System.Management.Automation.Platform]::IsCoreCLR -AND - $h[""AssemblyName""] -eq ""Microsoft.PowerShell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"") {{ - - $serviceCore = [Reflection.Assembly]::Load(""Microsoft.Powershell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"") - - if ($null -ne $serviceCore) {{ - - $ci = new-Object system.management.automation.cmdletinfo ""New-PSWorkflowExecutionOptions"", ([Microsoft.PowerShell.Commands.NewPSWorkflowExecutionOptionCommand]) - $wf = [powershell]::Create(""currentrunspace"").AddCommand($ci).Invoke() - - if($null -ne $wf -and $wf.Count -ne 0) {{ - $wf = $wf[0] - - foreach ($o in $wf.GetType().GetProperties()) {{ - $h[$o.Name] = $o.GetValue($wf, $null) - }} - }} - }} - }} - if (test-path -LiteralPath $pluginDir\InitializationParameters\SessionConfigurationData) {{ $xscd = [xml](Unescape-xml (Unescape-xml (get-item -LiteralPath $pluginDir\InitializationParameters\SessionConfigurationData).Value)) @@ -4730,12 +4708,12 @@ function Copy-PluginToEndpoint $resolvedPluginInstallPath = Resolve-Path $pluginInstallPath }} - if (!(Test-Path $resolvedPluginInstallPath\{5})) + if (!(Test-Path $resolvedPluginInstallPath\{4})) {{ - Copy-Item -Path $PSHOME\{5} -Destination $resolvedPluginInstallPath -Force -ErrorAction Stop - if (!(Test-Path $resolvedPluginInstallPath\{5})) + Copy-Item -Path $PSHOME\{4} -Destination $resolvedPluginInstallPath -Force -ErrorAction Stop + if (!(Test-Path $resolvedPluginInstallPath\{4})) {{ - Write-Error ($errorMsgUnableToInstallPlugin -f ""{5}"", $resolvedPluginInstallPath) + Write-Error ($errorMsgUnableToInstallPlugin -f ""{4}"", $resolvedPluginInstallPath) return $null }} }} @@ -4775,7 +4753,7 @@ function Register-Endpoint $null = Register-PSSessionConfiguration -Name $configurationName -force -ErrorAction Stop set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\$configurationName\Quotas\MaxShellsPerUser -value ""25"" -confirm:$false - set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\$configurationName\Quotas\MaxIdleTimeoutms -value {4} -confirm:$false + set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\$configurationName\Quotas\MaxIdleTimeoutms -value {3} -confirm:$false restart-service winrm -confirm:$false }} @@ -4862,65 +4840,6 @@ function Enable-PSRemoting Register-EndpointIfNotPresent -Name (""PowerShell."" + $powershellVersionMajor) $Force $queryForRegisterDefault $captionForRegisterDefault - # PowerShell Workflow and WOW are not supported for PowerShell 6+ - if (![System.Management.Automation.Platform]::IsCoreCLR) - {{ - # Check Microsoft.PowerShell.Workflow endpoint - $errorCount = $error.Count - $endPoint = Get-PSSessionConfiguration {0}.workflow -Force:$Force -ErrorAction silentlycontinue 2>&1 - $newErrorCount = $error.Count - - # remove the 'No Session Configuration matches criteria' errors - for ($index = 0; $index -lt ($newErrorCount - $errorCount); $index ++) - {{ - $error.RemoveAt(0) - }} - - if (!$endpoint) - {{ - $qMessage = $queryForRegisterDefault -f ""Microsoft.PowerShell.Workflow"",""Register-PSSessionConfiguration Microsoft.PowerShell.Workflow -force"" - if ($force -or $pscmdlet.ShouldProcess($qMessage, $captionForRegisterDefault)) {{ - $tempxmlfile = [io.path]::Gettempfilename() - ""{1}"" | out-file -force -filepath $tempxmlfile -confirm:$false - $null = winrm create winrm/config/plugin?Name=Microsoft.PowerShell.Workflow -file:$tempxmlfile - remove-item -path $tempxmlfile -force -confirm:$false - restart-service winrm -confirm:$false - }} - }} - - $pa = $env:PROCESSOR_ARCHITECTURE - if ($pa -eq ""x86"") - {{ - # on 64-bit platforms, wow64 bit process has the correct architecture - # available in processor_architew6432 variable - $pa = $env:PROCESSOR_ARCHITEW6432 - }} - - if ((($pa -eq ""amd64"")) -and (test-path $env:windir\syswow64\pwrshplugin.dll)) - {{ - # Check availability of WOW64 endpoint. Register if not available. - $errorCount = $error.Count - $endPoint = Get-PSSessionConfiguration {0}32 -Force:$Force -ErrorAction silentlycontinue 2>&1 - $newErrorCount = $error.Count - - # remove the 'No Session Configuration matches criteria' errors - for ($index = 0; $index -lt ($newErrorCount - $errorCount); $index ++) - {{ - $error.RemoveAt(0) - }} - - $qMessage = $queryForRegisterDefault -f ""{0}32"",""Register-PSSessionConfiguration {0}32 -processorarchitecture x86 -force"" - if ((!$endpoint) -and - ($force -or $pscmdlet.ShouldProcess($qMessage, $captionForRegisterDefault))) - {{ - $null = Register-PSSessionConfiguration {0}32 -processorarchitecture x86 -force - set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\{0}32\Quotas\MaxShellsPerUser -value ""25"" -confirm:$false - set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\{0}32\Quotas\MaxIdleTimeoutms -value {4} -confirm:$false - restart-service winrm -confirm:$false - }} - }} - }} - # remove the 'network deny all' tag Get-PSSessionConfiguration -Force:$Force | ForEach-Object {{ $sddl = $null @@ -4961,12 +4880,12 @@ function Enable-PSRemoting # Remote Management Users, Win8+ only if ([System.Environment]::OSVersion.Version -ge ""6.2.0.0"") {{ - $rmSidId = new-object system.security.principal.securityidentifier ""{2}"" + $rmSidId = new-object system.security.principal.securityidentifier ""{1}"" $sd.DiscretionaryAcl.AddAccess('Allow', $rmSidId, 268435456, 'none', 'none') }} # Interactive Users - $iaSidId = new-object system.security.principal.securityidentifier ""{3}"" + $iaSidId = new-object system.security.principal.securityidentifier ""{2}"" $sd.DiscretionaryAcl.AddAccess('Allow', $iaSidId, 268435456, 'none', 'none') }} @@ -4988,44 +4907,6 @@ function Enable-PSRemoting }} # end of Enable-PSRemoting Enable-PSRemoting -force $args[0] -queryForRegisterDefault $args[1] -captionForRegisterDefault $args[2] -queryForSet $args[3] -captionForSet $args[4] -whatif:$args[5] -confirm:$args[6] -skipNetworkProfileCheck $args[7] -errorMsgUnableToInstallPlugin $args[8] -"; - - private const string _workflowConfigXml = @" - - - - - - - - - - - - - - - "; private static ScriptBlock s_enableRemotingSb; @@ -5036,15 +4917,9 @@ function Enable-PSRemoting static EnablePSRemotingCommand() { - string workflowConfigXml = string.Format(CultureInfo.InvariantCulture, _workflowConfigXml, - string.Format(CultureInfo.InvariantCulture, "{0}.{1}", PSVersionInfo.PSVersion.Major, PSVersionInfo.PSVersion.Minor), - PSSessionConfigurationCommandBase.GetLocalSddl()); - string enableRemotingScript = string.Format(CultureInfo.InvariantCulture, enableRemotingSbFormat, PSSessionConfigurationCommandUtilities.GetWinrmPluginShellName(), - // Workflow endpoint configuration will be done through Register-PSSessionConfiguration - // when the new features are available. - workflowConfigXml, PSSessionConfigurationCommandBase.RemoteManagementUsersSID, PSSessionConfigurationCommandBase.InteractiveUsersSID, + PSSessionConfigurationCommandBase.RemoteManagementUsersSID, PSSessionConfigurationCommandBase.InteractiveUsersSID, RemotingConstants.MaxIdleTimeoutMS, RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index b12680865f4..9009f3d59f5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -2411,7 +2411,7 @@ private List GetUsingVariables(ScriptBlock localScriptBlo throw new ArgumentNullException("localScriptBlock", "Caller needs to make sure the parameter value is not null"); } - var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(localScriptBlock.Ast); + var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpression(localScriptBlock.Ast); return allUsingExprs.Select(usingExpr => UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst)usingExpr)).ToList(); } diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 3a26e8eec91..79d0c20117d 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -173,7 +173,7 @@ internal static void ThrowError(ScriptBlockToPowerShellNotSupportedException ex, internal class UsingExpressionAstSearcher : AstSearcher { - internal static IEnumerable FindAllUsingExpressionExceptForWorkflow(Ast ast) + internal static IEnumerable FindAllUsingExpression(Ast ast) { Diagnostics.Assert(ast != null, "caller to verify arguments"); @@ -189,12 +189,6 @@ private UsingExpressionAstSearcher(Func callback, bool stopOnFirst, b public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst ast) { - // Skip the workflow. We are not interested in the UsingExpressions in a workflow - if (ast.IsWorkflow) - { - return AstVisitAction.SkipChildren; - } - return CheckScriptBlock(ast); } } @@ -346,7 +340,7 @@ private static Tuple, object[]> GetUsingValues(Ast bo { Diagnostics.Assert(context != null || variables != null, "can't retrieve variables with no context and no variables"); - var usingAsts = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(body).ToList(); + var usingAsts = UsingExpressionAstSearcher.FindAllUsingExpression(body).ToList(); var usingValueArray = new object[usingAsts.Count]; var usingValueMap = new Dictionary(usingAsts.Count); HashSet usingVarNames = (variables != null && filterNonUsingVariables) ? new HashSet() : null; @@ -458,10 +452,6 @@ private static Tuple, object[]> GetUsingValues(Ast bo /// /// Check if the given UsingExpression is in a different scope from the previous UsingExpression that we analyzed. /// - /// - /// Note that the value of is retrieved by calling 'UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow'. - /// So is guaranteed not inside a workflow. - /// /// The UsingExpression to analyze. /// The top level Ast, should be either ScriptBlockAst or FunctionDefinitionAst. /// The ScriptBlockAst that represents the scope of the previously analyzed UsingExpressions. diff --git a/src/System.Management.Automation/help/AliasHelpInfo.cs b/src/System.Management.Automation/help/AliasHelpInfo.cs index 7f7e13a2d27..d0fd56d0f49 100644 --- a/src/System.Management.Automation/help/AliasHelpInfo.cs +++ b/src/System.Management.Automation/help/AliasHelpInfo.cs @@ -27,7 +27,7 @@ private AliasHelpInfo(AliasInfo aliasInfo) this.ForwardTarget = name; // A Cmdlet/Function/Script etc can have alias. this.ForwardHelpCategory = HelpCategory.Cmdlet | - HelpCategory.Function | HelpCategory.ExternalScript | HelpCategory.ScriptCommand | HelpCategory.Filter | HelpCategory.Workflow; + HelpCategory.Function | HelpCategory.ExternalScript | HelpCategory.ScriptCommand | HelpCategory.Filter; if (!string.IsNullOrEmpty(aliasInfo.Name)) { diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index 11e976b8ed7..24acee030d7 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -1253,7 +1253,7 @@ private static bool Match(string target, ICollection patterns) internal override IEnumerable ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest) { HelpCategory categoriesHandled = (HelpCategory.Alias - | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand | HelpCategory.Workflow); + | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand); if ((helpInfo.HelpCategory & categoriesHandled) != 0) { diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index 76a65aab270..838676f41ce 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -499,7 +499,7 @@ private void ValidateAndThrowIfError(HelpCategory cat) // categories that support -Parameter, -Role, -Functionality, -Component parameters HelpCategory supportedCategories = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ExternalScript | - HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand | HelpCategory.Workflow; + HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand; if ((cat & supportedCategories) == 0) { diff --git a/src/System.Management.Automation/help/HelpRequest.cs b/src/System.Management.Automation/help/HelpRequest.cs index 65598ce869e..83113a4ca9d 100644 --- a/src/System.Management.Automation/help/HelpRequest.cs +++ b/src/System.Management.Automation/help/HelpRequest.cs @@ -155,7 +155,7 @@ internal void Validate() if ((!(Component == null && Role == null && Functionality == null)) && (HelpCategory == HelpCategory.None)) { - HelpCategory = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.Function | HelpCategory.Filter | HelpCategory.ExternalScript | HelpCategory.ScriptCommand | HelpCategory.Workflow; + HelpCategory = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.Function | HelpCategory.Filter | HelpCategory.ExternalScript | HelpCategory.ScriptCommand; return; } diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index a362b4723ef..3e3c4080a85 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -908,11 +908,6 @@ internal enum HelpCategory /// DefaultHelp = 0x1000, - /// - /// Help for a Workflow. - /// - Workflow = 0x2000, - /// /// Help for a Configuration. /// diff --git a/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs b/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs index 252078ba1ed..119c51d67dd 100644 --- a/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs +++ b/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs @@ -37,8 +37,7 @@ internal override HelpCategory HelpCategory HelpCategory.Filter | HelpCategory.Function | HelpCategory.Configuration | - HelpCategory.ScriptCommand | - HelpCategory.Workflow; + HelpCategory.ScriptCommand; } } diff --git a/src/System.Management.Automation/resources/Credential.resx b/src/System.Management.Automation/resources/Credential.resx index 63d780d1404..8cc61de0e5e 100644 --- a/src/System.Management.Automation/resources/Credential.resx +++ b/src/System.Management.Automation/resources/Credential.resx @@ -118,10 +118,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Cannot serialize the credential. If this command is starting a workflow, the credentials cannot be persisted, because the process in which the workflow is started does not have permission to serialize credentials. - --- If the workflow was started in a PSSession to the local computer, add the EnableNetworkAccess parameter to the command that created the session. --- If the workflow was started in a PSSession to a remote computer, add the Authentication parameter with a value of CredSSP to the command that created the session. Or, connect to a session configuration that has a RunAsUser property value. + Cannot serialize the credential. The value for UserName is not in the correct format. diff --git a/src/System.Management.Automation/resources/ErrorPackage.resx b/src/System.Management.Automation/resources/ErrorPackage.resx index 49d1e8c2fc7..b05a0efbf62 100644 --- a/src/System.Management.Automation/resources/ErrorPackage.resx +++ b/src/System.Management.Automation/resources/ErrorPackage.resx @@ -126,14 +126,6 @@ Object "{0}" is reported as an error. - - The action preference of "Suspend" is supported only for ErrorAction. - "Suspend" and ErrorAction should not be localized - - - The error action preference of "Suspend" is supported only on workflows. - "Suspend" should not be localized - it is a literal. - The value {0} is not supported for an ActionPreference variable. The provided value should be used only as a value for a preference parameter, and has been replaced by the default value. For more information, see the Help topic, "about_Preference_Variables." diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index adaa86dbcb7..3db00ba2c6a 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -392,9 +392,6 @@ Possible matches are The switch statement was incomplete. - - The '-parallel' parameter can be used only within a workflow. - Cannot process the 'switch' statement because of a missing file name argument to the -file option. @@ -911,9 +908,6 @@ The correct form is: foreach ($a in $b) {...} Missing statement body after keyword '{0}'. - - Parallel and sequence blocks are not allowed in restricted language mode or a Data section. - Unexpected keyword '{0}'. @@ -1202,9 +1196,6 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. - - Workflow is not supported in PowerShell 6+. - Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. @@ -1500,4 +1491,7 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Class keyword is not allowed in ConstrainedLanguage mode. + + Block statements are not allowed in restricted language mode or a Data section. + diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index b1f3060c880..68a66084490 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -503,9 +503,6 @@ internal static string DumpLockdownState(uint pdwLockdownState) return returnValue; } - // Overrides for features that should only be enabled in debug mode - internal static bool XamlWorkflowSupported { get; set; } - /// /// Native constants for dealing with the lockdown policy. /// From 2e90c8563970837130e8adbad671eb06b30c7ec5 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 18:45:04 -0300 Subject: [PATCH 02/29] CodeFactor changes --- .../engine/parser/ast.cs | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 999d8604db3..34af34315d4 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -3520,7 +3520,7 @@ public Tuple GetWithInputHandlingForInvokeCommandWithUsingExpres public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider { /// - /// Construct a function definition. + /// Initializes a new instance of the class. /// /// /// The extent of the function definition, starting with the function or filter keyword, ending at the closing curly. @@ -3535,11 +3535,15 @@ public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider /// If , , or is null, or /// if is an empty string. /// - public FunctionDefinitionAst(IScriptExtent extent, - bool isFilter, - string name, - IEnumerable parameters, - ScriptBlockAst body) + /// + /// This class represents a function definition in PowerShell. + /// + public FunctionDefinitionAst( + IScriptExtent extent, + bool isFilter, + string name, + IEnumerable parameters, + ScriptBlockAst body) : base(extent) { if (string.IsNullOrEmpty(name)) @@ -3565,16 +3569,18 @@ public FunctionDefinitionAst(IScriptExtent extent, SetParent(body); } - internal FunctionDefinitionAst(IScriptExtent extent, - bool isFilter, - Token functionNameToken, - IEnumerable parameters, - ScriptBlockAst body) - : this(extent, - isFilter, - (functionNameToken.Kind == TokenKind.Generic) ? ((StringToken)functionNameToken).Value : functionNameToken.Text, - parameters, - body) + internal FunctionDefinitionAst( + IScriptExtent extent, + bool isFilter, + Token functionNameToken, + IEnumerable parameters, + ScriptBlockAst body) + : this( + extent, + isFilter, + (functionNameToken.Kind == TokenKind.Generic) ? ((StringToken)functionNameToken).Value : functionNameToken.Text, + parameters, + body) { NameExtent = functionNameToken.Extent; } @@ -7279,7 +7285,7 @@ public BlockStatementAst(IScriptExtent extent, Token kind, StatementBlockAst bod // This should remain empty until block statements are needed in PowerShell. The only tokens that supported // them in the past were deprecated along with workflow in PowerShell 7. - private static SortedSet tokenKindsThatSupportBlockStatements = new SortedSet {}; + private static SortedSet tokenKindsThatSupportBlockStatements = new SortedSet(); /// /// The scriptblockexpression that has a keyword applied to it. This property is nerver null. From ca0433ba16b62ab8a29c3ee85405819e9d56d5fa Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 18:48:24 -0300 Subject: [PATCH 03/29] minor fix to previous commit --- src/System.Management.Automation/engine/parser/ast.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 34af34315d4..cdae0b9fbd9 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -3520,7 +3520,7 @@ public Tuple GetWithInputHandlingForInvokeCommandWithUsingExpres public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// /// The extent of the function definition, starting with the function or filter keyword, ending at the closing curly. From eefe902f266b2f45594f478712234750c1aaf46e Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 22:03:37 -0300 Subject: [PATCH 04/29] add deprecated placeholders to pass asserts --- .../engine/parser/token.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index 50d8d92823f..c1f45d2ebb4 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -710,6 +710,11 @@ public enum TokenFlags /// The token is a statement but does not support attributes. /// StatementDoesntSupportAttributes = 0x01000000, + + /// + /// The token has been deprecated. + /// + Deprecated = 0x10000000, } /// @@ -893,6 +898,10 @@ public static class TokenTraits /* Using */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* Var */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* While */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, + /* Workflow */ TokenFlags.Deprecated, + /* Parallel */ TokenFlags.Deprecated, + /* Sequence */ TokenFlags.Deprecated, + /* InlineScript */ TokenFlags.Deprecated, /* Configuration */ TokenFlags.Keyword, /* */ TokenFlags.Keyword, /* Public */ TokenFlags.Keyword, @@ -1087,6 +1096,10 @@ public static class TokenTraits /* Using */ "using", /* Var */ "var", /* While */ "while", + /* Workflow */ "DEPRECATED", + /* Parallel */ "DEPRECATED", + /* Sequence */ "DEPRECATED", + /* InlineScript */ "DEPRECATED", /* Configuration */ "configuration", /* */ "", /* Public */ "public", From c4e5618c8971cf92681f5f7436ac9257fa6191fc Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 22:53:11 -0300 Subject: [PATCH 05/29] foreach parameter deprecation plus test cleanup --- .../engine/parser/Parser.cs | 51 +------------------ .../engine/parser/SemanticChecks.cs | 9 ---- .../engine/parser/ast.cs | 48 ----------------- .../resources/ParserStrings.resx | 8 --- .../Scripting/ActionPreference.Tests.ps1 | 45 ---------------- .../Scripting/ForeachParallel.Tests.ps1 | 33 +++--------- .../Language/Scripting/TestsOnWinFullOnly.ps1 | 32 ------------ 7 files changed, 8 insertions(+), 218 deletions(-) delete mode 100644 test/powershell/Language/Scripting/TestsOnWinFullOnly.ps1 diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index f551bc936f2..006007ab8ab 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -3222,18 +3222,9 @@ private ExpressionAst GetWordOrExpression(Token keywordToken) private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachToken) { // G foreach-statement: - // G 'foreach' new-lines:opt foreach-parameters:opt new-lines:opt '(' + // G 'foreach' new-lines:opt '(' // G new-lines:opt variable new-lines:opt 'in' new-lines:opt pipeline // G new-lines:opt ')' statement-block - // G foreach-parameters: - // G foreach-parameter - // G foreach-parameters foreach-parameter - // G foreach-parameter: - // G '-parallel' - // G '-throttlelimit' new-lines:opt foreach-throttlelimit - // G foreach-throttlelimit: - // G command-argument - // G primary-expression IScriptExtent startOfStatement = labelToken != null ? labelToken.Extent : forEachToken.Extent; IScriptExtent endErrorStatement = null; @@ -3241,45 +3232,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo SkipNewlines(); // Process parameters on foreach - Token foreachParameterToken = PeekToken(); ForEachFlags flags = ForEachFlags.None; - ExpressionAst throttleLimit = null; - - while (foreachParameterToken.Kind == TokenKind.Parameter) - { - SkipToken(); - - if (IsSpecificParameter(foreachParameterToken, "parallel")) - { - flags |= ForEachFlags.Parallel; - } - else if (IsSpecificParameter(foreachParameterToken, "throttlelimit")) - { - SkipNewlines(); - throttleLimit = GetSingleCommandArgument(CommandArgumentContext.CommandArgument); - if (throttleLimit == null) - { - // ErrorRecovery: pretend we saw the throttle limit and continue. - - ReportIncompleteInput(After(foreachParameterToken), - nameof(ParserStrings.MissingThrottleLimit), - ParserStrings.MissingThrottleLimit); - } - } - else - { - // ErrorRecovery: just ignore the token, continue parsing. - - endErrorStatement = foreachParameterToken.Extent; - ReportError(foreachParameterToken.Extent, - nameof(ParserStrings.InvalidForeachFlag), - ParserStrings.InvalidForeachFlag, - ((ParameterToken)foreachParameterToken).ParameterName); - } - - SkipNewlines(); - foreachParameterToken = PeekToken(); - } Token lParen = NextToken(); if (lParen.Kind != TokenKind.LParen) @@ -3378,7 +3331,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo return new ForEachStatementAst(ExtentOf(startOfStatement, body), labelToken != null ? labelToken.LabelText : null, flags, - throttleLimit, variableAst, pipeline, body); + variableAst, pipeline, body); } private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 9e158e9294e..b5311aa148c 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -472,15 +472,6 @@ public override AstVisitAction VisitDataStatement(DataStatementAst dataStatement public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { - // Throttle limit must be combined with Parallel flag - if ((forEachStatementAst.ThrottleLimit != null) && - ((forEachStatementAst.Flags & ForEachFlags.Parallel) != ForEachFlags.Parallel)) - { - _parser.ReportError(forEachStatementAst.Extent, - nameof(ParserStrings.ThrottleLimitRequiresParallelFlag), - ParserStrings.ThrottleLimitRequiresParallelFlag); - } - return AstVisitAction.Continue; } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index cdae0b9fbd9..ed7b0235a82 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -4117,11 +4117,6 @@ public enum ForEachFlags /// None = 0x00, - /// - /// The -parallel flag. - /// - Parallel = 0x01, - // If any flags are added that impact evaluation of items during the foreach statement, then // a binder (and caching strategy) needs to be added similar to SwitchClauseEvalBinder. } @@ -4163,47 +4158,11 @@ public ForEachStatementAst(IScriptExtent extent, SetParent(variable); } - /// - /// Construct a foreach statement. - /// - /// - /// The extent of the statement, starting from the optional label or the foreach keyword and ending at the closing curly brace. - /// - /// The optionally null label. - /// Any flags that affect how the foreach statement is processed. - /// The limit to be obeyed during parallel processing, if any. - /// The variable set on each iteration of the loop. - /// The pipeline generating values to iterate through. - /// The body to execute for each element written from pipeline. - /// - /// If , , or is null. - /// - public ForEachStatementAst(IScriptExtent extent, - string label, - ForEachFlags flags, - ExpressionAst throttleLimit, - VariableExpressionAst variable, - PipelineBaseAst expression, - StatementBlockAst body) - : this(extent, label, flags, variable, expression, body) - { - this.ThrottleLimit = throttleLimit; - if (throttleLimit != null) - { - SetParent(throttleLimit); - } - } - /// /// The name of the variable set for each item as the loop iterates. This property is never null. /// public VariableExpressionAst Variable { get; private set; } - /// - /// The limit to be obeyed during parallel processing, if any. - /// - public ExpressionAst ThrottleLimit { get; private set; } - /// /// The flags, if any specified on the foreach statement. /// @@ -4218,13 +4177,6 @@ public override Ast Copy() var newExpression = CopyElement(this.Condition); var newBody = CopyElement(this.Body); - if (this.ThrottleLimit != null) - { - var newThrottleLimit = CopyElement(this.ThrottleLimit); - return new ForEachStatementAst(this.Extent, this.Label, this.Flags, newThrottleLimit, - newVariable, newExpression, newBody); - } - return new ForEachStatementAst(this.Extent, this.Label, this.Flags, newVariable, newExpression, newBody); } diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index 3db00ba2c6a..c5e3ae359e8 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -998,14 +998,6 @@ The correct form is: foreach ($a in $b) {...} Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. - - The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. - 'ThrottleLimit' must not be localized. - - - The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. - 'ThrottleLimit' and 'Parallel' must not be localized. - The configuration block results were null or empty. Verify that configurations were defined in the block. diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index 134d4d1836d..e1f553fc373 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -43,16 +43,6 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $GLOBAL:errorActionPreference = $orgin } - It 'action preference of Suspend cannot be set as a preference variable' { - $e = { - $GLOBAL:errorActionPreference = "Suspend" - Get-Process -Name asdfasdfasdf - } | Should -Throw -ErrorId 'RuntimeException' -PassThru - $e.CategoryInfo.Reason | Should -BeExactly 'ArgumentTransformationMetadataException' - - $GLOBAL:errorActionPreference = $orgin - } - It 'enum disambiguation works' { $errorCount = $error.Count Get-Process -Name asdfasdfsadfsadf -ErrorAction Ig @@ -60,42 +50,7 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $error.Count | Should -BeExactly $errorCount } - It 'ErrorAction = Suspend works on Workflow' -Skip:$IsCoreCLR { - . .\TestsOnWinFullOnly.ps1 - Run-TestOnWinFull "ActionPreference:ErrorAction=SuspendOnWorkflow" - } - - It 'ErrorAction = Suspend does not work on functions' { - function MyHelperFunction { - [CmdletBinding()] - param() - "Hello" - } - - { MyHelperFunction -ErrorAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,MyHelperFunction" - } - - It 'ErrorAction = Suspend does not work on cmdlets' { - { Get-Process -ErrorAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" - } - - It 'WarningAction = Suspend does not work' { - { Get-Process -WarningAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" - } - #issue 2076 - It 'ErrorAction and WarningAction are the only action preferences do not support suspend' -Pending{ - $params = [System.Management.Automation.Internal.CommonParameters].GetProperties().Name | Select-String Action - - $suspendErrors = $null - $num=0 - - $params | ForEach-Object { - $input=@{'InputObject' = 'Test';$_='Suspend'} - { Write-Output @input } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.WriteOutputCommand" - } - } - It ' does not take precedence over $ErrorActionPreference' -TestCases @( @{switch="Verbose"}, @{switch="Debug"} diff --git a/test/powershell/Language/Scripting/ForeachParallel.Tests.ps1 b/test/powershell/Language/Scripting/ForeachParallel.Tests.ps1 index c0941a36269..58eaeaf68e8 100644 --- a/test/powershell/Language/Scripting/ForeachParallel.Tests.ps1 +++ b/test/powershell/Language/Scripting/ForeachParallel.Tests.ps1 @@ -2,40 +2,19 @@ # Licensed under the MIT License. Describe "Parallel foreach syntax" -Tags "CI" { - Context 'Should be able to retrieve AST of parallel foreach, error in regular case' { - $errors = @() - $ast = [System.Management.Automation.Language.Parser]::ParseInput( - 'foreach -parallel ($foo in $bar) {}', [ref] $null, [ref] $errors) - It '$errors.Count' { $errors.Count | Should -Be 1 } - It '$ast.EndBlock.Statements[0].Flags' { $ast.EndBlock.Statements[0].Flags | Should -BeExactly 'Parallel' } - } - - It 'Should be able to retrieve AST of parallel foreach, works in JobDefinition case' -Skip:$IsCoreCLR { - . .\TestsOnWinFullOnly.ps1 - Run-TestOnWinFull "ForeachParallel:ASTOfParallelForeachOnWorkflow" - } - - Context 'Supports newlines before and after' { - $errors = @() - $ast = [System.Management.Automation.Language.Parser]::ParseInput( - "foreach `n-parallel `n(`$foo in `$bar) {}", [ref] $null, [ref] $null) - It '$errors.Count' { $errors.Count | Should -Be 0 } - It '$ast.EndBlock.Statements[0].Flags' { $ast.EndBlock.Statements[0].Flags | Should -BeExactly 'Parallel' } - } - - Context 'Generates an error on invalid parameter' { + Context 'Generates an error on an arbitrary parameter' { $errors = @() $ast = [System.Management.Automation.Language.Parser]::ParseInput( 'foreach -bogus ($input in $bar) { }', [ref]$null, [ref]$errors) - It '$errors.Count' { $errors.Count | Should -Be 1 } - It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'InvalidForeachFlag' } + It '$errors.Count' { $errors.Count | Should -BeGreaterOrEqual 1 } + It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'MissingOpenParenthesisAfterKeyword' } } - Context 'Generate an error on -parallel that is not a workflow' { + Context 'Generate an error on -parallel' { $errors = @() $ast = [System.Management.Automation.Language.Parser]::ParseInput( 'foreach -parallel ($input in $bar) { }', [ref]$null, [ref]$errors) - It '$errors.Count' { $errors.Count | Should -Be 1 } - It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'ParallelNotSupported' } + It '$errors.Count' { $errors.Count | Should -BeGreaterOrEqual 1 } + It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'MissingOpenParenthesisAfterKeyword' } } } \ No newline at end of file diff --git a/test/powershell/Language/Scripting/TestsOnWinFullOnly.ps1 b/test/powershell/Language/Scripting/TestsOnWinFullOnly.ps1 deleted file mode 100644 index 3a273c02b8a..00000000000 --- a/test/powershell/Language/Scripting/TestsOnWinFullOnly.ps1 +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. -function Run-TestOnWinFull -{ - [CmdletBinding()] - param( [string]$name ) - - switch ($name) - { - "ActionPreference:ErrorAction=SuspendOnWorkflow" { - workflow TestErrorActionSuspend { "Hello" } - - $r = TestErrorActionSuspend -ErrorAction Suspend - - $r | Should -BeExactly 'Hello' - break; } - - "ForeachParallel:ASTOfParallelForeachOnWorkflow" { - Import-Module PSWorkflow - $errors = @() - $ast = [System.Management.Automation.Language.Parser]::ParseInput( - 'workflow foo { foreach -parallel ($foo in $bar) {} }', [ref] $null, [ref] $errors) - $errors.Count | Should -Be 0 - $ast.EndBlock.Statements[0].Body.EndBlock.Statements[0].Flags | Should -BeExactly 'Parallel' - break; - } - default { - #do nothing - } - - } -} \ No newline at end of file From 15b6ccaf2ef6ec1b858ee4104c5a946abfad2ef0 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Thu, 25 Jul 2019 00:01:10 -0300 Subject: [PATCH 06/29] fix Pester test workflow references --- test/powershell/SDK/PSDebugging.Tests.ps1 | 2 +- test/powershell/engine/Api/TypeInference.Tests.ps1 | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/test/powershell/SDK/PSDebugging.Tests.ps1 b/test/powershell/SDK/PSDebugging.Tests.ps1 index f1d486a258b..5189cb5c5ec 100644 --- a/test/powershell/SDK/PSDebugging.Tests.ps1 +++ b/test/powershell/SDK/PSDebugging.Tests.ps1 @@ -187,7 +187,7 @@ Describe "Runspace Debugging API tests" -tag CI { Context "PSStandaloneMonitorRunspaceInfo tests" { BeforeAll { $runspace = [runspacefactory]::CreateRunspace() - $runspaceType = [PSMonitorRunspaceType]::WorkflowInlineScript + $runspaceType = [PSMonitorRunspaceType]::InvokeCommand $monitorInfo = [PSStandaloneMonitorRunspaceInfo]::new($runspace) $instanceId = $runspace.InstanceId $parentDebuggerId = [guid]::newguid() diff --git a/test/powershell/engine/Api/TypeInference.Tests.ps1 b/test/powershell/engine/Api/TypeInference.Tests.ps1 index c31cff4de33..7cbc899df10 100644 --- a/test/powershell/engine/Api/TypeInference.Tests.ps1 +++ b/test/powershell/engine/Api/TypeInference.Tests.ps1 @@ -591,7 +591,8 @@ Describe "Type inference Tests" -tags "CI" { $res.Name | Should -Be 'System.Int32' } - It "Infers type from block statement" { + # This test should be skipped until block statements are brought back into PowerShell + It "Infers type from block statement" -Skip:$true { $errors = $null $tokens = $null $ast = [Language.Parser]::ParseInput("parallel {1}", [ref] $tokens, [ref] $errors) From 34d2dd7659ac67c71b1ff4ce7d10b6df47456545 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Thu, 25 Jul 2019 11:25:30 -0300 Subject: [PATCH 07/29] temporarily re-add IsWorkflow as dummy property --- src/System.Management.Automation/engine/parser/ast.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index ed7b0235a82..b51bdf23ed9 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -3590,6 +3590,16 @@ internal FunctionDefinitionAst( /// public bool IsFilter { get; private set; } + /// + /// Gets a value indicating whether or not the function is actually a workflow. + /// + /// + /// This property has been deprecated. It should be removed once PowerShellGet + /// is updated to check the PowerShell version before looking at the IsWorkflow + /// property. + /// + public bool IsWorkflow { get { return false; } } + /// /// The name of the function or filter. This property is never null or empty. /// From 92242d5dc5def6dafa77191fcf3b52609dadcca1 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 14:53:20 -0300 Subject: [PATCH 08/29] replace deprecated keywords; add tests --- .../engine/parser/Parser.cs | 11 +++++++ .../engine/parser/token.cs | 32 ++++++++++++------- .../engine/parser/tokenizer.cs | 18 ++++++----- .../resources/ParserStrings.resx | 3 ++ .../Language/Parser/Parsing.Tests.ps1 | 15 ++++++++- 5 files changed, 59 insertions(+), 20 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 006007ab8ab..f35e3ade481 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -2042,6 +2042,17 @@ private StatementAst StatementRule() case TokenKind.Configuration: statement = ConfigurationStatementRule(attributes != null ? attributes.OfType() : null, token); break; + case TokenKind.Workflow: + case TokenKind.Parallel: + case TokenKind.Sequence: + case TokenKind.InlineScript: + // These tokens have been deprecated. + ReportError(token.Extent, + nameof(ParserStrings.DeprecatedKeywordNotAllowed), + ParserStrings.DeprecatedKeywordNotAllowed, + token.Kind.Text()); + statement = new ErrorStatementAst(token.Extent); + break; case TokenKind.From: case TokenKind.Define: case TokenKind.Var: diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index c1f45d2ebb4..cd406e102a5 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -516,8 +516,18 @@ public enum TokenKind /// The 'while' keyword. While = 150, - // Keywords 151-154 were part of the workflow functionality that was removed in PowerShell 7. + /// The 'workflow' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. + Workflow = 151, + /// The 'parallel' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. + Parallel = 152, + + /// The 'sequence' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. + Sequence = 153, + + /// The 'InlineScript' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. + InlineScript = 154, + /// The "configuration" keyword Configuration = 155, @@ -898,10 +908,10 @@ public static class TokenTraits /* Using */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* Var */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* While */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* Workflow */ TokenFlags.Deprecated, - /* Parallel */ TokenFlags.Deprecated, - /* Sequence */ TokenFlags.Deprecated, - /* InlineScript */ TokenFlags.Deprecated, + /* Workflow */ TokenFlags.Keyword | TokenFlags.Deprecated, + /* Parallel */ TokenFlags.Keyword | TokenFlags.Deprecated, + /* Sequence */ TokenFlags.Keyword | TokenFlags.Deprecated, + /* InlineScript */ TokenFlags.Keyword | TokenFlags.Deprecated, /* Configuration */ TokenFlags.Keyword, /* */ TokenFlags.Keyword, /* Public */ TokenFlags.Keyword, @@ -1096,10 +1106,10 @@ public static class TokenTraits /* Using */ "using", /* Var */ "var", /* While */ "while", - /* Workflow */ "DEPRECATED", - /* Parallel */ "DEPRECATED", - /* Sequence */ "DEPRECATED", - /* InlineScript */ "DEPRECATED", + /* Workflow */ "workflow", + /* Parallel */ "parallel", + /* Sequence */ "sequence", + /* InlineScript */ "inlinescript", /* Configuration */ "configuration", /* */ "", /* Public */ "public", @@ -1128,8 +1138,8 @@ static TokenTraits() // Some random assertions to make sure the enum and the traits are in sync Diagnostics.Assert(GetTraits(TokenKind.Begin) == (TokenFlags.Keyword | TokenFlags.ScriptBlockBlockName), "Table out of sync with enum - flags Begin"); - Diagnostics.Assert(GetTraits(TokenKind.While) == (TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes), - "Table out of sync with enum - flags While"); + Diagnostics.Assert(GetTraits(TokenKind.Workflow) == (TokenFlags.Keyword | TokenFlags.Deprecated), + "Table out of sync with enum - flags Workflow"); Diagnostics.Assert(GetTraits(TokenKind.Configuration) == TokenFlags.Keyword, "Table out of sync with enum - flags Configuration"); Diagnostics.Assert(GetTraits(TokenKind.Shr) == (TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison | TokenFlags.CanConstantFold), diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 6158e242c87..93001c4147c 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -624,10 +624,11 @@ private static readonly Dictionary s_operatorTable /*6*/ "throw", "begin", "process", "end", /*6*/ /*7*/ "dynamicparam", "function", "filter", "param", /*7*/ /*8*/ "class", "define", "var", "using", /*8*/ - /*9*/ "configuration", "public", "private", "static", /*9*/ - /*A*/ "interface", "enum", "namespace", "module", /*A*/ - /*B*/ "type", "assembly", "command", "hidden", /*B*/ - /*C*/ "base", /*C*/ + /*9*/ "workflow", "parallel", "sequence", "inlinescript", /*9*/ + /*A*/ "configuration", "public", "private", "static", /*A*/ + /*B*/ "interface", "enum", "namespace", "module", /*B*/ + /*C*/ "type", "assembly", "command", "hidden", /*C*/ + /*D*/ "base", /*D*/ }; private static readonly TokenKind[] s_keywordTokenKind = new TokenKind[] { @@ -639,10 +640,11 @@ private static readonly Dictionary s_operatorTable /*6*/ TokenKind.Throw, TokenKind.Begin, TokenKind.Process, TokenKind.End, /*6*/ /*7*/ TokenKind.Dynamicparam, TokenKind.Function, TokenKind.Filter, TokenKind.Param, /*7*/ /*8*/ TokenKind.Class, TokenKind.Define, TokenKind.Var, TokenKind.Using, /*8*/ - /*9*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*9*/ - /*A*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*A*/ - /*B*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*B*/ - /*C*/ TokenKind.Base, /*C*/ + /*9*/ TokenKind.Workflow, TokenKind.Parallel, TokenKind.Sequence, TokenKind.InlineScript, /*9*/ + /*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/ + /*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*B*/ + /*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/ + /*D*/ TokenKind.Base, }; internal static readonly string[] _operatorText = new string[] { diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index c5e3ae359e8..96e70a39cdd 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -466,6 +466,9 @@ The correct form is: foreach ($a in $b) {...} The '{0}' keyword is not supported in this version of the language. + + The '{0}' keyword has been deprecated and is no longer supported. + Missing expression after '{0}' in loop. diff --git a/test/powershell/Language/Parser/Parsing.Tests.ps1 b/test/powershell/Language/Parser/Parsing.Tests.ps1 index afb15081124..10957fd364b 100644 --- a/test/powershell/Language/Parser/Parsing.Tests.ps1 +++ b/test/powershell/Language/Parser/Parsing.Tests.ps1 @@ -2,10 +2,23 @@ # Licensed under the MIT License. set-strictmode -v 2 +Describe 'reserved keyword parsing' -Tags 'CI' { + ShouldBeParseError 'from' ReservedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'define' ReservedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'var' ReservedKeywordNotAllowed 1 -CheckColumnNumber +} + +Describe 'deprecated keyword parsing' -Tags 'CI' { + ShouldBeParseError 'workflow' DeprecatedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'parallel' DeprecatedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'sequence' DeprecatedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'inlinescript' DeprecatedKeywordNotAllowed 1 -CheckColumnNumber +} + Describe 'for statement parsing' -Tags "CI" { ShouldBeParseError 'for' MissingOpenParenthesisAfterKeyword 4 -CheckColumnNumber ShouldBeParseError 'for(' MissingEndParenthesisAfterStatement 5 -CheckColumnNumber - ShouldBeParseError 'for(;' MissingEndParenthesisAfterStatement 6 -CheckColumnNumber + ShouldBeParseError 'for(; ' MissingEndParenthesisAfterStatement 6 -CheckColumnNumber ShouldBeParseError 'for(;;' MissingEndParenthesisAfterStatement 7 -CheckColumnNumber ShouldBeParseError 'for($a' MissingEndParenthesisAfterStatement 7 -CheckColumnNumber ShouldBeParseError 'for($a;' MissingEndParenthesisAfterStatement 8 -CheckColumnNumber From 0f9155c50ed4d633aab97a3204de243bb00a9dc8 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 14:57:58 -0300 Subject: [PATCH 09/29] remove extra whitespace, add missing comment --- src/System.Management.Automation/engine/parser/token.cs | 2 +- src/System.Management.Automation/engine/parser/tokenizer.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index cd406e102a5..0351167af1c 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -527,7 +527,7 @@ public enum TokenKind /// The 'InlineScript' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. InlineScript = 154, - + /// The "configuration" keyword Configuration = 155, diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 93001c4147c..6f839bd189e 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -644,7 +644,7 @@ private static readonly Dictionary s_operatorTable /*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/ /*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*B*/ /*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/ - /*D*/ TokenKind.Base, + /*D*/ TokenKind.Base, /*D*/ }; internal static readonly string[] _operatorText = new string[] { From 64af1b5aa6fe6aba58c5449705c09d812cd4e379 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 14:59:39 -0300 Subject: [PATCH 10/29] remove unintentional space --- test/powershell/Language/Parser/Parsing.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/Language/Parser/Parsing.Tests.ps1 b/test/powershell/Language/Parser/Parsing.Tests.ps1 index 10957fd364b..96b899f0fd4 100644 --- a/test/powershell/Language/Parser/Parsing.Tests.ps1 +++ b/test/powershell/Language/Parser/Parsing.Tests.ps1 @@ -18,7 +18,7 @@ Describe 'deprecated keyword parsing' -Tags 'CI' { Describe 'for statement parsing' -Tags "CI" { ShouldBeParseError 'for' MissingOpenParenthesisAfterKeyword 4 -CheckColumnNumber ShouldBeParseError 'for(' MissingEndParenthesisAfterStatement 5 -CheckColumnNumber - ShouldBeParseError 'for(; ' MissingEndParenthesisAfterStatement 6 -CheckColumnNumber + ShouldBeParseError 'for(;' MissingEndParenthesisAfterStatement 6 -CheckColumnNumber ShouldBeParseError 'for(;;' MissingEndParenthesisAfterStatement 7 -CheckColumnNumber ShouldBeParseError 'for($a' MissingEndParenthesisAfterStatement 7 -CheckColumnNumber ShouldBeParseError 'for($a;' MissingEndParenthesisAfterStatement 8 -CheckColumnNumber From 7374bbecf6d4c92fe5ada2346ceacf4d92be572f Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 15:04:04 -0300 Subject: [PATCH 11/29] CodeFactor cleanup --- .../engine/parser/Parser.cs | 15 ++++++++----- .../remoting/commands/CustomShellCommands.cs | 22 +++++++++---------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index f35e3ade481..fbf54cd144d 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -1966,7 +1966,8 @@ private StatementAst StatementRule() } else { - ReportError(attributes[0].Extent, + ReportError( + attributes[0].Extent, nameof(ParserStrings.UnexpectedAttribute), ParserStrings.UnexpectedAttribute, attributes[0].TypeName.FullName); @@ -1976,7 +1977,8 @@ private StatementAst StatementRule() { foreach (var attr in attributes.Where(attr => !(attr is AttributeAst))) { - ReportError(attr.Extent, + ReportError( + attr.Extent, nameof(ParserStrings.TypeNotAllowedBeforeStatement), ParserStrings.TypeNotAllowedBeforeStatement, attr.TypeName.FullName); @@ -2047,7 +2049,8 @@ private StatementAst StatementRule() case TokenKind.Sequence: case TokenKind.InlineScript: // These tokens have been deprecated. - ReportError(token.Extent, + ReportError( + token.Extent, nameof(ParserStrings.DeprecatedKeywordNotAllowed), ParserStrings.DeprecatedKeywordNotAllowed, token.Kind.Text()); @@ -2056,7 +2059,8 @@ private StatementAst StatementRule() case TokenKind.From: case TokenKind.Define: case TokenKind.Var: - ReportError(token.Extent, + ReportError( + token.Extent, nameof(ParserStrings.ReservedKeywordNotAllowed), ParserStrings.ReservedKeywordNotAllowed, token.Kind.Text()); @@ -2106,7 +2110,8 @@ private StatementAst StatementRule() case TokenKind.Using: statement = UsingStatementRule(token); // Report an error - usings must appear before anything else in the script, but parse it anyway - ReportError(statement.Extent, + ReportError( + statement.Extent, nameof(ParserStrings.UsingMustBeAtStartOfScript), ParserStrings.UsingMustBeAtStartOfScript); break; diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index da179878ffb..170d8cc2a0a 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -4,25 +4,23 @@ using System; using System.Collections; using System.Collections.ObjectModel; +using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Security.AccessControl; -using System.Text; -using System.Threading; - using System.Management.Automation; using System.Management.Automation.Internal; -using System.Management.Automation.Runspaces; -using System.Management.Automation.Remoting; using System.Management.Automation.Language; - +using System.Management.Automation.Remoting; +using System.Management.Automation.Runspaces; +using System.Security; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Text; +using System.Threading; using Dbg = System.Management.Automation.Diagnostics; -using WSManNativeApi = System.Management.Automation.Remoting.Client.WSManNativeApi; using PowerShellApi = System.Management.Automation.PowerShell; +using WSManNativeApi = System.Management.Automation.Remoting.Client.WSManNativeApi; -using System.Security; -using System.Collections.Generic; -using System.Security.Principal; namespace Microsoft.PowerShell.Commands { @@ -1051,6 +1049,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d maxObjectSizeMB.Value, Environment.NewLine)); } + if (threadAptState.HasValue) { initParameters.Append(string.Format(CultureInfo.InvariantCulture, @@ -1059,6 +1058,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d threadAptState.Value, Environment.NewLine)); } + if (threadOptions.HasValue) { initParameters.Append(string.Format(CultureInfo.InvariantCulture, From 66be180026f12ef56db4d87007e598477f1593db Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 15:05:02 -0300 Subject: [PATCH 12/29] CodeFactor cleanup --- .../engine/remoting/commands/CustomShellCommands.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 170d8cc2a0a..c2369772e31 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -21,7 +21,6 @@ using PowerShellApi = System.Management.Automation.PowerShell; using WSManNativeApi = System.Management.Automation.Remoting.Client.WSManNativeApi; - namespace Microsoft.PowerShell.Commands { #region Register-PSSessionConfiguration cmdlet From 7034c8ba559cba8fa561773094343cfd3df3aa33 Mon Sep 17 00:00:00 2001 From: Paul Higinbotham Date: Mon, 5 Aug 2019 13:27:49 -0700 Subject: [PATCH 13/29] Fix debugger disable performance regression (#10269) --- .../engine/debugger/debugger.cs | 22 ++- .../ConstrainedLanguageDebugger.Tests.ps1 | 187 +++--------------- 2 files changed, 47 insertions(+), 162 deletions(-) diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 9697715f283..cf24179fac8 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -1692,6 +1692,9 @@ internal void Clear() private volatile int _processingRunspaceDebugQueue; private ManualResetEventSlim _runspaceDebugCompleteEvent; + // System is locked down when true. Used to disable debugger on lock down. + private bool? _isSystemLockedDown; + private static readonly string s_processDebugPromptMatch; #endregion private members @@ -2109,16 +2112,27 @@ private bool CanDisableDebugger } } - private static bool IsSystemLockedDown + private bool IsSystemLockedDown { get { - return (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() == - System.Management.Automation.Security.SystemEnforcementMode.Enforce); + if (_isSystemLockedDown == null) + { + lock (_syncObject) + { + if (_isSystemLockedDown == null) + { + _isSystemLockedDown = (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() == + System.Management.Automation.Security.SystemEnforcementMode.Enforce); + } + } + } + + return _isSystemLockedDown.Value; } } - private static void CheckForBreakpointSupport() + private void CheckForBreakpointSupport() { if (IsSystemLockedDown) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageDebugger.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageDebugger.Tests.ps1 index 04aaa8b3869..0f038c6e890 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageDebugger.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageDebugger.Tests.ps1 @@ -22,85 +22,6 @@ try BeforeAll { - # Invoke-LanguageModeTestingSupportCmdlet definition - $languageModeCmdletDef = @' - using System; - using System.Globalization; - using System.Reflection; - using System.Collections; - using System.Collections.Generic; - using System.IO; - using System.Security; - using System.Runtime.InteropServices; - using System.Threading; - using System.Management.Automation; - - /// Adds a new type to the Application Domain - [Cmdlet("Invoke", "LanguageModeTestingSupportCmdlet")] - public sealed class InvokeLanguageModeTestingSupportCmdlet : PSCmdlet - { - [Parameter()] - public SwitchParameter EnableFullLanguageMode - { - get { return enableFullLanguageMode; } - set { enableFullLanguageMode = value; } - } - private SwitchParameter enableFullLanguageMode; - - [Parameter()] - public SwitchParameter SetLockdownMode - { - get { return setLockdownMode; } - set { setLockdownMode = value; } - } - private SwitchParameter setLockdownMode; - - [Parameter()] - public SwitchParameter RevertLockdownMode - { - get { return revertLockdownMode; } - set { revertLockdownMode = value; } - } - private SwitchParameter revertLockdownMode; - - protected override void BeginProcessing() - { - if(enableFullLanguageMode) - { - SessionState.LanguageMode = PSLanguageMode.FullLanguage; - } - - if(setLockdownMode) - { - Environment.SetEnvironmentVariable("__PSLockdownPolicy", "0x80000007", EnvironmentVariableTarget.Machine); - } - - if(revertLockdownMode) - { - Environment.SetEnvironmentVariable("__PSLockdownPolicy", null, EnvironmentVariableTarget.Machine); - } - } - } -'@ - - if (-not (Get-Command Invoke-LanguageModeTestingSupportCmdlet -ea Ignore)) - { - $languageModeModuleName = "LanguageModeModule" - $modulePath = [System.IO.Path]::GetFileNameWithoutExtension([IO.Path]::GetRandomFileName()) - $script:moduleDirectory = join-path "$PSScriptRoot\$modulePath" $languageModeModuleName - if (-not (Test-Path $moduleDirectory)) - { - $null = New-Item -ItemType Directory $moduleDirectory -Force - } - - try - { - Add-Type -TypeDefinition $languageModeCmdletDef -OutputAssembly $moduleDirectory\TestCmdletForConstrainedLanguage.dll -ErrorAction Ignore - } catch {} - - Import-Module -Name $moduleDirectory\TestCmdletForConstrainedLanguage.dll - } - # Debugger test type definition $debuggerTestTypeDef = @' using System; @@ -146,6 +67,26 @@ try # Define debugger test type Add-Type -TypeDefinition $debuggerTestTypeDef + + # Test cases + $TestCasesDisableDebugger = @( + @{ + testName = 'Verifies that Set-PSBreakpoint Line is disabled on locked down system' + scriptText = 'Set-PSBreakpoint -Script {0} -Line 1' -f $scriptFilePath + }, + @{ + testName = 'Verifies that Set-PSBreakpoint Statement is disabled on locked down system' + scriptText = 'Set-PSBreakpoint -Script {0} -Line 1 -Column 1' -f $scriptFilePath + }, + @{ + testName = 'Verifies that Set-PSBreakpoint Command is disabled on locked down system' + scriptText = 'Set-PSBreakpoint -Command {0}' -f $scriptFilePath + }, + @{ + testName = 'Verifies that Set-PSBreakpoint Variable is disabled on locked down system' + scriptText = 'Set-PSBreakpoint -Variable HelloVar' + } + ) } AfterAll { @@ -156,93 +97,23 @@ try } } - It "Verifies that Set-PSBreakpoint Line is disabled on locked down system" { + It "" -TestCases $TestCasesDisableDebugger { - try - { - Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + param ($scriptText) - Set-PSBreakpoint -Script $scriptFilePath -Line 1 - throw "No Exception!" - } - catch - { - $expectedError = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } - - $expectedError.FullyQualifiedErrorId | Should Be 'NotSupported,Microsoft.PowerShell.Commands.SetPSBreakpointCommand' - } - - It "Verifies that Set-PSBreakpoint Statement is disabled on locked down system" { - - try - { - Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - Set-PSBreakpoint -Script $scriptFilePath -Line 1 -Column 1 - throw "No Exception!" - } - catch - { - $expectedError = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } - - $expectedError.FullyQualifiedErrorId | Should Be 'NotSupported,Microsoft.PowerShell.Commands.SetPSBreakpointCommand' - } - - It "Verifies that Set-PSBreakpoint Command is disabled on locked down system" { - - try + try { Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - Set-PSBreakpoint -Command $scriptFilePath - throw "No Exception!" - } - catch - { - $expectedError = $_ + # Run script in new runspace created within lock down mode. + [powershell] $ps = [powershell]::Create([System.Management.Automation.RunspaceMode]::NewRunspace); + $ps.AddScript($scriptText).Invoke() + $expectedError = $ps.Streams.Error[0] } finally { - Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } - - $expectedError.FullyQualifiedErrorId | Should Be 'NotSupported,Microsoft.PowerShell.Commands.SetPSBreakpointCommand' - } - - It "Verifies that Set-PSBreakpoint Variable is disabled on locked down system" { - - try - { - Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - Set-PSBreakpoint -Variable HelloVar - throw "No Exception!" - } - catch - { - $expectedError = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode -EnableFullLanguageMode + if ($ps -ne $null) { $ps.Dispose() } } $expectedError.FullyQualifiedErrorId | Should Be 'NotSupported,Microsoft.PowerShell.Commands.SetPSBreakpointCommand' From 3ca5a1bdb031eeb9453b1481bcfa23eee6d89aec Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Mon, 5 Aug 2019 20:55:16 -0700 Subject: [PATCH 14/29] Don't collect process starttime as it's not being used on consolehost startup (#10294) * mark _readyForInputTimeInMS member as part of LEGACYTELEMETRY * move _interactiveCommandCount to LEGACYTELEMETRY --- .../host/msh/ConsoleHost.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 226e4497134..6b461fa6035 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1023,11 +1023,12 @@ bool IHostProvidesTelemetryData.HostIsInteractive double IHostProvidesTelemetryData.ReadyForInputTimeInMS { get { return _readyForInputTimeInMS; } } int IHostProvidesTelemetryData.InteractiveCommandCount { get { return _interactiveCommandCount; } } -#endif - private double _profileLoadTimeInMS; private double _readyForInputTimeInMS; private int _interactiveCommandCount; +#endif + + private double _profileLoadTimeInMS; #endregion overrides @@ -1602,8 +1603,10 @@ private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool sta PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational); } +#if LEGACYTELEMETRY // Record how long it took from process start to runspace open for telemetry. _readyForInputTimeInMS = (DateTime.Now - Process.GetCurrentProcess().StartTime).TotalMilliseconds; +#endif DoRunspaceInitialization(skipProfiles, initialCommand, configurationName, initialCommandArgs); } @@ -2517,8 +2520,10 @@ e is RemoteException || } } +#if LEGACYTELEMETRY if (!inBlockMode) s_theConsoleHost._interactiveCommandCount += 1; +#endif } } // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 From 9eb5587d07473435231d2177b10dd471712fef0c Mon Sep 17 00:00:00 2001 From: Reece Dunham Date: Tue, 6 Aug 2019 17:17:15 -0400 Subject: [PATCH 15/29] Cleanup Docker release testing (#10310) --- docker/InstallTarballPackage.sh | 11 ++++------- docker/tests/README.md | 2 +- docker/tests/Templates/centos7/Dockerfile | 4 ++-- .../Templates/fxdependent-dotnetsdk-latest/Dockerfile | 4 ++-- .../tests/Templates/fxdependent-fedora28/Dockerfile | 4 ++-- .../Templates/fxdependent-ubuntu16.04/Dockerfile | 4 ++-- .../Templates/fxdependent-ubuntu18.04/Dockerfile | 4 ++-- docker/tests/containerTestCommon.psm1 | 3 +-- 8 files changed, 16 insertions(+), 20 deletions(-) diff --git a/docker/InstallTarballPackage.sh b/docker/InstallTarballPackage.sh index 1bc807a0b92..08c7923c6eb 100644 --- a/docker/InstallTarballPackage.sh +++ b/docker/InstallTarballPackage.sh @@ -3,24 +3,21 @@ # Exit on errors set -e -# # Example use: # ./InstallTarballPackage.sh "6.0.0-beta.9" "powershell-6.0.0-beta.9-linux-x64.tar.gz" -# + usage() { echo "usage: $0 " exit 1 } POWERSHELL_VERSION=$1 -if [ ! "$POWERSHELL_VERSION" ] -then +if [ ! "$POWERSHELL_VERSION" ]; then usage fi POWERSHELL_PACKAGE=$2 -if [ ! "$POWERSHELL_PACKAGE" ] -then +if [ ! "$POWERSHELL_PACKAGE" ]; then usage fi @@ -37,7 +34,7 @@ tar zxf /tmp/powershell.tar.gz -C /opt/microsoft/powershell/$POWERSHELL_VERSION # Create the symbolic link that points to powershell ln -s /opt/microsoft/powershell/$POWERSHELL_VERSION/pwsh $POWERSHELL_LINKFILE # Add the symbolic link path to /etc/shells -if [ ! -f /etc/shells ] ; then +if [ ! -f /etc/shells ]; then echo $POWERSHELL_LINKFILE > /etc/shells ; else grep -q "^${POWERSHELL_LINKFILE}$" /etc/shells || echo $POWERSHELL_LINKFILE >> /etc/shells ; diff --git a/docker/tests/README.md b/docker/tests/README.md index f43ec7b51aa..716a7d6f62e 100644 --- a/docker/tests/README.md +++ b/docker/tests/README.md @@ -10,7 +10,7 @@ The tests must be run separately on the Windows and Linux docker daemons. You ca Invoke-Pester ``` -Note: be sure to do this using both the Windows and Linux docker daemon, as the windows. +Note: be sure to do this using both the Windows and Linux docker daemon. ## To test the productions containers diff --git a/docker/tests/Templates/centos7/Dockerfile b/docker/tests/Templates/centos7/Dockerfile index 1de7fdf04e6..dddf2439445 100644 --- a/docker/tests/Templates/centos7/Dockerfile +++ b/docker/tests/Templates/centos7/Dockerfile @@ -17,7 +17,7 @@ ENV LANG en_US.UTF-8 ENV LC_ALL $LANG RUN localedef --charmap=UTF-8 --inputfile=en_US $LANG -RUN curl -L -o $PACKAGENAME $PACKAGELOCATION/$PACKAGENAME -RUN yum install -y $PACKAGENAME +RUN curl -L -o $PACKAGENAME $PACKAGELOCATION/$PACKAGENAME \ + && yum install -y $PACKAGENAME RUN $TESTDOWNLOADCOMMAND RUN pwsh$PREVIEWSUFFIX -c "Import-Module /PowerShell/build.psm1;\$dir='/usr/local/share/powershell/Modules';\$null=New-Item -Type Directory -Path \$dir -ErrorAction SilentlyContinue;Restore-PSPester -Destination \$dir;exit (Invoke-Pester $TESTLIST -PassThru).FailedCount" diff --git a/docker/tests/Templates/fxdependent-dotnetsdk-latest/Dockerfile b/docker/tests/Templates/fxdependent-dotnetsdk-latest/Dockerfile index bd61efbf6cb..cf56e4ec074 100644 --- a/docker/tests/Templates/fxdependent-dotnetsdk-latest/Dockerfile +++ b/docker/tests/Templates/fxdependent-dotnetsdk-latest/Dockerfile @@ -23,8 +23,8 @@ RUN locale-gen $LANG && update-locale # Install PowerShell package ADD $PACKAGELOCATION/$PACKAGENAME . -RUN mkdir -p /opt/microsoft/powershell -RUN tar zxf $PACKAGENAME -C /opt/microsoft/powershell +RUN mkdir -p /opt/microsoft/powershell \ + && tar zxf $PACKAGENAME -C /opt/microsoft/powershell # Download and run tests RUN $TESTDOWNLOADCOMMAND diff --git a/docker/tests/Templates/fxdependent-fedora28/Dockerfile b/docker/tests/Templates/fxdependent-fedora28/Dockerfile index a654fa9c0cc..6acb7452446 100644 --- a/docker/tests/Templates/fxdependent-fedora28/Dockerfile +++ b/docker/tests/Templates/fxdependent-fedora28/Dockerfile @@ -30,8 +30,8 @@ RUN localedef --charmap=UTF-8 --inputfile=en_US $LANG # Install PowerShell package ADD $PACKAGELOCATION/$PACKAGENAME . -RUN mkdir -p /opt/microsoft/powershell -RUN tar zxf $PACKAGENAME -C /opt/microsoft/powershell +RUN mkdir -p /opt/microsoft/powershell \ + && tar zxf $PACKAGENAME -C /opt/microsoft/powershell # Download and run tests RUN $TESTDOWNLOADCOMMAND diff --git a/docker/tests/Templates/fxdependent-ubuntu16.04/Dockerfile b/docker/tests/Templates/fxdependent-ubuntu16.04/Dockerfile index 4964c9613d6..aa976ddb19e 100644 --- a/docker/tests/Templates/fxdependent-ubuntu16.04/Dockerfile +++ b/docker/tests/Templates/fxdependent-ubuntu16.04/Dockerfile @@ -31,8 +31,8 @@ RUN locale-gen $LANG && update-locale # Install PowerShell package ADD $PACKAGELOCATION/$PACKAGENAME . -RUN mkdir -p /opt/microsoft/powershell -RUN tar zxf $PACKAGENAME -C /opt/microsoft/powershell +RUN mkdir -p /opt/microsoft/powershell \ + && tar zxf $PACKAGENAME -C /opt/microsoft/powershell # Download and run tests RUN $TESTDOWNLOADCOMMAND diff --git a/docker/tests/Templates/fxdependent-ubuntu18.04/Dockerfile b/docker/tests/Templates/fxdependent-ubuntu18.04/Dockerfile index acec24a0f6e..adc9219a07d 100644 --- a/docker/tests/Templates/fxdependent-ubuntu18.04/Dockerfile +++ b/docker/tests/Templates/fxdependent-ubuntu18.04/Dockerfile @@ -23,8 +23,8 @@ RUN locale-gen $LANG && update-locale # Install PowerShell package ADD $PACKAGELOCATION/$PACKAGENAME . -RUN mkdir -p /opt/microsoft/powershell -RUN tar zxf $PACKAGENAME -C /opt/microsoft/powershell +RUN mkdir -p /opt/microsoft/powershell \ + && tar zxf $PACKAGENAME -C /opt/microsoft/powershell # Download and run tests RUN $TESTDOWNLOADCOMMAND diff --git a/docker/tests/containerTestCommon.psm1 b/docker/tests/containerTestCommon.psm1 index 3b1dd767b74..4816812b644 100644 --- a/docker/tests/containerTestCommon.psm1 +++ b/docker/tests/containerTestCommon.psm1 @@ -75,7 +75,6 @@ function Get-LinuxContainer Path = "$psscriptroot/../release/$os" } } - } # Return a list of Windows Container Test Cases @@ -130,7 +129,7 @@ function Test-SkipLinux return $true } default { - throw "Unknow docker os '$os'" + throw "Unknown docker os '$os'" } } } From d84ebc157196e80c9ddb116f351bf633fd1340e7 Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Tue, 6 Aug 2019 16:32:58 -0700 Subject: [PATCH 16/29] Update our language on our policy applying to security issues (#10304) --- .github/SECURITY.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 3277852a855..10633f0d6d1 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,5 +1,12 @@ # Security Vulnerabilities +Security issues are treated very seriously and will, by default, +takes precedence over other considerations including usability, performance, +etc... Best effort will be used to mitigate side effects of a security +change, but PowerShell must be secure by default. + +## Reporting a security vulnerability + If you believe that there is a security vulnerability in PowerShell, it **must** be reported to [secure@microsoft.com](https://technet.microsoft.com/security/ff852094.aspx) to allow for [Coordinated Vulnerability Disclosure](https://technet.microsoft.com/security/dn467923). **Only** file an issue, if [secure@microsoft.com](https://www.microsoft.com/en-us/msrc/faqs-report-an-issue?rtc=1) has confirmed filing an issue is appropriate. From cf7699b4b9bb96bac906a7052f890d524f375677 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 8 Aug 2019 01:25:10 +0500 Subject: [PATCH 17/29] Add tests for WildcardPattern.Escape() and Unescape() (#10090) --- test/xUnit/csharp/test_WildcardPattern.cs | 63 +++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 test/xUnit/csharp/test_WildcardPattern.cs diff --git a/test/xUnit/csharp/test_WildcardPattern.cs b/test/xUnit/csharp/test_WildcardPattern.cs new file mode 100644 index 00000000000..50fb30620a2 --- /dev/null +++ b/test/xUnit/csharp/test_WildcardPattern.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Management.Automation; +using Xunit; + +namespace PSTests.Parallel +{ + public class WildcardPatternTests + { + [Fact] + public void TestEscape_Null() + { + Assert.Throws(delegate { WildcardPattern.Escape(null); }); + } + + [Fact] + public void TestEscape_Empty() + { + Assert.Equal(WildcardPattern.Escape(string.Empty), string.Empty); + } + + [Theory] + [InlineData("a", "a")] + [InlineData("a*", "a`*")] + [InlineData("*?[]", "`*`?`[`]")] + public void TestEscape_String(string source, string expected) + { + Assert.Equal(WildcardPattern.Escape(source), expected); + } + + [Theory] + [InlineData("a", "a")] + [InlineData("a*", "a*")] + [InlineData("*?[]", "*?[]")] + public void TestEscape_String_NotEscape(string source, string expected) + { + Assert.Equal(WildcardPattern.Escape(source, new[] { '*', '?', '[', ']' }), expected); + } + + [Fact] + public void TestUnescape_Null() + { + Assert.Throws(delegate { WildcardPattern.Unescape(null); }); + } + + [Fact] + public void TestUnescape_Empty() + { + Assert.Equal(WildcardPattern.Unescape(string.Empty), string.Empty); + } + + [Theory] + [InlineData("a", "a")] + [InlineData("a`*", "a*")] + [InlineData("`*`?`[`]", "*?[]")] + public void TestUnescape_String(string source, string expected) + { + Assert.Equal(WildcardPattern.Unescape(source), expected); + } + } +} From b58525ee841e0837bec1e67485d3a153fb77ac02 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 18:13:00 -0300 Subject: [PATCH 18/29] bulk removal of deprecated code (workflow cleanup) --- .../engine/ArgumentTypeConverterAttribute.cs | 5 - .../engine/CommandBase.cs | 2 - .../CommandCompletion/CompletionCompleters.cs | 2 +- .../engine/ExecutionContext.cs | 2 +- .../engine/LanguagePrimitives.cs | 3 +- .../engine/MshCommandRuntime.cs | 15 - .../engine/SessionStateStrings.cs | 4 +- .../engine/debugger/debugger.cs | 135 +-------- .../engine/lang/interface/PSToken.cs | 4 - .../engine/parser/Parser.cs | 122 ++------- .../engine/parser/SemanticChecks.cs | 40 +-- .../engine/parser/ast.cs | 80 +----- .../engine/parser/token.cs | 28 +- .../engine/parser/tokenizer.cs | 22 +- .../engine/remoting/client/JobManager.cs | 76 +++-- .../remoting/client/PowerShellStreams.cs | 259 ------------------ .../remoting/commands/CustomShellCommands.cs | 141 +--------- .../remoting/commands/PSRemotingCmdlet.cs | 2 +- .../engine/runtime/ScriptBlockToPowerShell.cs | 14 +- .../help/AliasHelpInfo.cs | 2 +- .../help/CommandHelpProvider.cs | 2 +- .../help/HelpCommands.cs | 2 +- .../help/HelpRequest.cs | 2 +- .../help/HelpSystem.cs | 5 - .../help/ScriptCommandHelpProvider.cs | 3 +- .../resources/Credential.resx | 5 +- .../resources/ErrorPackage.resx | 8 - .../resources/ParserStrings.resx | 12 +- .../security/wldpNativeMethods.cs | 3 - 29 files changed, 117 insertions(+), 883 deletions(-) delete mode 100644 src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index 19c383e6cd2..c7e373a06f3 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -152,11 +152,6 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b if (_convertTypes[i] == typeof(ActionPreference)) { ActionPreference resultPreference = (ActionPreference)result; - - if (resultPreference == ActionPreference.Suspend) - { - throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference); - } } } } diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index 08500961cfc..d7b6b023330 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -286,8 +286,6 @@ public enum ActionPreference Inquire, /// Ignore the event completely (not even logging it to the target stream) Ignore, - /// Suspend the command for further diagnosis. Supported only for workflows. - Suspend, } #endregion ActionPreference diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 2119e513259..b637a1a139f 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -207,7 +207,7 @@ List ExecuteGetCommandCommand(bool useModulePrefix) } private static readonly HashSet s_keywordsToExcludeFromAddingAmpersand - = new HashSet(StringComparer.OrdinalIgnoreCase) { TokenKind.InlineScript.ToString(), TokenKind.Configuration.ToString() }; + = new HashSet(StringComparer.OrdinalIgnoreCase) { TokenKind.Configuration.ToString() }; internal static CompletionResult GetCommandNameCompletionResult(string name, object command, bool addAmpersandIfNecessary, string quote) { string syntax = name, listItem = name; diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index ff06791f3a7..2084cd33d2c 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -580,7 +580,7 @@ internal T GetEnumPreference(VariablePath preferenceVariablePath, T defaultPr if (val is ActionPreference) { ActionPreference preference = (ActionPreference)val; - if ((preference == ActionPreference.Ignore) || (preference == ActionPreference.Suspend)) + if (preference == ActionPreference.Ignore) { // Reset the variable value EngineSessionState.SetVariableValue(preferenceVariablePath.UserPath, defaultPref); diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 618a23b9f51..47bb39ad349 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -559,7 +559,6 @@ public static IEnumerator GetEnumerator(object obj) /// /// This method takes a an arbitrary object and wraps it in a PSDataCollection of PSObject. - /// This simplifies interacting with the PowerShell workflow activities. /// /// /// @@ -1771,7 +1770,7 @@ public static object ConvertPSObjectToType(PSObject valueToConvert, Type resultT } /// - /// Generic convertto that simplifies working with workflow. + /// Generic conversion method. /// /// The type of object to return /// diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index ed7468cf56b..6ea14e0f23f 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -3037,11 +3037,6 @@ internal ActionPreference WarningPreference set { - if (value == ActionPreference.Suspend) - { - throw PSTraceSource.NewNotSupportedException(ErrorPackage.SuspendActionPreferenceErrorActionOnly); - } - _warningPreference = value; IsWarningActionSet = true; } @@ -3207,11 +3202,6 @@ internal ActionPreference ErrorAction set { - if (value == ActionPreference.Suspend) - { - throw PSTraceSource.NewNotSupportedException(ErrorPackage.SuspendActionPreferenceSupportedOnlyOnWorkflow); - } - _errorAction = value; IsErrorActionSet = true; } @@ -3274,11 +3264,6 @@ internal ActionPreference InformationPreference set { - if (value == ActionPreference.Suspend) - { - throw PSTraceSource.NewNotSupportedException(ErrorPackage.SuspendActionPreferenceErrorActionOnly); - } - _informationPreference = value; IsInformationActionSet = true; } diff --git a/src/System.Management.Automation/engine/SessionStateStrings.cs b/src/System.Management.Automation/engine/SessionStateStrings.cs index 741ab5f47cb..92462b03e10 100644 --- a/src/System.Management.Automation/engine/SessionStateStrings.cs +++ b/src/System.Management.Automation/engine/SessionStateStrings.cs @@ -116,12 +116,12 @@ internal static class StringLiterals internal const string PowerShellDataFileExtension = ".psd1"; /// - /// The file extension (including the dot) of an workflow dependent assembly. + /// The file extension (including the dot) of a binary module. /// internal const string PowerShellILAssemblyExtension = ".dll"; /// - /// The file extension (including the dot) of an workflow dependent Ngen assembly. + /// The file extension (including the dot) of a binary module Ngen assembly. /// internal const string PowerShellNgenAssemblyExtension = ".ni.dll"; diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index cf24179fac8..c12aba6c0ae 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -304,12 +304,12 @@ public enum DebugModes Default = 0x1, /// - /// PowerShell script debugging including workflow script. + /// PowerShell script debugging. /// LocalScript = 0x2, /// - /// PowerShell remote script and workflow debugging. + /// PowerShell remote script debugging. /// RemoteScript = 0x4 }; @@ -3333,18 +3333,6 @@ private DebuggerCommandResults ProcessCommandForActiveDebugger(PSCommand command _lastActiveDebuggerAction = dbgCommand.ResumeAction.Value; return new DebuggerCommandResults(dbgCommand.ResumeAction, true); } - - // If active debugger is Workflow debugger then process command here (for "list" and "help"). - if (activeDebugger.GetType().FullName.Equals("Microsoft.PowerShell.Workflow.PSWorkflowDebugger", StringComparison.OrdinalIgnoreCase)) - { - DebuggerCommand results = _commandProcessor.ProcessCommand(null, commandText, stopArgs.InvocationInfo, output); - - if ((results != null) && - results.ExecutedByDebugger) - { - return new DebuggerCommandResults(results.ResumeAction, true); - } - } } return activeDebugger.ProcessCommand(command, output); @@ -3545,39 +3533,6 @@ private void HandleMonitorRunningRSDebuggerStop(object sender, DebuggerStopEvent PSMonitorRunspaceType runspaceType = nestedDebugger.RunspaceType; - // If this is a workflow debugger then ensure that there is a current active - // debugger that is the associated job debugger for this inline script WF runspace. - if (runspaceType == PSMonitorRunspaceType.WorkflowInlineScript) - { - bool needToPushAssociatedWFDebugger = true; - if (_activeDebuggers.TryPeek(out activeDebugger)) - { - needToPushAssociatedWFDebugger = (activeDebugger.InstanceId != nestedDebugger.ParentDebuggerId); - if (needToPushAssociatedWFDebugger) - { - // Pop incorrect active debugger. - PopActiveDebugger(); - } - } - - if (needToPushAssociatedWFDebugger) - { - PSJobStartEventArgs wfJobArgs = null; - lock (_syncObject) - { - _runningJobs.TryGetValue(nestedDebugger.ParentDebuggerId, out wfJobArgs); - } - - if (wfJobArgs == null) - { - Diagnostics.Assert(false, "We should never get a WF job InlineScript debugger without an associated WF parent job."); - return; - } - - PushActiveDebugger(wfJobArgs.Debugger, _jobCallStackOffset); - } - } - // Fix up invocation info script extents for embedded nested debuggers where the script source is // from the parent. args.InvocationInfo = nestedDebugger.FixupInvocationInfo(args.InvocationInfo); @@ -4239,7 +4194,7 @@ protected virtual bool HandleListCommand(PSDataCollection output) /// Attempts to fix up the debugger stop invocation information so that /// the correct stack and source can be displayed in the debugger, for /// cases where the debugged runspace is called inside a parent sccript, - /// such as with Workflow InlineScripts and script Invoke-Command cases. + /// such as with script Invoke-Command cases. /// /// /// InvocationInfo. @@ -4405,8 +4360,7 @@ private void RestoreRemoteOutput(object runningCmd) /// /// Wrapper class for runspace debugger where the runspace is being used in an - /// embedded scenario such as Workflow InlineScript or Invoke-Command command - /// inside script. + /// embedded scenario such as Invoke-Command command inside script. /// internal sealed class EmbeddedRunspaceDebugger : NestedRunspaceDebugger { @@ -4515,7 +4469,7 @@ protected override bool HandleListCommand(PSDataCollection output) /// Attempts to fix up the debugger stop invocation information so that /// the correct stack and source can be displayed in the debugger, for /// cases where the debugged runspace is called inside a parent sccript, - /// such as with Workflow InlineScripts and script Invoke-Command cases. + /// such as with script Invoke-Command cases. /// /// Invocation information from debugger stop. /// InvocationInfo. @@ -5360,65 +5314,6 @@ namespace System.Management.Automation.Internal [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Needed Internal use only")] public static class DebuggerUtils { - /// - /// Set-DebuggerVariable function. - /// - public const string SetVariableFunction = @"function Set-DebuggerVariable - { - [CmdletBinding()] - param( - [Parameter(Position=0)] - [HashTable] - $Variables - ) - - foreach($key in $Variables.Keys) - { - microsoft.powershell.utility\set-variable -Name $key -Value $Variables[$key] -Scope global - } - - Set-StrictMode -Off - }"; - - /// - /// Remove-DebuggerVariable function. - /// - public const string RemoveVariableFunction = @"function Remove-DebuggerVariable - { - [CmdletBinding()] - param( - [Parameter(Position=0)] - [string[]] - $Name - ) - - foreach ($item in $Name) - { - microsoft.powershell.utility\remove-variable -name $item -scope global - } - - Set-StrictMode -Off - }"; - - /// - /// Get-PSCallStack override function. - /// - public const string GetPSCallStackOverrideFunction = @"function Get-PSCallStack - { - [CmdletBinding()] - param() - - if ($null -ne $PSWorkflowDebugger) - { - foreach ($frame in $PSWorkflowDebugger.GetCallStack()) - { - Write-Output $frame - } - } - - Set-StrictMode -Off - }"; - internal const string SetDebugModeFunctionName = "__Set-PSDebugMode"; internal const string SetDebuggerActionFunctionName = "__Set-PSDebuggerAction"; internal const string GetDebuggerStopArgsFunctionName = "__Get-PSDebuggerStopArgs"; @@ -5453,21 +5348,6 @@ public static bool ShouldAddCommandToHistory(string command) } } - /// - /// Helper method to return an enumeration of workflow debugger - /// functions. - /// - /// - public static IEnumerable GetWorkflowDebuggerFunctions() - { - return new Collection() - { - SetVariableFunction, - RemoveVariableFunction, - GetPSCallStackOverrideFunction - }; - } - /// /// Start monitoring a runspace on the target debugger. /// @@ -5526,11 +5406,6 @@ public enum PSMonitorRunspaceType /// Runspace from remote Invoke-Command script. /// InvokeCommand, - - /// - /// Runspace from Workflow activity inline script. - /// - WorkflowInlineScript } /// diff --git a/src/System.Management.Automation/engine/lang/interface/PSToken.cs b/src/System.Management.Automation/engine/lang/interface/PSToken.cs index 712dc35ec54..49514187408 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSToken.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSToken.cs @@ -283,10 +283,6 @@ public static PSTokenType GetPSTokenType(Token token) /* Using */ PSTokenType.Keyword, /* Var */ PSTokenType.Keyword, /* While */ PSTokenType.Keyword, - /* Workflow */ PSTokenType.Keyword, - /* Parallel */ PSTokenType.Keyword, - /* Sequence */ PSTokenType.Keyword, - /* InlineScript */ PSTokenType.Keyword, /* Configuration */ PSTokenType.Keyword, /* DynamicKeyword */ PSTokenType.Keyword, /* Public */ PSTokenType.Keyword, diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index b48637cd108..f551bc936f2 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -2013,7 +2013,6 @@ private StatementAst StatementRule() break; case TokenKind.Function: case TokenKind.Filter: - case TokenKind.Workflow: statement = FunctionDeclarationRule(token); break; case TokenKind.Return: @@ -2040,10 +2039,6 @@ private StatementAst StatementRule() case TokenKind.Data: statement = DataStatementRule(token); break; - case TokenKind.Parallel: - case TokenKind.Sequence: - statement = BlockStatementRule(token); - break; case TokenKind.Configuration: statement = ConfigurationStatementRule(attributes != null ? attributes.OfType() : null, token); break; @@ -2320,45 +2315,6 @@ private StatementAst BlockStatementRule(Token kindToken) return new BlockStatementAst(ExtentOf(kindToken, body), kindToken, body); } - /// - /// Handle the InlineScript syntax in the script workflow. - /// - /// - /// - /// - /// true -- InlineScript parsing successful - /// false -- InlineScript parsing unsuccessful - /// - private bool InlineScriptRule(Token inlineScriptToken, List elements) - { - // G Command - // G InlineScript scriptblock-expression - - Diagnostics.Assert(elements != null && elements.Count == 0, "The CommandElement list should be empty"); - var commandName = new StringConstantExpressionAst(inlineScriptToken.Extent, inlineScriptToken.Text, StringConstantType.BareWord); - inlineScriptToken.TokenFlags |= TokenFlags.CommandName; - elements.Add(commandName); - - SkipNewlines(); - Token lCurly = NextToken(); - - if (lCurly.Kind != TokenKind.LCurly) - { - // ErrorRecovery: If there is no opening curly, assume it hasn't been entered yet and don't consume anything. - - UngetToken(lCurly); - ReportIncompleteInput(After(inlineScriptToken), - nameof(ParserStrings.MissingStatementAfterKeyword), - ParserStrings.MissingStatementAfterKeyword, - inlineScriptToken.Text); - return false; - } - - var expr = ScriptBlockExpressionRule(lCurly); - elements.Add(expr); - return true; - } - private StatementAst IfStatementRule(Token ifToken) { // G if-statement: @@ -2589,15 +2545,6 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke specifiedFlags.Add("casesensitive", new Tuple(switchParameterToken, null)); } } - else if (IsSpecificParameter(switchParameterToken, "parallel")) - { - flags |= SwitchFlags.Parallel; - - if (!specifiedFlags.ContainsKey("parallel")) - { - specifiedFlags.Add("parallel", new Tuple(switchParameterToken, null)); - } - } else if (IsSpecificParameter(switchParameterToken, "file")) { flags |= SwitchFlags.File; @@ -5222,7 +5169,7 @@ private StatementAst MethodDeclarationRule(Token functionNameToken, string class SetTokenizerMode(TokenizerMode.Command); ScriptBlockAst scriptBlock = ScriptBlockRule(lCurly, false, baseCtorCallStatement); var result = new FunctionDefinitionAst(ExtentOf(functionNameToken, scriptBlock), - /*isFilter:*/false, /*isWorkflow:*/false, functionNameToken, parameters, scriptBlock); + /*isFilter:*/false, functionNameToken, parameters, scriptBlock); return result; } @@ -5237,7 +5184,6 @@ private StatementAst FunctionDeclarationRule(Token functionToken) // G function-statement: // G 'function' new-lines:opt function-name function-parameter-declaration:opt '{' script-block '}' // G 'filter' new-lines:opt function-name function-parameter-declaration:opt '{' script-block '}' - // G 'workflow' new-lines:opt function-name function-parameter-declaration:opt '{' script-block '}' // G // G function-name: // G command-argument @@ -5309,26 +5255,15 @@ private StatementAst FunctionDeclarationRule(Token functionToken) } bool isFilter = functionToken.Kind == TokenKind.Filter; - bool isWorkflow = functionToken.Kind == TokenKind.Workflow; - - bool oldTokenizerWorkflowContext = _tokenizer.InWorkflowContext; - try - { - _tokenizer.InWorkflowContext = isWorkflow; - ScriptBlockAst scriptBlock = ScriptBlockRule(lCurly, isFilter); - var functionName = (functionNameToken.Kind == TokenKind.Generic) - ? ((StringToken)functionNameToken).Value - : functionNameToken.Text; + ScriptBlockAst scriptBlock = ScriptBlockRule(lCurly, isFilter); + var functionName = (functionNameToken.Kind == TokenKind.Generic) + ? ((StringToken)functionNameToken).Value + : functionNameToken.Text; - FunctionDefinitionAst result = new FunctionDefinitionAst(ExtentOf(functionToken, scriptBlock), - isFilter, isWorkflow, functionNameToken, parameters, scriptBlock); - return result; - } - finally - { - _tokenizer.InWorkflowContext = oldTokenizerWorkflowContext; - } + FunctionDefinitionAst result = new FunctionDefinitionAst(ExtentOf(functionToken, scriptBlock), + isFilter, functionNameToken, parameters, scriptBlock); + return result; } private List FunctionParameterDeclarationRule(out IScriptExtent endErrorStatement, out Token rParen) @@ -6344,42 +6279,31 @@ internal Ast CommandRule(bool forDynamicKeyword) break; default: - if (token.Kind == TokenKind.InlineScript && context == CommandArgumentContext.CommandName) - { - scanning = InlineScriptRule(token, elements); - Diagnostics.Assert(elements.Count >= 1, "We should at least have the command name: inlinescript"); - endExtent = elements.Last().Extent; + var ast = GetCommandArgument(context, token); - if (!scanning) { continue; } - } - else + // If this is the special verbatim argument syntax, look for the next element + StringToken argumentToken = token as StringToken; + if ((argumentToken != null) && string.Equals(argumentToken.Value, VERBATIM_ARGUMENT, StringComparison.OrdinalIgnoreCase)) { - var ast = GetCommandArgument(context, token); + elements.Add(ast); + endExtent = ast.Extent; - // If this is the special verbatim argument syntax, look for the next element - StringToken argumentToken = token as StringToken; - if ((argumentToken != null) && string.Equals(argumentToken.Value, VERBATIM_ARGUMENT, StringComparison.OrdinalIgnoreCase)) + var verbatimToken = GetVerbatimCommandArgumentToken(); + if (verbatimToken != null) { + foundVerbatimArgument = true; + scanning = false; + ast = new StringConstantExpressionAst(verbatimToken.Extent, verbatimToken.Value, StringConstantType.BareWord); elements.Add(ast); endExtent = ast.Extent; - - var verbatimToken = GetVerbatimCommandArgumentToken(); - if (verbatimToken != null) - { - foundVerbatimArgument = true; - scanning = false; - ast = new StringConstantExpressionAst(verbatimToken.Extent, verbatimToken.Value, StringConstantType.BareWord); - elements.Add(ast); - endExtent = ast.Extent; - } - - break; } - endExtent = ast.Extent; - elements.Add(ast); + break; } + endExtent = ast.Extent; + elements.Add(ast); + break; } diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 54c211e6043..9e158e9294e 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -443,30 +443,11 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun CheckForDuplicateParameters(functionDefinitionAst.Parameters); } - if (functionDefinitionAst.IsWorkflow) - { - _parser.ReportError(functionDefinitionAst.Extent, - nameof(ParserStrings.WorkflowNotSupportedInPowerShellCore), - ParserStrings.WorkflowNotSupportedInPowerShellCore); - } - return AstVisitAction.Continue; } public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) { - // Parallel flag not allowed - if ((switchStatementAst.Flags & SwitchFlags.Parallel) == SwitchFlags.Parallel) - { - bool reportError = !switchStatementAst.IsInWorkflow(); - if (reportError) - { - _parser.ReportError(switchStatementAst.Extent, - nameof(ParserStrings.ParallelNotSupported), - ParserStrings.ParallelNotSupported); - } - } - return AstVisitAction.Continue; } @@ -491,18 +472,6 @@ public override AstVisitAction VisitDataStatement(DataStatementAst dataStatement public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { - // Parallel flag not allowed - if ((forEachStatementAst.Flags & ForEachFlags.Parallel) == ForEachFlags.Parallel) - { - bool reportError = !forEachStatementAst.IsInWorkflow(); - if (reportError) - { - _parser.ReportError(forEachStatementAst.Extent, - nameof(ParserStrings.ParallelNotSupported), - ParserStrings.ParallelNotSupported); - } - } - // Throttle limit must be combined with Parallel flag if ((forEachStatementAst.ThrottleLimit != null) && ((forEachStatementAst.Flags & ForEachFlags.Parallel) != ForEachFlags.Parallel)) @@ -1134,11 +1103,6 @@ public override AstVisitAction VisitAttributedExpression(AttributedExpressionAst public override AstVisitAction VisitBlockStatement(BlockStatementAst blockStatementAst) { - if (blockStatementAst.IsInWorkflow()) - { - return AstVisitAction.Continue; - } - _parser.ReportError(blockStatementAst.Kind.Extent, nameof(ParserStrings.UnexpectedKeyword), ParserStrings.UnexpectedKeyword, @@ -2354,8 +2318,8 @@ public override AstVisitAction VisitBlockStatement(BlockStatementAst blockStatem { // Keyword blocks are not allowed ReportError(blockStatementAst, - nameof(ParserStrings.ParallelAndSequenceBlockNotSupportedInDataSection), - ParserStrings.ParallelAndSequenceBlockNotSupportedInDataSection); + nameof(ParserStrings.BlockStatementNotSupportedInDataSection), + ParserStrings.BlockStatementNotSupportedInDataSection); return AstVisitAction.Continue; } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 434b5a6b5e6..999d8604db3 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -288,42 +288,6 @@ internal void ClearParent() internal static PSTypeName[] EmptyPSTypeNameArray = Array.Empty(); - internal bool IsInWorkflow() - { - // Scan up the AST's parents, looking for a script block that is either - // a workflow, or has a job definition attribute. - // Stop scanning when we encounter a FunctionDefinitionAst - Ast current = this; - bool stopScanning = false; - - while (current != null && !stopScanning) - { - ScriptBlockAst scriptBlock = current as ScriptBlockAst; - if (scriptBlock != null) - { - // See if this uses the workflow keyword - FunctionDefinitionAst functionDefinition = scriptBlock.Parent as FunctionDefinitionAst; - if ((functionDefinition != null)) - { - stopScanning = true; - if (functionDefinition.IsWorkflow) { return true; } - } - } - - CommandAst commandAst = current as CommandAst; - if (commandAst != null && - string.Equals(TokenKind.InlineScript.Text(), commandAst.GetCommandName(), StringComparison.OrdinalIgnoreCase) && - this != commandAst) - { - return false; - } - - current = current.Parent; - } - - return false; - } - internal bool HasSuspiciousContent { get; set; } #region Search Ancestor Ast @@ -894,7 +858,7 @@ public ScriptBlockAst(IScriptExtent extent, /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// /// If or is null. /// @@ -913,7 +877,7 @@ public ScriptBlockAst(IScriptExtent extent, List usingStateme /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// /// If or is null. /// @@ -932,7 +896,7 @@ public ScriptBlockAst(IScriptExtent extent, ParamBlockAst paramBlock, StatementB /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// True if the script block is a configuration. /// /// If or is null. @@ -953,7 +917,7 @@ public ScriptBlockAst(IScriptExtent extent, ParamBlockAst paramBlock, StatementB /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// True if the script block is a configuration. /// /// If or is null. @@ -974,7 +938,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable using /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// True if the script block is a configuration. /// /// If or is null. @@ -996,7 +960,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable attributes /// The statements that go in the end block if is false, or the /// process block if is true. /// - /// True if the script block is a filter, false if it is a function or workflow. + /// True if the script block is a filter, false if it is a function. /// True if the script block is a configuration. /// /// If or is null. @@ -3562,7 +3526,6 @@ public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider /// The extent of the function definition, starting with the function or filter keyword, ending at the closing curly. /// /// True if the filter keyword was used. - /// True if the workflow keyword was used. /// The name of the function. /// /// The parameters specified after the function name. This does not include parameters specified with a param statement. @@ -3574,7 +3537,6 @@ public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider /// public FunctionDefinitionAst(IScriptExtent extent, bool isFilter, - bool isWorkflow, string name, IEnumerable parameters, ScriptBlockAst body) @@ -3590,13 +3552,7 @@ public FunctionDefinitionAst(IScriptExtent extent, throw PSTraceSource.NewArgumentNullException("body"); } - if (isFilter && isWorkflow) - { - throw PSTraceSource.NewArgumentException("isFilter"); - } - this.IsFilter = isFilter; - this.IsWorkflow = isWorkflow; this.Name = name; if (parameters != null && parameters.Any()) @@ -3611,13 +3567,11 @@ public FunctionDefinitionAst(IScriptExtent extent, internal FunctionDefinitionAst(IScriptExtent extent, bool isFilter, - bool isWorkflow, Token functionNameToken, IEnumerable parameters, ScriptBlockAst body) : this(extent, isFilter, - isWorkflow, (functionNameToken.Kind == TokenKind.Generic) ? ((StringToken)functionNameToken).Value : functionNameToken.Text, parameters, body) @@ -3630,11 +3584,6 @@ internal FunctionDefinitionAst(IScriptExtent extent, /// public bool IsFilter { get; private set; } - /// - /// If true, the workflow keyword was used. - /// - public bool IsWorkflow { get; private set; } - /// /// The name of the function or filter. This property is never null or empty. /// @@ -3707,7 +3656,7 @@ public override Ast Copy() var newParameters = CopyElements(this.Parameters); var newBody = CopyElement(this.Body); - return new FunctionDefinitionAst(this.Extent, this.IsFilter, this.IsWorkflow, this.Name, newParameters, newBody) { NameExtent = this.NameExtent }; + return new FunctionDefinitionAst(this.Extent, this.IsFilter, this.Name, newParameters, newBody) { NameExtent = this.NameExtent }; } internal string GetParamTextFromParameterList(Tuple, string> usingVariablesTuple = null) @@ -4589,11 +4538,6 @@ public enum SwitchFlags /// CaseSensitive = 0x10, - /// - /// The -parallel flag. - /// - Parallel = 0x20, - // If any flags are added that influence evaluation of switch elements, // then the caching strategy in SwitchClauseEvalBinder needs to be updated, // and possibly its _binderCache. @@ -7304,8 +7248,8 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } /// - /// The ast that represents a scriptblock with a keyword name. This is normally allowed only for script workflow. - /// e.g. parallel { ... } or sequence { ... }. + /// The ast that represents a scriptblock with a keyword name. + /// e.g. The parallel and sequence block statements that were deprecated along with workflow in PowerShell 7. /// public class BlockStatementAst : StatementAst { @@ -7323,7 +7267,7 @@ public BlockStatementAst(IScriptExtent extent, Token kind, StatementBlockAst bod throw PSTraceSource.NewArgumentNullException(kind == null ? "kind" : "body"); } - if (kind.Kind != TokenKind.Sequence && kind.Kind != TokenKind.Parallel) + if (!tokenKindsThatSupportBlockStatements.Contains(kind.Kind)) { throw PSTraceSource.NewArgumentException("kind"); } @@ -7333,6 +7277,10 @@ public BlockStatementAst(IScriptExtent extent, Token kind, StatementBlockAst bod SetParent(body); } + // This should remain empty until block statements are needed in PowerShell. The only tokens that supported + // them in the past were deprecated along with workflow in PowerShell 7. + private static SortedSet tokenKindsThatSupportBlockStatements = new SortedSet {}; + /// /// The scriptblockexpression that has a keyword applied to it. This property is nerver null. /// diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index def6b8d0dc1..50d8d92823f 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -516,17 +516,7 @@ public enum TokenKind /// The 'while' keyword. While = 150, - /// The 'workflow' keyword. - Workflow = 151, - - /// The 'parallel' keyword. - Parallel = 152, - - /// The 'sequence' keyword. - Sequence = 153, - - /// The 'InlineScript' keyword - InlineScript = 154, + // Keywords 151-154 were part of the workflow functionality that was removed in PowerShell 7. /// The "configuration" keyword Configuration = 155, @@ -903,10 +893,6 @@ public static class TokenTraits /* Using */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* Var */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* While */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* Workflow */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* Parallel */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* Sequence */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* InlineScript */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* Configuration */ TokenFlags.Keyword, /* */ TokenFlags.Keyword, /* Public */ TokenFlags.Keyword, @@ -1101,10 +1087,6 @@ public static class TokenTraits /* Using */ "using", /* Var */ "var", /* While */ "while", - /* Workflow */ "workflow", - /* Parallel */ "parallel", - /* Sequence */ "sequence", - /* InlineScript */ "inlinescript", /* Configuration */ "configuration", /* */ "", /* Public */ "public", @@ -1133,10 +1115,10 @@ static TokenTraits() // Some random assertions to make sure the enum and the traits are in sync Diagnostics.Assert(GetTraits(TokenKind.Begin) == (TokenFlags.Keyword | TokenFlags.ScriptBlockBlockName), "Table out of sync with enum - flags Begin"); - Diagnostics.Assert(GetTraits(TokenKind.Workflow) == (TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes), - "Table out of sync with enum - flags Workflow"); - Diagnostics.Assert(GetTraits(TokenKind.Sequence) == (TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes), - "Table out of sync with enum - flags Sequence"); + Diagnostics.Assert(GetTraits(TokenKind.While) == (TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes), + "Table out of sync with enum - flags While"); + Diagnostics.Assert(GetTraits(TokenKind.Configuration) == TokenFlags.Keyword, + "Table out of sync with enum - flags Configuration"); Diagnostics.Assert(GetTraits(TokenKind.Shr) == (TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison | TokenFlags.CanConstantFold), "Table out of sync with enum - flags Shr"); Diagnostics.Assert(s_tokenText[(int)TokenKind.Shr].Equals("-shr", StringComparison.OrdinalIgnoreCase), diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 328417a8eae..6158e242c87 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -624,11 +624,10 @@ private static readonly Dictionary s_operatorTable /*6*/ "throw", "begin", "process", "end", /*6*/ /*7*/ "dynamicparam", "function", "filter", "param", /*7*/ /*8*/ "class", "define", "var", "using", /*8*/ - /*9*/ "workflow", "parallel", "sequence", "inlinescript", /*9*/ - /*A*/ "configuration", "public", "private", "static", /*A*/ - /*B*/ "interface", "enum", "namespace", "module", /*B*/ - /*C*/ "type", "assembly", "command", "hidden", /*C*/ - /*D*/ "base", /*D*/ + /*9*/ "configuration", "public", "private", "static", /*9*/ + /*A*/ "interface", "enum", "namespace", "module", /*A*/ + /*B*/ "type", "assembly", "command", "hidden", /*B*/ + /*C*/ "base", /*C*/ }; private static readonly TokenKind[] s_keywordTokenKind = new TokenKind[] { @@ -640,11 +639,10 @@ private static readonly Dictionary s_operatorTable /*6*/ TokenKind.Throw, TokenKind.Begin, TokenKind.Process, TokenKind.End, /*6*/ /*7*/ TokenKind.Dynamicparam, TokenKind.Function, TokenKind.Filter, TokenKind.Param, /*7*/ /*8*/ TokenKind.Class, TokenKind.Define, TokenKind.Var, TokenKind.Using, /*8*/ - /*9*/ TokenKind.Workflow, TokenKind.Parallel, TokenKind.Sequence, TokenKind.InlineScript, /*9*/ - /*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/ - /*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*B*/ - /*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/ - /*D*/ TokenKind.Base, /*D*/ + /*9*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*9*/ + /*A*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*A*/ + /*B*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*B*/ + /*C*/ TokenKind.Base, /*C*/ }; internal static readonly string[] _operatorText = new string[] { @@ -722,7 +720,6 @@ internal Tokenizer(Parser parser) internal TokenizerMode Mode { get; set; } internal bool AllowSignedNumbers { get; set; } internal bool WantSimpleName { get; set; } - internal bool InWorkflowContext { get; set; } internal List TokenList { get; set; } internal Token FirstToken { get; private set; } @@ -4392,8 +4389,7 @@ private Token ScanIdentifier(char firstChar) sb = null; if (s_keywordTable.TryGetValue(ident, out tokenKind)) { - if (tokenKind != TokenKind.InlineScript || InWorkflowContext) - return NewToken(tokenKind); + return NewToken(tokenKind); } if (DynamicKeyword.ContainsKeyword(ident) && !DynamicKeyword.IsHiddenKeyword(ident)) diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index 8585d296007..a81c5efdeff 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -81,51 +81,43 @@ internal void RegisterJobSourceAdapter(Type jobSourceAdapterType) Dbg.Assert(jobSourceAdapterType != null, "JobSourceAdapterType should never be called with null value."); object instance = null; - if (jobSourceAdapterType.FullName != null && jobSourceAdapterType.FullName.EndsWith("WorkflowJobSourceAdapter", StringComparison.OrdinalIgnoreCase)) + ConstructorInfo constructor = jobSourceAdapterType.GetConstructor(Type.EmptyTypes); + if (!constructor.IsPublic) { - MethodInfo method = jobSourceAdapterType.GetMethod("GetInstance"); - instance = method.Invoke(null, null); + string message = string.Format(CultureInfo.CurrentCulture, + RemotingErrorIdStrings.JobManagerRegistrationConstructorError, + jobSourceAdapterType.FullName); + throw new InvalidOperationException(message); } - else - { - ConstructorInfo constructor = jobSourceAdapterType.GetConstructor(Type.EmptyTypes); - if (!constructor.IsPublic) - { - string message = string.Format(CultureInfo.CurrentCulture, - RemotingErrorIdStrings.JobManagerRegistrationConstructorError, - jobSourceAdapterType.FullName); - throw new InvalidOperationException(message); - } - try - { - instance = constructor.Invoke(null); - } - catch (MemberAccessException exception) - { - _tracer.TraceException(exception); - throw; - } - catch (TargetInvocationException exception) - { - _tracer.TraceException(exception); - throw; - } - catch (TargetParameterCountException exception) - { - _tracer.TraceException(exception); - throw; - } - catch (NotSupportedException exception) - { - _tracer.TraceException(exception); - throw; - } - catch (SecurityException exception) - { - _tracer.TraceException(exception); - throw; - } + try + { + instance = constructor.Invoke(null); + } + catch (MemberAccessException exception) + { + _tracer.TraceException(exception); + throw; + } + catch (TargetInvocationException exception) + { + _tracer.TraceException(exception); + throw; + } + catch (TargetParameterCountException exception) + { + _tracer.TraceException(exception); + throw; + } + catch (NotSupportedException exception) + { + _tracer.TraceException(exception); + throw; + } + catch (SecurityException exception) + { + _tracer.TraceException(exception); + throw; } if (instance != null) diff --git a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs b/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs deleted file mode 100644 index 038a8fc1763..00000000000 --- a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -namespace System.Management.Automation -{ - /// - /// Define all the output streams and one input stream for a workflow. - /// - public sealed class PowerShellStreams : IDisposable - { - /// - /// Input stream for incoming objects. - /// - private PSDataCollection _inputStream; - - /// - /// Output stream for returned objects. - /// - private PSDataCollection _outputStream; - - /// - /// Error stream for error messages. - /// - private PSDataCollection _errorStream; - - /// - /// Warning stream for warning messages. - /// - private PSDataCollection _warningStream; - - /// - /// Progress stream for progress messages. - /// - private PSDataCollection _progressStream; - - /// - /// Verbose stream for verbose messages. - /// - private PSDataCollection _verboseStream; - - /// - /// Debug stream for debug messages. - /// - private PSDataCollection _debugStream; - - /// - /// Information stream for Information messages. - /// - private PSDataCollection _informationStream; - - /// - /// If the object is already disposed or not. - /// - private bool _disposed; - - /// - /// Private object for thread-safe execution. - /// - private readonly object _syncLock = new object(); - - /// - /// Default constructor. - /// - public PowerShellStreams() - { - _inputStream = null; - _outputStream = null; - _errorStream = null; - _warningStream = null; - _progressStream = null; - _verboseStream = null; - _debugStream = null; - _informationStream = null; - - _disposed = false; - } - - /// - /// Default constructor. - /// - public PowerShellStreams(PSDataCollection pipelineInput) - { - // Populate the input collection if there is any... - _inputStream = pipelineInput ?? new PSDataCollection(); - - _inputStream.Complete(); - - _outputStream = new PSDataCollection(); - _errorStream = new PSDataCollection(); - _warningStream = new PSDataCollection(); - _progressStream = new PSDataCollection(); - _verboseStream = new PSDataCollection(); - _debugStream = new PSDataCollection(); - _informationStream = new PSDataCollection(); - - _disposed = false; - } - - /// - /// Dispose implementation. - /// - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Protected virtual implementation of Dispose. - /// - /// - private void Dispose(bool disposing) - { - if (_disposed) - return; - - lock (_syncLock) - { - if (!_disposed) - { - if (disposing) - { - _inputStream.Dispose(); - _outputStream.Dispose(); - _errorStream.Dispose(); - _warningStream.Dispose(); - _progressStream.Dispose(); - _verboseStream.Dispose(); - _debugStream.Dispose(); - _informationStream.Dispose(); - - _inputStream = null; - _outputStream = null; - _errorStream = null; - _warningStream = null; - _progressStream = null; - _verboseStream = null; - _debugStream = null; - _informationStream = null; - } - - _disposed = true; - } - } - } - - /// - /// Gets input stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection InputStream - { - get { return _inputStream; } - - set { _inputStream = value; } - } - - /// - /// Gets output stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection OutputStream - { - get { return _outputStream; } - - set { _outputStream = value; } - } - - /// - /// Gets error stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection ErrorStream - { - get { return _errorStream; } - - set { _errorStream = value; } - } - - /// - /// Gets warning stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection WarningStream - { - get { return _warningStream; } - - set { _warningStream = value; } - } - - /// - /// Gets progress stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection ProgressStream - { - get { return _progressStream; } - - set { _progressStream = value; } - } - - /// - /// Gets verbose stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection VerboseStream - { - get { return _verboseStream; } - - set { _verboseStream = value; } - } - - /// - /// Get debug stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection DebugStream - { - get { return _debugStream; } - - set { _debugStream = value; } - } - - /// - /// Gets Information stream. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public PSDataCollection InformationStream - { - get { return _informationStream; } - - set { _informationStream = value; } - } - - /// - /// Marking all the streams as completed so that no further data can be added and - /// jobs will know that there is no more data coming in. - /// - public void CloseAll() - { - if (_disposed == false) - { - lock (_syncLock) - { - if (_disposed == false) - { - _outputStream.Complete(); - _errorStream.Complete(); - _warningStream.Complete(); - _progressStream.Complete(); - _verboseStream.Complete(); - _debugStream.Complete(); - _informationStream.Complete(); - } - } - } - } - } -} diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 13f7d65c1ba..da179878ffb 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -2716,28 +2716,6 @@ function ExtractPluginProperties([string]$pluginDir, $objectToWriteTo) Get-Details $pluginDir $h - # Workflow is not supported in PowerShell 6+. Attempting to load the - # assembly results in a FileNotFoundException. - if (![System.Management.Automation.Platform]::IsCoreCLR -AND - $h[""AssemblyName""] -eq ""Microsoft.PowerShell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"") {{ - - $serviceCore = [Reflection.Assembly]::Load(""Microsoft.Powershell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"") - - if ($null -ne $serviceCore) {{ - - $ci = new-Object system.management.automation.cmdletinfo ""New-PSWorkflowExecutionOptions"", ([Microsoft.PowerShell.Commands.NewPSWorkflowExecutionOptionCommand]) - $wf = [powershell]::Create(""currentrunspace"").AddCommand($ci).Invoke() - - if($null -ne $wf -and $wf.Count -ne 0) {{ - $wf = $wf[0] - - foreach ($o in $wf.GetType().GetProperties()) {{ - $h[$o.Name] = $o.GetValue($wf, $null) - }} - }} - }} - }} - if (test-path -LiteralPath $pluginDir\InitializationParameters\SessionConfigurationData) {{ $xscd = [xml](Unescape-xml (Unescape-xml (get-item -LiteralPath $pluginDir\InitializationParameters\SessionConfigurationData).Value)) @@ -4723,12 +4701,12 @@ function Copy-PluginToEndpoint $resolvedPluginInstallPath = Resolve-Path $pluginInstallPath }} - if (!(Test-Path $resolvedPluginInstallPath\{5})) + if (!(Test-Path $resolvedPluginInstallPath\{4})) {{ - Copy-Item -Path $PSHOME\{5} -Destination $resolvedPluginInstallPath -Force -ErrorAction Stop - if (!(Test-Path $resolvedPluginInstallPath\{5})) + Copy-Item -Path $PSHOME\{4} -Destination $resolvedPluginInstallPath -Force -ErrorAction Stop + if (!(Test-Path $resolvedPluginInstallPath\{4})) {{ - Write-Error ($errorMsgUnableToInstallPlugin -f ""{5}"", $resolvedPluginInstallPath) + Write-Error ($errorMsgUnableToInstallPlugin -f ""{4}"", $resolvedPluginInstallPath) return $null }} }} @@ -4768,7 +4746,7 @@ function Register-Endpoint $null = Register-PSSessionConfiguration -Name $configurationName -force -ErrorAction Stop set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\$configurationName\Quotas\MaxShellsPerUser -value ""25"" -confirm:$false - set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\$configurationName\Quotas\MaxIdleTimeoutms -value {4} -confirm:$false + set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\$configurationName\Quotas\MaxIdleTimeoutms -value {3} -confirm:$false restart-service winrm -confirm:$false }} @@ -4855,65 +4833,6 @@ function Enable-PSRemoting Register-EndpointIfNotPresent -Name (""PowerShell."" + $powershellVersionMajor) $Force $queryForRegisterDefault $captionForRegisterDefault - # PowerShell Workflow and WOW are not supported for PowerShell 6+ - if (![System.Management.Automation.Platform]::IsCoreCLR) - {{ - # Check Microsoft.PowerShell.Workflow endpoint - $errorCount = $error.Count - $endPoint = Get-PSSessionConfiguration {0}.workflow -Force:$Force -ErrorAction silentlycontinue 2>&1 - $newErrorCount = $error.Count - - # remove the 'No Session Configuration matches criteria' errors - for ($index = 0; $index -lt ($newErrorCount - $errorCount); $index ++) - {{ - $error.RemoveAt(0) - }} - - if (!$endpoint) - {{ - $qMessage = $queryForRegisterDefault -f ""Microsoft.PowerShell.Workflow"",""Register-PSSessionConfiguration Microsoft.PowerShell.Workflow -force"" - if ($force -or $pscmdlet.ShouldProcess($qMessage, $captionForRegisterDefault)) {{ - $tempxmlfile = [io.path]::Gettempfilename() - ""{1}"" | out-file -force -filepath $tempxmlfile -confirm:$false - $null = winrm create winrm/config/plugin?Name=Microsoft.PowerShell.Workflow -file:$tempxmlfile - remove-item -path $tempxmlfile -force -confirm:$false - restart-service winrm -confirm:$false - }} - }} - - $pa = $env:PROCESSOR_ARCHITECTURE - if ($pa -eq ""x86"") - {{ - # on 64-bit platforms, wow64 bit process has the correct architecture - # available in processor_architew6432 variable - $pa = $env:PROCESSOR_ARCHITEW6432 - }} - - if ((($pa -eq ""amd64"")) -and (test-path $env:windir\syswow64\pwrshplugin.dll)) - {{ - # Check availability of WOW64 endpoint. Register if not available. - $errorCount = $error.Count - $endPoint = Get-PSSessionConfiguration {0}32 -Force:$Force -ErrorAction silentlycontinue 2>&1 - $newErrorCount = $error.Count - - # remove the 'No Session Configuration matches criteria' errors - for ($index = 0; $index -lt ($newErrorCount - $errorCount); $index ++) - {{ - $error.RemoveAt(0) - }} - - $qMessage = $queryForRegisterDefault -f ""{0}32"",""Register-PSSessionConfiguration {0}32 -processorarchitecture x86 -force"" - if ((!$endpoint) -and - ($force -or $pscmdlet.ShouldProcess($qMessage, $captionForRegisterDefault))) - {{ - $null = Register-PSSessionConfiguration {0}32 -processorarchitecture x86 -force - set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\{0}32\Quotas\MaxShellsPerUser -value ""25"" -confirm:$false - set-item -WarningAction SilentlyContinue wsman:\localhost\plugin\{0}32\Quotas\MaxIdleTimeoutms -value {4} -confirm:$false - restart-service winrm -confirm:$false - }} - }} - }} - # remove the 'network deny all' tag Get-PSSessionConfiguration -Force:$Force | ForEach-Object {{ $sddl = $null @@ -4954,12 +4873,12 @@ function Enable-PSRemoting # Remote Management Users, Win8+ only if ([System.Environment]::OSVersion.Version -ge ""6.2.0.0"") {{ - $rmSidId = new-object system.security.principal.securityidentifier ""{2}"" + $rmSidId = new-object system.security.principal.securityidentifier ""{1}"" $sd.DiscretionaryAcl.AddAccess('Allow', $rmSidId, 268435456, 'none', 'none') }} # Interactive Users - $iaSidId = new-object system.security.principal.securityidentifier ""{3}"" + $iaSidId = new-object system.security.principal.securityidentifier ""{2}"" $sd.DiscretionaryAcl.AddAccess('Allow', $iaSidId, 268435456, 'none', 'none') }} @@ -4981,44 +4900,6 @@ function Enable-PSRemoting }} # end of Enable-PSRemoting Enable-PSRemoting -force $args[0] -queryForRegisterDefault $args[1] -captionForRegisterDefault $args[2] -queryForSet $args[3] -captionForSet $args[4] -whatif:$args[5] -confirm:$args[6] -skipNetworkProfileCheck $args[7] -errorMsgUnableToInstallPlugin $args[8] -"; - - private const string _workflowConfigXml = @" - - - - - - - - - - - - - - - "; private static ScriptBlock s_enableRemotingSb; @@ -5029,15 +4910,9 @@ function Enable-PSRemoting static EnablePSRemotingCommand() { - string workflowConfigXml = string.Format(CultureInfo.InvariantCulture, _workflowConfigXml, - string.Format(CultureInfo.InvariantCulture, "{0}.{1}", PSVersionInfo.PSVersion.Major, PSVersionInfo.PSVersion.Minor), - PSSessionConfigurationCommandBase.GetLocalSddl()); - string enableRemotingScript = string.Format(CultureInfo.InvariantCulture, enableRemotingSbFormat, PSSessionConfigurationCommandUtilities.GetWinrmPluginShellName(), - // Workflow endpoint configuration will be done through Register-PSSessionConfiguration - // when the new features are available. - workflowConfigXml, PSSessionConfigurationCommandBase.RemoteManagementUsersSID, PSSessionConfigurationCommandBase.InteractiveUsersSID, + PSSessionConfigurationCommandBase.RemoteManagementUsersSID, PSSessionConfigurationCommandBase.InteractiveUsersSID, RemotingConstants.MaxIdleTimeoutMS, RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index b12680865f4..9009f3d59f5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -2411,7 +2411,7 @@ private List GetUsingVariables(ScriptBlock localScriptBlo throw new ArgumentNullException("localScriptBlock", "Caller needs to make sure the parameter value is not null"); } - var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(localScriptBlock.Ast); + var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpression(localScriptBlock.Ast); return allUsingExprs.Select(usingExpr => UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst)usingExpr)).ToList(); } diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 3a26e8eec91..79d0c20117d 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -173,7 +173,7 @@ internal static void ThrowError(ScriptBlockToPowerShellNotSupportedException ex, internal class UsingExpressionAstSearcher : AstSearcher { - internal static IEnumerable FindAllUsingExpressionExceptForWorkflow(Ast ast) + internal static IEnumerable FindAllUsingExpression(Ast ast) { Diagnostics.Assert(ast != null, "caller to verify arguments"); @@ -189,12 +189,6 @@ private UsingExpressionAstSearcher(Func callback, bool stopOnFirst, b public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst ast) { - // Skip the workflow. We are not interested in the UsingExpressions in a workflow - if (ast.IsWorkflow) - { - return AstVisitAction.SkipChildren; - } - return CheckScriptBlock(ast); } } @@ -346,7 +340,7 @@ private static Tuple, object[]> GetUsingValues(Ast bo { Diagnostics.Assert(context != null || variables != null, "can't retrieve variables with no context and no variables"); - var usingAsts = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(body).ToList(); + var usingAsts = UsingExpressionAstSearcher.FindAllUsingExpression(body).ToList(); var usingValueArray = new object[usingAsts.Count]; var usingValueMap = new Dictionary(usingAsts.Count); HashSet usingVarNames = (variables != null && filterNonUsingVariables) ? new HashSet() : null; @@ -458,10 +452,6 @@ private static Tuple, object[]> GetUsingValues(Ast bo /// /// Check if the given UsingExpression is in a different scope from the previous UsingExpression that we analyzed. /// - /// - /// Note that the value of is retrieved by calling 'UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow'. - /// So is guaranteed not inside a workflow. - /// /// The UsingExpression to analyze. /// The top level Ast, should be either ScriptBlockAst or FunctionDefinitionAst. /// The ScriptBlockAst that represents the scope of the previously analyzed UsingExpressions. diff --git a/src/System.Management.Automation/help/AliasHelpInfo.cs b/src/System.Management.Automation/help/AliasHelpInfo.cs index 7f7e13a2d27..d0fd56d0f49 100644 --- a/src/System.Management.Automation/help/AliasHelpInfo.cs +++ b/src/System.Management.Automation/help/AliasHelpInfo.cs @@ -27,7 +27,7 @@ private AliasHelpInfo(AliasInfo aliasInfo) this.ForwardTarget = name; // A Cmdlet/Function/Script etc can have alias. this.ForwardHelpCategory = HelpCategory.Cmdlet | - HelpCategory.Function | HelpCategory.ExternalScript | HelpCategory.ScriptCommand | HelpCategory.Filter | HelpCategory.Workflow; + HelpCategory.Function | HelpCategory.ExternalScript | HelpCategory.ScriptCommand | HelpCategory.Filter; if (!string.IsNullOrEmpty(aliasInfo.Name)) { diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index 11e976b8ed7..24acee030d7 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -1253,7 +1253,7 @@ private static bool Match(string target, ICollection patterns) internal override IEnumerable ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest) { HelpCategory categoriesHandled = (HelpCategory.Alias - | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand | HelpCategory.Workflow); + | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand); if ((helpInfo.HelpCategory & categoriesHandled) != 0) { diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index 76a65aab270..838676f41ce 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -499,7 +499,7 @@ private void ValidateAndThrowIfError(HelpCategory cat) // categories that support -Parameter, -Role, -Functionality, -Component parameters HelpCategory supportedCategories = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ExternalScript | - HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand | HelpCategory.Workflow; + HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand; if ((cat & supportedCategories) == 0) { diff --git a/src/System.Management.Automation/help/HelpRequest.cs b/src/System.Management.Automation/help/HelpRequest.cs index 65598ce869e..83113a4ca9d 100644 --- a/src/System.Management.Automation/help/HelpRequest.cs +++ b/src/System.Management.Automation/help/HelpRequest.cs @@ -155,7 +155,7 @@ internal void Validate() if ((!(Component == null && Role == null && Functionality == null)) && (HelpCategory == HelpCategory.None)) { - HelpCategory = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.Function | HelpCategory.Filter | HelpCategory.ExternalScript | HelpCategory.ScriptCommand | HelpCategory.Workflow; + HelpCategory = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.Function | HelpCategory.Filter | HelpCategory.ExternalScript | HelpCategory.ScriptCommand; return; } diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index a362b4723ef..3e3c4080a85 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -908,11 +908,6 @@ internal enum HelpCategory /// DefaultHelp = 0x1000, - /// - /// Help for a Workflow. - /// - Workflow = 0x2000, - /// /// Help for a Configuration. /// diff --git a/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs b/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs index 252078ba1ed..119c51d67dd 100644 --- a/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs +++ b/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs @@ -37,8 +37,7 @@ internal override HelpCategory HelpCategory HelpCategory.Filter | HelpCategory.Function | HelpCategory.Configuration | - HelpCategory.ScriptCommand | - HelpCategory.Workflow; + HelpCategory.ScriptCommand; } } diff --git a/src/System.Management.Automation/resources/Credential.resx b/src/System.Management.Automation/resources/Credential.resx index 63d780d1404..8cc61de0e5e 100644 --- a/src/System.Management.Automation/resources/Credential.resx +++ b/src/System.Management.Automation/resources/Credential.resx @@ -118,10 +118,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Cannot serialize the credential. If this command is starting a workflow, the credentials cannot be persisted, because the process in which the workflow is started does not have permission to serialize credentials. - --- If the workflow was started in a PSSession to the local computer, add the EnableNetworkAccess parameter to the command that created the session. --- If the workflow was started in a PSSession to a remote computer, add the Authentication parameter with a value of CredSSP to the command that created the session. Or, connect to a session configuration that has a RunAsUser property value. + Cannot serialize the credential. The value for UserName is not in the correct format. diff --git a/src/System.Management.Automation/resources/ErrorPackage.resx b/src/System.Management.Automation/resources/ErrorPackage.resx index 49d1e8c2fc7..b05a0efbf62 100644 --- a/src/System.Management.Automation/resources/ErrorPackage.resx +++ b/src/System.Management.Automation/resources/ErrorPackage.resx @@ -126,14 +126,6 @@ Object "{0}" is reported as an error. - - The action preference of "Suspend" is supported only for ErrorAction. - "Suspend" and ErrorAction should not be localized - - - The error action preference of "Suspend" is supported only on workflows. - "Suspend" should not be localized - it is a literal. - The value {0} is not supported for an ActionPreference variable. The provided value should be used only as a value for a preference parameter, and has been replaced by the default value. For more information, see the Help topic, "about_Preference_Variables." diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index adaa86dbcb7..3db00ba2c6a 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -392,9 +392,6 @@ Possible matches are The switch statement was incomplete. - - The '-parallel' parameter can be used only within a workflow. - Cannot process the 'switch' statement because of a missing file name argument to the -file option. @@ -911,9 +908,6 @@ The correct form is: foreach ($a in $b) {...} Missing statement body after keyword '{0}'. - - Parallel and sequence blocks are not allowed in restricted language mode or a Data section. - Unexpected keyword '{0}'. @@ -1202,9 +1196,6 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. - - Workflow is not supported in PowerShell 6+. - Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. @@ -1500,4 +1491,7 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Class keyword is not allowed in ConstrainedLanguage mode. + + Block statements are not allowed in restricted language mode or a Data section. + diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index af164017878..47398d34a1a 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -502,9 +502,6 @@ internal static string DumpLockdownState(uint pdwLockdownState) return returnValue; } - // Overrides for features that should only be enabled in debug mode - internal static bool XamlWorkflowSupported { get; set; } - /// /// Native constants for dealing with the lockdown policy. /// From c56d6d8210ccb9142ad626e73fa4a5172ab51c5c Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 18:45:04 -0300 Subject: [PATCH 19/29] CodeFactor changes --- .../engine/parser/ast.cs | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 999d8604db3..34af34315d4 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -3520,7 +3520,7 @@ public Tuple GetWithInputHandlingForInvokeCommandWithUsingExpres public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider { /// - /// Construct a function definition. + /// Initializes a new instance of the class. /// /// /// The extent of the function definition, starting with the function or filter keyword, ending at the closing curly. @@ -3535,11 +3535,15 @@ public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider /// If , , or is null, or /// if is an empty string. /// - public FunctionDefinitionAst(IScriptExtent extent, - bool isFilter, - string name, - IEnumerable parameters, - ScriptBlockAst body) + /// + /// This class represents a function definition in PowerShell. + /// + public FunctionDefinitionAst( + IScriptExtent extent, + bool isFilter, + string name, + IEnumerable parameters, + ScriptBlockAst body) : base(extent) { if (string.IsNullOrEmpty(name)) @@ -3565,16 +3569,18 @@ public FunctionDefinitionAst(IScriptExtent extent, SetParent(body); } - internal FunctionDefinitionAst(IScriptExtent extent, - bool isFilter, - Token functionNameToken, - IEnumerable parameters, - ScriptBlockAst body) - : this(extent, - isFilter, - (functionNameToken.Kind == TokenKind.Generic) ? ((StringToken)functionNameToken).Value : functionNameToken.Text, - parameters, - body) + internal FunctionDefinitionAst( + IScriptExtent extent, + bool isFilter, + Token functionNameToken, + IEnumerable parameters, + ScriptBlockAst body) + : this( + extent, + isFilter, + (functionNameToken.Kind == TokenKind.Generic) ? ((StringToken)functionNameToken).Value : functionNameToken.Text, + parameters, + body) { NameExtent = functionNameToken.Extent; } @@ -7279,7 +7285,7 @@ public BlockStatementAst(IScriptExtent extent, Token kind, StatementBlockAst bod // This should remain empty until block statements are needed in PowerShell. The only tokens that supported // them in the past were deprecated along with workflow in PowerShell 7. - private static SortedSet tokenKindsThatSupportBlockStatements = new SortedSet {}; + private static SortedSet tokenKindsThatSupportBlockStatements = new SortedSet(); /// /// The scriptblockexpression that has a keyword applied to it. This property is nerver null. From 08ba242a9f0cc9fcd7e87338ad665c19d661c98e Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 18:48:24 -0300 Subject: [PATCH 20/29] minor fix to previous commit --- src/System.Management.Automation/engine/parser/ast.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 34af34315d4..cdae0b9fbd9 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -3520,7 +3520,7 @@ public Tuple GetWithInputHandlingForInvokeCommandWithUsingExpres public class FunctionDefinitionAst : StatementAst, IParameterMetadataProvider { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// /// The extent of the function definition, starting with the function or filter keyword, ending at the closing curly. From 5d83c00c7e571b74365a79390cf339661341742e Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 22:03:37 -0300 Subject: [PATCH 21/29] add deprecated placeholders to pass asserts --- .../engine/parser/token.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index 50d8d92823f..c1f45d2ebb4 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -710,6 +710,11 @@ public enum TokenFlags /// The token is a statement but does not support attributes. /// StatementDoesntSupportAttributes = 0x01000000, + + /// + /// The token has been deprecated. + /// + Deprecated = 0x10000000, } /// @@ -893,6 +898,10 @@ public static class TokenTraits /* Using */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* Var */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* While */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, + /* Workflow */ TokenFlags.Deprecated, + /* Parallel */ TokenFlags.Deprecated, + /* Sequence */ TokenFlags.Deprecated, + /* InlineScript */ TokenFlags.Deprecated, /* Configuration */ TokenFlags.Keyword, /* */ TokenFlags.Keyword, /* Public */ TokenFlags.Keyword, @@ -1087,6 +1096,10 @@ public static class TokenTraits /* Using */ "using", /* Var */ "var", /* While */ "while", + /* Workflow */ "DEPRECATED", + /* Parallel */ "DEPRECATED", + /* Sequence */ "DEPRECATED", + /* InlineScript */ "DEPRECATED", /* Configuration */ "configuration", /* */ "", /* Public */ "public", From da3cca55f54dbcebbf78509cab07b9833383845c Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Wed, 24 Jul 2019 22:53:11 -0300 Subject: [PATCH 22/29] foreach parameter deprecation plus test cleanup --- .../engine/parser/Parser.cs | 51 +------------------ .../engine/parser/SemanticChecks.cs | 9 ---- .../engine/parser/ast.cs | 48 ----------------- .../resources/ParserStrings.resx | 8 --- .../Scripting/ActionPreference.Tests.ps1 | 45 ---------------- .../Scripting/ForeachParallel.Tests.ps1 | 33 +++--------- .../Language/Scripting/TestsOnWinFullOnly.ps1 | 32 ------------ 7 files changed, 8 insertions(+), 218 deletions(-) delete mode 100644 test/powershell/Language/Scripting/TestsOnWinFullOnly.ps1 diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index f551bc936f2..006007ab8ab 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -3222,18 +3222,9 @@ private ExpressionAst GetWordOrExpression(Token keywordToken) private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachToken) { // G foreach-statement: - // G 'foreach' new-lines:opt foreach-parameters:opt new-lines:opt '(' + // G 'foreach' new-lines:opt '(' // G new-lines:opt variable new-lines:opt 'in' new-lines:opt pipeline // G new-lines:opt ')' statement-block - // G foreach-parameters: - // G foreach-parameter - // G foreach-parameters foreach-parameter - // G foreach-parameter: - // G '-parallel' - // G '-throttlelimit' new-lines:opt foreach-throttlelimit - // G foreach-throttlelimit: - // G command-argument - // G primary-expression IScriptExtent startOfStatement = labelToken != null ? labelToken.Extent : forEachToken.Extent; IScriptExtent endErrorStatement = null; @@ -3241,45 +3232,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo SkipNewlines(); // Process parameters on foreach - Token foreachParameterToken = PeekToken(); ForEachFlags flags = ForEachFlags.None; - ExpressionAst throttleLimit = null; - - while (foreachParameterToken.Kind == TokenKind.Parameter) - { - SkipToken(); - - if (IsSpecificParameter(foreachParameterToken, "parallel")) - { - flags |= ForEachFlags.Parallel; - } - else if (IsSpecificParameter(foreachParameterToken, "throttlelimit")) - { - SkipNewlines(); - throttleLimit = GetSingleCommandArgument(CommandArgumentContext.CommandArgument); - if (throttleLimit == null) - { - // ErrorRecovery: pretend we saw the throttle limit and continue. - - ReportIncompleteInput(After(foreachParameterToken), - nameof(ParserStrings.MissingThrottleLimit), - ParserStrings.MissingThrottleLimit); - } - } - else - { - // ErrorRecovery: just ignore the token, continue parsing. - - endErrorStatement = foreachParameterToken.Extent; - ReportError(foreachParameterToken.Extent, - nameof(ParserStrings.InvalidForeachFlag), - ParserStrings.InvalidForeachFlag, - ((ParameterToken)foreachParameterToken).ParameterName); - } - - SkipNewlines(); - foreachParameterToken = PeekToken(); - } Token lParen = NextToken(); if (lParen.Kind != TokenKind.LParen) @@ -3378,7 +3331,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo return new ForEachStatementAst(ExtentOf(startOfStatement, body), labelToken != null ? labelToken.LabelText : null, flags, - throttleLimit, variableAst, pipeline, body); + variableAst, pipeline, body); } private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 9e158e9294e..b5311aa148c 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -472,15 +472,6 @@ public override AstVisitAction VisitDataStatement(DataStatementAst dataStatement public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { - // Throttle limit must be combined with Parallel flag - if ((forEachStatementAst.ThrottleLimit != null) && - ((forEachStatementAst.Flags & ForEachFlags.Parallel) != ForEachFlags.Parallel)) - { - _parser.ReportError(forEachStatementAst.Extent, - nameof(ParserStrings.ThrottleLimitRequiresParallelFlag), - ParserStrings.ThrottleLimitRequiresParallelFlag); - } - return AstVisitAction.Continue; } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index cdae0b9fbd9..ed7b0235a82 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -4117,11 +4117,6 @@ public enum ForEachFlags /// None = 0x00, - /// - /// The -parallel flag. - /// - Parallel = 0x01, - // If any flags are added that impact evaluation of items during the foreach statement, then // a binder (and caching strategy) needs to be added similar to SwitchClauseEvalBinder. } @@ -4163,47 +4158,11 @@ public ForEachStatementAst(IScriptExtent extent, SetParent(variable); } - /// - /// Construct a foreach statement. - /// - /// - /// The extent of the statement, starting from the optional label or the foreach keyword and ending at the closing curly brace. - /// - /// The optionally null label. - /// Any flags that affect how the foreach statement is processed. - /// The limit to be obeyed during parallel processing, if any. - /// The variable set on each iteration of the loop. - /// The pipeline generating values to iterate through. - /// The body to execute for each element written from pipeline. - /// - /// If , , or is null. - /// - public ForEachStatementAst(IScriptExtent extent, - string label, - ForEachFlags flags, - ExpressionAst throttleLimit, - VariableExpressionAst variable, - PipelineBaseAst expression, - StatementBlockAst body) - : this(extent, label, flags, variable, expression, body) - { - this.ThrottleLimit = throttleLimit; - if (throttleLimit != null) - { - SetParent(throttleLimit); - } - } - /// /// The name of the variable set for each item as the loop iterates. This property is never null. /// public VariableExpressionAst Variable { get; private set; } - /// - /// The limit to be obeyed during parallel processing, if any. - /// - public ExpressionAst ThrottleLimit { get; private set; } - /// /// The flags, if any specified on the foreach statement. /// @@ -4218,13 +4177,6 @@ public override Ast Copy() var newExpression = CopyElement(this.Condition); var newBody = CopyElement(this.Body); - if (this.ThrottleLimit != null) - { - var newThrottleLimit = CopyElement(this.ThrottleLimit); - return new ForEachStatementAst(this.Extent, this.Label, this.Flags, newThrottleLimit, - newVariable, newExpression, newBody); - } - return new ForEachStatementAst(this.Extent, this.Label, this.Flags, newVariable, newExpression, newBody); } diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index 3db00ba2c6a..c5e3ae359e8 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -998,14 +998,6 @@ The correct form is: foreach ($a in $b) {...} Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. - - The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. - 'ThrottleLimit' must not be localized. - - - The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. - 'ThrottleLimit' and 'Parallel' must not be localized. - The configuration block results were null or empty. Verify that configurations were defined in the block. diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index 134d4d1836d..e1f553fc373 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -43,16 +43,6 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $GLOBAL:errorActionPreference = $orgin } - It 'action preference of Suspend cannot be set as a preference variable' { - $e = { - $GLOBAL:errorActionPreference = "Suspend" - Get-Process -Name asdfasdfasdf - } | Should -Throw -ErrorId 'RuntimeException' -PassThru - $e.CategoryInfo.Reason | Should -BeExactly 'ArgumentTransformationMetadataException' - - $GLOBAL:errorActionPreference = $orgin - } - It 'enum disambiguation works' { $errorCount = $error.Count Get-Process -Name asdfasdfsadfsadf -ErrorAction Ig @@ -60,42 +50,7 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $error.Count | Should -BeExactly $errorCount } - It 'ErrorAction = Suspend works on Workflow' -Skip:$IsCoreCLR { - . .\TestsOnWinFullOnly.ps1 - Run-TestOnWinFull "ActionPreference:ErrorAction=SuspendOnWorkflow" - } - - It 'ErrorAction = Suspend does not work on functions' { - function MyHelperFunction { - [CmdletBinding()] - param() - "Hello" - } - - { MyHelperFunction -ErrorAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,MyHelperFunction" - } - - It 'ErrorAction = Suspend does not work on cmdlets' { - { Get-Process -ErrorAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" - } - - It 'WarningAction = Suspend does not work' { - { Get-Process -WarningAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" - } - #issue 2076 - It 'ErrorAction and WarningAction are the only action preferences do not support suspend' -Pending{ - $params = [System.Management.Automation.Internal.CommonParameters].GetProperties().Name | Select-String Action - - $suspendErrors = $null - $num=0 - - $params | ForEach-Object { - $input=@{'InputObject' = 'Test';$_='Suspend'} - { Write-Output @input } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.WriteOutputCommand" - } - } - It ' does not take precedence over $ErrorActionPreference' -TestCases @( @{switch="Verbose"}, @{switch="Debug"} diff --git a/test/powershell/Language/Scripting/ForeachParallel.Tests.ps1 b/test/powershell/Language/Scripting/ForeachParallel.Tests.ps1 index c0941a36269..58eaeaf68e8 100644 --- a/test/powershell/Language/Scripting/ForeachParallel.Tests.ps1 +++ b/test/powershell/Language/Scripting/ForeachParallel.Tests.ps1 @@ -2,40 +2,19 @@ # Licensed under the MIT License. Describe "Parallel foreach syntax" -Tags "CI" { - Context 'Should be able to retrieve AST of parallel foreach, error in regular case' { - $errors = @() - $ast = [System.Management.Automation.Language.Parser]::ParseInput( - 'foreach -parallel ($foo in $bar) {}', [ref] $null, [ref] $errors) - It '$errors.Count' { $errors.Count | Should -Be 1 } - It '$ast.EndBlock.Statements[0].Flags' { $ast.EndBlock.Statements[0].Flags | Should -BeExactly 'Parallel' } - } - - It 'Should be able to retrieve AST of parallel foreach, works in JobDefinition case' -Skip:$IsCoreCLR { - . .\TestsOnWinFullOnly.ps1 - Run-TestOnWinFull "ForeachParallel:ASTOfParallelForeachOnWorkflow" - } - - Context 'Supports newlines before and after' { - $errors = @() - $ast = [System.Management.Automation.Language.Parser]::ParseInput( - "foreach `n-parallel `n(`$foo in `$bar) {}", [ref] $null, [ref] $null) - It '$errors.Count' { $errors.Count | Should -Be 0 } - It '$ast.EndBlock.Statements[0].Flags' { $ast.EndBlock.Statements[0].Flags | Should -BeExactly 'Parallel' } - } - - Context 'Generates an error on invalid parameter' { + Context 'Generates an error on an arbitrary parameter' { $errors = @() $ast = [System.Management.Automation.Language.Parser]::ParseInput( 'foreach -bogus ($input in $bar) { }', [ref]$null, [ref]$errors) - It '$errors.Count' { $errors.Count | Should -Be 1 } - It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'InvalidForeachFlag' } + It '$errors.Count' { $errors.Count | Should -BeGreaterOrEqual 1 } + It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'MissingOpenParenthesisAfterKeyword' } } - Context 'Generate an error on -parallel that is not a workflow' { + Context 'Generate an error on -parallel' { $errors = @() $ast = [System.Management.Automation.Language.Parser]::ParseInput( 'foreach -parallel ($input in $bar) { }', [ref]$null, [ref]$errors) - It '$errors.Count' { $errors.Count | Should -Be 1 } - It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'ParallelNotSupported' } + It '$errors.Count' { $errors.Count | Should -BeGreaterOrEqual 1 } + It '$errors[0].ErrorId' { $errors[0].ErrorId | Should -BeExactly 'MissingOpenParenthesisAfterKeyword' } } } \ No newline at end of file diff --git a/test/powershell/Language/Scripting/TestsOnWinFullOnly.ps1 b/test/powershell/Language/Scripting/TestsOnWinFullOnly.ps1 deleted file mode 100644 index 3a273c02b8a..00000000000 --- a/test/powershell/Language/Scripting/TestsOnWinFullOnly.ps1 +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. -function Run-TestOnWinFull -{ - [CmdletBinding()] - param( [string]$name ) - - switch ($name) - { - "ActionPreference:ErrorAction=SuspendOnWorkflow" { - workflow TestErrorActionSuspend { "Hello" } - - $r = TestErrorActionSuspend -ErrorAction Suspend - - $r | Should -BeExactly 'Hello' - break; } - - "ForeachParallel:ASTOfParallelForeachOnWorkflow" { - Import-Module PSWorkflow - $errors = @() - $ast = [System.Management.Automation.Language.Parser]::ParseInput( - 'workflow foo { foreach -parallel ($foo in $bar) {} }', [ref] $null, [ref] $errors) - $errors.Count | Should -Be 0 - $ast.EndBlock.Statements[0].Body.EndBlock.Statements[0].Flags | Should -BeExactly 'Parallel' - break; - } - default { - #do nothing - } - - } -} \ No newline at end of file From 441a7b1a99e521083f9746d16c7923646f4bbf8b Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Thu, 25 Jul 2019 00:01:10 -0300 Subject: [PATCH 23/29] fix Pester test workflow references --- test/powershell/SDK/PSDebugging.Tests.ps1 | 2 +- test/powershell/engine/Api/TypeInference.Tests.ps1 | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/test/powershell/SDK/PSDebugging.Tests.ps1 b/test/powershell/SDK/PSDebugging.Tests.ps1 index f1d486a258b..5189cb5c5ec 100644 --- a/test/powershell/SDK/PSDebugging.Tests.ps1 +++ b/test/powershell/SDK/PSDebugging.Tests.ps1 @@ -187,7 +187,7 @@ Describe "Runspace Debugging API tests" -tag CI { Context "PSStandaloneMonitorRunspaceInfo tests" { BeforeAll { $runspace = [runspacefactory]::CreateRunspace() - $runspaceType = [PSMonitorRunspaceType]::WorkflowInlineScript + $runspaceType = [PSMonitorRunspaceType]::InvokeCommand $monitorInfo = [PSStandaloneMonitorRunspaceInfo]::new($runspace) $instanceId = $runspace.InstanceId $parentDebuggerId = [guid]::newguid() diff --git a/test/powershell/engine/Api/TypeInference.Tests.ps1 b/test/powershell/engine/Api/TypeInference.Tests.ps1 index c31cff4de33..7cbc899df10 100644 --- a/test/powershell/engine/Api/TypeInference.Tests.ps1 +++ b/test/powershell/engine/Api/TypeInference.Tests.ps1 @@ -591,7 +591,8 @@ Describe "Type inference Tests" -tags "CI" { $res.Name | Should -Be 'System.Int32' } - It "Infers type from block statement" { + # This test should be skipped until block statements are brought back into PowerShell + It "Infers type from block statement" -Skip:$true { $errors = $null $tokens = $null $ast = [Language.Parser]::ParseInput("parallel {1}", [ref] $tokens, [ref] $errors) From ef79b52fb1c488d29c1db9238ae17c5ba47c442f Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Thu, 25 Jul 2019 11:25:30 -0300 Subject: [PATCH 24/29] temporarily re-add IsWorkflow as dummy property --- src/System.Management.Automation/engine/parser/ast.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index ed7b0235a82..b51bdf23ed9 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -3590,6 +3590,16 @@ internal FunctionDefinitionAst( /// public bool IsFilter { get; private set; } + /// + /// Gets a value indicating whether or not the function is actually a workflow. + /// + /// + /// This property has been deprecated. It should be removed once PowerShellGet + /// is updated to check the PowerShell version before looking at the IsWorkflow + /// property. + /// + public bool IsWorkflow { get { return false; } } + /// /// The name of the function or filter. This property is never null or empty. /// From bf0ab8706278bbca565eeb3f42d7f58e19745af1 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 14:53:20 -0300 Subject: [PATCH 25/29] replace deprecated keywords; add tests --- .../engine/parser/Parser.cs | 11 +++++++ .../engine/parser/token.cs | 32 ++++++++++++------- .../engine/parser/tokenizer.cs | 18 ++++++----- .../resources/ParserStrings.resx | 3 ++ .../Language/Parser/Parsing.Tests.ps1 | 15 ++++++++- 5 files changed, 59 insertions(+), 20 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 006007ab8ab..f35e3ade481 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -2042,6 +2042,17 @@ private StatementAst StatementRule() case TokenKind.Configuration: statement = ConfigurationStatementRule(attributes != null ? attributes.OfType() : null, token); break; + case TokenKind.Workflow: + case TokenKind.Parallel: + case TokenKind.Sequence: + case TokenKind.InlineScript: + // These tokens have been deprecated. + ReportError(token.Extent, + nameof(ParserStrings.DeprecatedKeywordNotAllowed), + ParserStrings.DeprecatedKeywordNotAllowed, + token.Kind.Text()); + statement = new ErrorStatementAst(token.Extent); + break; case TokenKind.From: case TokenKind.Define: case TokenKind.Var: diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index c1f45d2ebb4..cd406e102a5 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -516,8 +516,18 @@ public enum TokenKind /// The 'while' keyword. While = 150, - // Keywords 151-154 were part of the workflow functionality that was removed in PowerShell 7. + /// The 'workflow' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. + Workflow = 151, + /// The 'parallel' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. + Parallel = 152, + + /// The 'sequence' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. + Sequence = 153, + + /// The 'InlineScript' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. + InlineScript = 154, + /// The "configuration" keyword Configuration = 155, @@ -898,10 +908,10 @@ public static class TokenTraits /* Using */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* Var */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, /* While */ TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes, - /* Workflow */ TokenFlags.Deprecated, - /* Parallel */ TokenFlags.Deprecated, - /* Sequence */ TokenFlags.Deprecated, - /* InlineScript */ TokenFlags.Deprecated, + /* Workflow */ TokenFlags.Keyword | TokenFlags.Deprecated, + /* Parallel */ TokenFlags.Keyword | TokenFlags.Deprecated, + /* Sequence */ TokenFlags.Keyword | TokenFlags.Deprecated, + /* InlineScript */ TokenFlags.Keyword | TokenFlags.Deprecated, /* Configuration */ TokenFlags.Keyword, /* */ TokenFlags.Keyword, /* Public */ TokenFlags.Keyword, @@ -1096,10 +1106,10 @@ public static class TokenTraits /* Using */ "using", /* Var */ "var", /* While */ "while", - /* Workflow */ "DEPRECATED", - /* Parallel */ "DEPRECATED", - /* Sequence */ "DEPRECATED", - /* InlineScript */ "DEPRECATED", + /* Workflow */ "workflow", + /* Parallel */ "parallel", + /* Sequence */ "sequence", + /* InlineScript */ "inlinescript", /* Configuration */ "configuration", /* */ "", /* Public */ "public", @@ -1128,8 +1138,8 @@ static TokenTraits() // Some random assertions to make sure the enum and the traits are in sync Diagnostics.Assert(GetTraits(TokenKind.Begin) == (TokenFlags.Keyword | TokenFlags.ScriptBlockBlockName), "Table out of sync with enum - flags Begin"); - Diagnostics.Assert(GetTraits(TokenKind.While) == (TokenFlags.Keyword | TokenFlags.StatementDoesntSupportAttributes), - "Table out of sync with enum - flags While"); + Diagnostics.Assert(GetTraits(TokenKind.Workflow) == (TokenFlags.Keyword | TokenFlags.Deprecated), + "Table out of sync with enum - flags Workflow"); Diagnostics.Assert(GetTraits(TokenKind.Configuration) == TokenFlags.Keyword, "Table out of sync with enum - flags Configuration"); Diagnostics.Assert(GetTraits(TokenKind.Shr) == (TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison | TokenFlags.CanConstantFold), diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 6158e242c87..93001c4147c 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -624,10 +624,11 @@ private static readonly Dictionary s_operatorTable /*6*/ "throw", "begin", "process", "end", /*6*/ /*7*/ "dynamicparam", "function", "filter", "param", /*7*/ /*8*/ "class", "define", "var", "using", /*8*/ - /*9*/ "configuration", "public", "private", "static", /*9*/ - /*A*/ "interface", "enum", "namespace", "module", /*A*/ - /*B*/ "type", "assembly", "command", "hidden", /*B*/ - /*C*/ "base", /*C*/ + /*9*/ "workflow", "parallel", "sequence", "inlinescript", /*9*/ + /*A*/ "configuration", "public", "private", "static", /*A*/ + /*B*/ "interface", "enum", "namespace", "module", /*B*/ + /*C*/ "type", "assembly", "command", "hidden", /*C*/ + /*D*/ "base", /*D*/ }; private static readonly TokenKind[] s_keywordTokenKind = new TokenKind[] { @@ -639,10 +640,11 @@ private static readonly Dictionary s_operatorTable /*6*/ TokenKind.Throw, TokenKind.Begin, TokenKind.Process, TokenKind.End, /*6*/ /*7*/ TokenKind.Dynamicparam, TokenKind.Function, TokenKind.Filter, TokenKind.Param, /*7*/ /*8*/ TokenKind.Class, TokenKind.Define, TokenKind.Var, TokenKind.Using, /*8*/ - /*9*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*9*/ - /*A*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*A*/ - /*B*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*B*/ - /*C*/ TokenKind.Base, /*C*/ + /*9*/ TokenKind.Workflow, TokenKind.Parallel, TokenKind.Sequence, TokenKind.InlineScript, /*9*/ + /*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/ + /*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*B*/ + /*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/ + /*D*/ TokenKind.Base, }; internal static readonly string[] _operatorText = new string[] { diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index c5e3ae359e8..96e70a39cdd 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -466,6 +466,9 @@ The correct form is: foreach ($a in $b) {...} The '{0}' keyword is not supported in this version of the language. + + The '{0}' keyword has been deprecated and is no longer supported. + Missing expression after '{0}' in loop. diff --git a/test/powershell/Language/Parser/Parsing.Tests.ps1 b/test/powershell/Language/Parser/Parsing.Tests.ps1 index afb15081124..10957fd364b 100644 --- a/test/powershell/Language/Parser/Parsing.Tests.ps1 +++ b/test/powershell/Language/Parser/Parsing.Tests.ps1 @@ -2,10 +2,23 @@ # Licensed under the MIT License. set-strictmode -v 2 +Describe 'reserved keyword parsing' -Tags 'CI' { + ShouldBeParseError 'from' ReservedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'define' ReservedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'var' ReservedKeywordNotAllowed 1 -CheckColumnNumber +} + +Describe 'deprecated keyword parsing' -Tags 'CI' { + ShouldBeParseError 'workflow' DeprecatedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'parallel' DeprecatedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'sequence' DeprecatedKeywordNotAllowed 1 -CheckColumnNumber + ShouldBeParseError 'inlinescript' DeprecatedKeywordNotAllowed 1 -CheckColumnNumber +} + Describe 'for statement parsing' -Tags "CI" { ShouldBeParseError 'for' MissingOpenParenthesisAfterKeyword 4 -CheckColumnNumber ShouldBeParseError 'for(' MissingEndParenthesisAfterStatement 5 -CheckColumnNumber - ShouldBeParseError 'for(;' MissingEndParenthesisAfterStatement 6 -CheckColumnNumber + ShouldBeParseError 'for(; ' MissingEndParenthesisAfterStatement 6 -CheckColumnNumber ShouldBeParseError 'for(;;' MissingEndParenthesisAfterStatement 7 -CheckColumnNumber ShouldBeParseError 'for($a' MissingEndParenthesisAfterStatement 7 -CheckColumnNumber ShouldBeParseError 'for($a;' MissingEndParenthesisAfterStatement 8 -CheckColumnNumber From 225c5dce789728df239a24c6381db945dcdadbfe Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 14:57:58 -0300 Subject: [PATCH 26/29] remove extra whitespace, add missing comment --- src/System.Management.Automation/engine/parser/token.cs | 2 +- src/System.Management.Automation/engine/parser/tokenizer.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index cd406e102a5..0351167af1c 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -527,7 +527,7 @@ public enum TokenKind /// The 'InlineScript' keyword. This keyword was part of workflow functionality that was deprecated in PowerShell 7. InlineScript = 154, - + /// The "configuration" keyword Configuration = 155, diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 93001c4147c..6f839bd189e 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -644,7 +644,7 @@ private static readonly Dictionary s_operatorTable /*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/ /*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*B*/ /*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/ - /*D*/ TokenKind.Base, + /*D*/ TokenKind.Base, /*D*/ }; internal static readonly string[] _operatorText = new string[] { From 6c85f04db10e0017a6c9c237774c1ae52febc312 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 14:59:39 -0300 Subject: [PATCH 27/29] remove unintentional space --- test/powershell/Language/Parser/Parsing.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/Language/Parser/Parsing.Tests.ps1 b/test/powershell/Language/Parser/Parsing.Tests.ps1 index 10957fd364b..96b899f0fd4 100644 --- a/test/powershell/Language/Parser/Parsing.Tests.ps1 +++ b/test/powershell/Language/Parser/Parsing.Tests.ps1 @@ -18,7 +18,7 @@ Describe 'deprecated keyword parsing' -Tags 'CI' { Describe 'for statement parsing' -Tags "CI" { ShouldBeParseError 'for' MissingOpenParenthesisAfterKeyword 4 -CheckColumnNumber ShouldBeParseError 'for(' MissingEndParenthesisAfterStatement 5 -CheckColumnNumber - ShouldBeParseError 'for(; ' MissingEndParenthesisAfterStatement 6 -CheckColumnNumber + ShouldBeParseError 'for(;' MissingEndParenthesisAfterStatement 6 -CheckColumnNumber ShouldBeParseError 'for(;;' MissingEndParenthesisAfterStatement 7 -CheckColumnNumber ShouldBeParseError 'for($a' MissingEndParenthesisAfterStatement 7 -CheckColumnNumber ShouldBeParseError 'for($a;' MissingEndParenthesisAfterStatement 8 -CheckColumnNumber From 8c2ac0ce2122e5613f0c9ca600b1c619d5614286 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 15:04:04 -0300 Subject: [PATCH 28/29] CodeFactor cleanup --- .../engine/parser/Parser.cs | 15 ++++++++----- .../remoting/commands/CustomShellCommands.cs | 22 +++++++++---------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index f35e3ade481..fbf54cd144d 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -1966,7 +1966,8 @@ private StatementAst StatementRule() } else { - ReportError(attributes[0].Extent, + ReportError( + attributes[0].Extent, nameof(ParserStrings.UnexpectedAttribute), ParserStrings.UnexpectedAttribute, attributes[0].TypeName.FullName); @@ -1976,7 +1977,8 @@ private StatementAst StatementRule() { foreach (var attr in attributes.Where(attr => !(attr is AttributeAst))) { - ReportError(attr.Extent, + ReportError( + attr.Extent, nameof(ParserStrings.TypeNotAllowedBeforeStatement), ParserStrings.TypeNotAllowedBeforeStatement, attr.TypeName.FullName); @@ -2047,7 +2049,8 @@ private StatementAst StatementRule() case TokenKind.Sequence: case TokenKind.InlineScript: // These tokens have been deprecated. - ReportError(token.Extent, + ReportError( + token.Extent, nameof(ParserStrings.DeprecatedKeywordNotAllowed), ParserStrings.DeprecatedKeywordNotAllowed, token.Kind.Text()); @@ -2056,7 +2059,8 @@ private StatementAst StatementRule() case TokenKind.From: case TokenKind.Define: case TokenKind.Var: - ReportError(token.Extent, + ReportError( + token.Extent, nameof(ParserStrings.ReservedKeywordNotAllowed), ParserStrings.ReservedKeywordNotAllowed, token.Kind.Text()); @@ -2106,7 +2110,8 @@ private StatementAst StatementRule() case TokenKind.Using: statement = UsingStatementRule(token); // Report an error - usings must appear before anything else in the script, but parse it anyway - ReportError(statement.Extent, + ReportError( + statement.Extent, nameof(ParserStrings.UsingMustBeAtStartOfScript), ParserStrings.UsingMustBeAtStartOfScript); break; diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index da179878ffb..170d8cc2a0a 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -4,25 +4,23 @@ using System; using System.Collections; using System.Collections.ObjectModel; +using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Security.AccessControl; -using System.Text; -using System.Threading; - using System.Management.Automation; using System.Management.Automation.Internal; -using System.Management.Automation.Runspaces; -using System.Management.Automation.Remoting; using System.Management.Automation.Language; - +using System.Management.Automation.Remoting; +using System.Management.Automation.Runspaces; +using System.Security; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Text; +using System.Threading; using Dbg = System.Management.Automation.Diagnostics; -using WSManNativeApi = System.Management.Automation.Remoting.Client.WSManNativeApi; using PowerShellApi = System.Management.Automation.PowerShell; +using WSManNativeApi = System.Management.Automation.Remoting.Client.WSManNativeApi; -using System.Security; -using System.Collections.Generic; -using System.Security.Principal; namespace Microsoft.PowerShell.Commands { @@ -1051,6 +1049,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d maxObjectSizeMB.Value, Environment.NewLine)); } + if (threadAptState.HasValue) { initParameters.Append(string.Format(CultureInfo.InvariantCulture, @@ -1059,6 +1058,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d threadAptState.Value, Environment.NewLine)); } + if (threadOptions.HasValue) { initParameters.Append(string.Format(CultureInfo.InvariantCulture, From 2ab5d28a9cb326f13c272b94b0b02d011a2df552 Mon Sep 17 00:00:00 2001 From: Kirk Munro Date: Sun, 4 Aug 2019 15:05:02 -0300 Subject: [PATCH 29/29] CodeFactor cleanup --- .../engine/remoting/commands/CustomShellCommands.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 170d8cc2a0a..c2369772e31 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -21,7 +21,6 @@ using PowerShellApi = System.Management.Automation.PowerShell; using WSManNativeApi = System.Management.Automation.Remoting.Client.WSManNativeApi; - namespace Microsoft.PowerShell.Commands { #region Register-PSSessionConfiguration cmdlet