From 28cdd173f321be9a773734b294473fa8135904d7 Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Thu, 30 Jul 2026 19:06:36 -0400 Subject: [PATCH 01/20] Add Directory.Parse.config to skip unknown attributes/elements during parsing Introduces a configuration mechanism that allows specific unrecognized attributes or child elements to be silently skipped during project file parsing instead of throwing InvalidProjectFileException. Configuration is loaded additively from: - Next to the MSBuild executable - User profile (~/.msbuild/) - MSBUILD_PARSE_CONFIG environment variable - Walk up from startup directory (BuildManager) or project directory (evaluation) The config is centralized on BuildParameters, serialized to worker nodes via ITranslatable, and threaded through ProjectRootElementCache -> ProjectParser -> ProjectXmlUtilities. Set MSBUILD_DISABLE_PARSE_CONFIG=1 to disable. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- documentation/specs/directory-parse-config.md | 129 +++++++ .../UnknownElementsConfiguration_Tests.cs | 274 +++++++++++++++ .../BackEnd/BuildManager/BuildManager.cs | 6 + .../BackEnd/BuildManager/BuildParameters.cs | 19 + src/Build/Construction/ProjectRootElement.cs | 12 +- src/Build/Definition/ProjectCollection.cs | 23 ++ src/Build/Evaluation/Evaluator.cs | 47 +++ src/Build/Evaluation/ProjectParser.cs | 101 ++++-- .../Evaluation/ProjectRootElementCacheBase.cs | 2 + .../UnknownElementsConfiguration.cs | 326 ++++++++++++++++++ src/Build/Microsoft.Build.csproj | 1 + ...ectXmlUtilities.XmlElementChildIterator.cs | 4 +- src/Build/Xml/ProjectXmlUtilities.cs | 54 ++- src/Framework/Traits.cs | 7 + 14 files changed, 950 insertions(+), 55 deletions(-) create mode 100644 documentation/specs/directory-parse-config.md create mode 100644 src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs create mode 100644 src/Build/Evaluation/UnknownElementsConfiguration.cs diff --git a/documentation/specs/directory-parse-config.md b/documentation/specs/directory-parse-config.md new file mode 100644 index 00000000000..73cbcd9c444 --- /dev/null +++ b/documentation/specs/directory-parse-config.md @@ -0,0 +1,129 @@ +# Directory.Parse.config — Ignoring Unexpected Attributes and Elements + +## Summary + +MSBuild now supports a configuration file (`Directory.Parse.config`) that allows specific unrecognized attributes or child elements to be silently skipped during project parsing, instead of throwing `InvalidProjectFileException` (MSB4066/MSB4067). + +This enables compatibility scenarios where project files may include attributes/elements intended for newer MSBuild versions or third-party tools that can still build without those attributes/elements. + +## Configuration File Format + +`Directory.Parse.config` is a plain text file with one entry per line: + +``` +# Lines starting with # are comments +# Empty lines are ignored + +# Format: Type:Name:AllowedName +Attribute:Target:CustomAttr +Element:Project:CustomElement +Attribute:PropertyGroup:NewFeatureFlag +``` + +- **Type**: Either `Attribute` or `Element` (case-insensitive) +- **Name**: `Attribute`: the name/type of the element; `Element`: the name/type of the parent element +- **AllowedName**: The name of the attribute or child element to allow + +Matching is case-insensitive. +Invalid lines (wrong format, unknown type, wrong number of colons) are silently ignored. + +For more details on `Name`: + +### Valid Attribute Names + +For attributes the `Name` can be the name of the following MSBuild elements: +- `Target` +- `PropertyGroup` +- `ItemGroup` +- `Import` +- `ImportGroup` +- `UsingTask` +- `OnError` +- `Output` +- `Choose` +- `Otherwise` +- `ProjectExtensions` + +Although the following are not elements, they can be specified to target attributes on these types of elements: +- `Property`: attributes on elements inside a `PropertyGroup` +- `Item`: attributes on elements inside a `ItemGroup` +- `Metadata`: attributes on elements inside an `Item` or `ItemDefinitionGroup` +- `Parameter`: attributes on elements in a ParameterGroup inside a UsingTask +- `UsingTaskBody`: attributes on Task elements inside a UsingTask + +### Valid Element Names + +The following names can be specified: +- `Project` +- `Import` +- `ImportGroup` +- `UsingTask` +- `OnError` +- `Output` +- `Choose` +- `When` +- `Otherwise` + +The following cannot be specified since their children are by definition always valid: +- `Target` +- `PropertyGroup` +- `ItemGroup` +- `ProjectExtensions` + +## Discovery and Loading + +Configuration files are discovered and merged additively: + +1. **Global config at build start** + - Next to the MSBuild executable + - User profile: `%USERPROFILE%\.msbuild\Directory.Parse.config` (Windows) or `$HOME/.msbuild/Directory.Parse.config` (Unix) + - Paths listed in `MSBUILD_PARSE_CONFIG`, split using the platform path separator + - The startup directory of MSBuild + +2. **Directory-specific config at evaluation start** + - MSBuild walks up from the project file's directory looking for `Directory.Parse.config` + - If found and that file was not already loaded globally, it is loaded and merged for that evaluation + +## Centralized Loading (BuildManager) + +In a normal build flow, the main node loads global config once during `BuildManager.BeginBuild()`. The config is: +- Stored on `BuildParameters.UnknownElementsConfiguration` +- Serialized to worker nodes via the standard `ITranslatable` mechanism +- Set on the shared `ProjectRootElementCache`, so parsing uses the same configuration + +At evaluation start, MSBuild may merge in one additional `Directory.Parse.config` discovered from the project file's directory walk. + +Users of the `ProjectCollection` API can also set `ProjectCollection.UnknownElementsConfiguration` directly, which flows into `BuildParameters` when builds are started. + +## Logging + +During evaluation, two low-importance messages can be logged to the binary log: + +- **Config files loaded**: Lists all discovered and loaded config file paths. +- **Skipped items summary**: Lists all unrecognized attributes/elements that were skipped, with occurrence counts. This is logged after evaluation work has completed so it reflects actual skips from that evaluation. + +Example log messages: +``` +Loaded Directory.Parse.config from: C:\repo\Directory.Parse.config, C:\Users\me\.msbuild\Directory.Parse.config +Skipped unrecognized items allowed by Directory.Parse.config: Attribute:Target:CustomAttr (2 occurrences); Element:Project:Widget (1 occurrence) +``` + +## Examples + +### Allow a custom attribute on Target elements + +Directory.Parse.config: +``` +Attribute:Target:CustomAttr +``` + +This allows `` without error. + +### Allow a custom child element under Project + +Directory.Parse.config: +``` +Element:Project:ToolConfiguration +``` + +This allows `` as a direct child of `` without error. diff --git a/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs b/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs new file mode 100644 index 00000000000..16cb7672d1c --- /dev/null +++ b/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs @@ -0,0 +1,274 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.IO; +using Microsoft.Build.Exceptions; +using Microsoft.Build.Evaluation; +using Shouldly; +using Xunit; + +#nullable disable + +namespace Microsoft.Build.UnitTests.Evaluation +{ + public class UnknownElementsConfiguration_Tests : IDisposable + { + private readonly string _testDir; + + public UnknownElementsConfiguration_Tests() + { + _testDir = Path.Combine(Path.GetTempPath(), "MSBuildTest_UnknownElements_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_testDir); + } + + public void Dispose() + { + if (Directory.Exists(_testDir)) + { + Directory.Delete(_testDir, recursive: true); + } + } + + [Fact] + public void ParsesValidConfigFile() + { + string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + File.WriteAllText(configPath, @" +# This is a comment +Attribute:Target:Foo +Element:Project:CustomThing + +Attribute:PropertyGroup:Bar +"); + + var config = UnknownElementsConfiguration.LoadFromFile(configPath); + + config.LoadedConfigFiles.Count.ShouldBe(1); + config.CheckSkipAttribute("Target", "Foo").ShouldBeTrue(); + config.CheckSkipElement("Project", "CustomThing").ShouldBeTrue(); + config.CheckSkipAttribute("PropertyGroup", "Bar").ShouldBeTrue(); + } + + [Fact] + public void IsCaseInsensitive() + { + string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + + var config = UnknownElementsConfiguration.LoadFromFile(configPath); + + config.CheckSkipAttribute("target", "foo").ShouldBeTrue(); + config.CheckSkipAttribute("TARGET", "FOO").ShouldBeTrue(); + config.CheckSkipAttribute("Target", "Foo").ShouldBeTrue(); + } + + [Fact] + public void RejectsNonAllowedItems() + { + string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + + var config = UnknownElementsConfiguration.LoadFromFile(configPath); + + config.CheckSkipAttribute("Target", "Bar").ShouldBeFalse(); + config.CheckSkipElement("Target", "Foo").ShouldBeFalse(); + config.CheckSkipAttribute("ItemGroup", "Foo").ShouldBeFalse(); + } + + [Fact] + public void IgnoresInvalidLines() + { + string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + File.WriteAllText(configPath, @" +# Comment +InvalidType:Target:Foo +Attribute:Target +Attribute +:Target:Foo +Attribute:Target:Foo:ExtraColon +Attribute:Target:ValidOne +"); + + var config = UnknownElementsConfiguration.LoadFromFile(configPath); + + config.CheckSkipAttribute("Target", "ValidOne").ShouldBeTrue(); + config.CheckSkipAttribute("Target", "Foo").ShouldBeFalse(); + } + + [Fact] + public void ReturnsEmptyWhenNoConfigExists() + { + var config = UnknownElementsConfiguration.LoadFromFile(Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName)); + + config.LoadedConfigFiles.Count.ShouldBe(0); + config.CheckSkipAttribute("Target", "Foo").ShouldBeFalse(); + } + + [Fact] + public void MergeCombinesEntriesAndDeduplicatesFiles() + { + string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + + string extraConfigPath = Path.Combine(_testDir, "extra.config"); + File.WriteAllText(extraConfigPath, "Element:Project:CustomThing\n"); + + var merged = UnknownElementsConfiguration.LoadFromFile(configPath) + .Merge(UnknownElementsConfiguration.LoadFromFile(extraConfigPath)) + .Merge(UnknownElementsConfiguration.LoadFromFile(configPath)); + + merged.CheckSkipAttribute("Target", "Foo").ShouldBeTrue(); + merged.CheckSkipElement("Project", "CustomThing").ShouldBeTrue(); + merged.LoadedConfigFiles.Count.ShouldBe(2); + } + + [Fact] + public void LoadGlobalConfigLoadsEnvironmentVariablePaths() + { + string envConfigPath = Path.Combine(_testDir, "env.config"); + File.WriteAllText(envConfigPath, "Element:Project:CustomThing\n"); + + string oldEnv = Environment.GetEnvironmentVariable(UnknownElementsConfiguration.EnvironmentVariableName); + try + { + Environment.SetEnvironmentVariable(UnknownElementsConfiguration.EnvironmentVariableName, envConfigPath); + var config = UnknownElementsConfiguration.LoadGlobalConfig(); + + config.CheckSkipElement("Project", "CustomThing").ShouldBeTrue(); + } + finally + { + Environment.SetEnvironmentVariable(UnknownElementsConfiguration.EnvironmentVariableName, oldEnv); + } + } + + [Fact] + public void RecordsSkippedItems() + { + string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + + var config = UnknownElementsConfiguration.LoadFromFile(configPath); + + config.GetSkippedSummaryMessage().ShouldBeNull(); + + config.CheckSkipAttribute("Target", "Foo"); + config.CheckSkipAttribute("Target", "Foo"); + + string summary = config.GetSkippedSummaryMessage(); + summary.ShouldNotBeNull(); + summary.ShouldContain("Attribute:Target:Foo"); + summary.ShouldContain("2 occurrences"); + } + + [Fact] + public void GetLoadedConfigsMessageReturnsNullWhenEmpty() + { + var config = UnknownElementsConfiguration.LoadFromFile(Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName)); + config.GetLoadedConfigsMessage().ShouldBeNull(); + } + + [Fact] + public void GetLoadedConfigsMessageListsFiles() + { + string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + + var config = UnknownElementsConfiguration.LoadFromFile(configPath); + + string message = config.GetLoadedConfigsMessage(); + message.ShouldNotBeNull(); + message.ShouldContain(_testDir); + } + + [Fact] + public void AllowedAttributeDoesNotThrowDuringParsing() + { + string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + File.WriteAllText(configPath, "Attribute:Target:CustomAttr\n"); + + string projectContent = @" + + + +"; + + string projectFile = Path.Combine(_testDir, "test.proj"); + File.WriteAllText(projectFile, projectContent); + + using (var projectCollection = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(configPath))) + { + var project = new Project(projectFile, null, null, projectCollection); + project.ShouldNotBeNull(); + } + } + + [Fact] + public void NonAllowedAttributeStillThrows() + { + string projectContent = @" + + + +"; + + string projectFile = Path.Combine(_testDir, "test.proj"); + File.WriteAllText(projectFile, projectContent); + + using (var projectCollection = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName)))) + { + Should.Throw(() => new Project(projectFile, null, null, projectCollection)); + } + } + + [Fact] + public void AllowedChildElementDoesNotThrowDuringParsing() + { + string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + File.WriteAllText(configPath, "Element:Project:CustomElement\n"); + + string projectContent = @" + + + + +"; + + string projectFile = Path.Combine(_testDir, "test.proj"); + File.WriteAllText(projectFile, projectContent); + + using (var projectCollection = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(configPath))) + { + var project = new Project(projectFile, null, null, projectCollection); + project.ShouldNotBeNull(); + } + } + + [Fact] + public void NonAllowedChildElementStillThrows() + { + string projectContent = @" + + + + +"; + + string projectFile = Path.Combine(_testDir, "test.proj"); + File.WriteAllText(projectFile, projectContent); + + using (var projectCollection = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName)))) + { + Should.Throw(() => new Project(projectFile, null, null, projectCollection)); + } + } + + private static ProjectCollection CreateProjectCollection(UnknownElementsConfiguration config) + { + var projectCollection = new ProjectCollection(); + projectCollection.UnknownElementsConfiguration = config; + return projectCollection; + } + } +} diff --git a/src/Build/BackEnd/BuildManager/BuildManager.cs b/src/Build/BackEnd/BuildManager/BuildManager.cs index 2a4eaefea24..212c584a806 100644 --- a/src/Build/BackEnd/BuildManager/BuildManager.cs +++ b/src/Build/BackEnd/BuildManager/BuildManager.cs @@ -618,6 +618,12 @@ public void BeginBuild(BuildParameters parameters) // Initialize additional build parameters. _buildParameters.BuildId = GetNextBuildId(); + if (_buildParameters.UnknownElementsConfiguration is null && !Traits.Instance.EscapeHatches.DisableParseConfig) + { + _buildParameters.UnknownElementsConfiguration = UnknownElementsConfiguration.LoadGlobalConfig(BuildParameters.StartupDirectory); + _buildParameters.ProjectRootElementCache.UnknownElementsConfiguration = _buildParameters.UnknownElementsConfiguration; + } + if (_buildParameters.UsesCachedResults() && _buildParameters.ProjectIsolationMode == ProjectIsolationMode.False) { // If input or output caches are used and the project isolation mode is set to diff --git a/src/Build/BackEnd/BuildManager/BuildParameters.cs b/src/Build/BackEnd/BuildManager/BuildParameters.cs index 4e6733aec3e..a110cf50b92 100644 --- a/src/Build/BackEnd/BuildManager/BuildParameters.cs +++ b/src/Build/BackEnd/BuildManager/BuildParameters.cs @@ -236,6 +236,12 @@ public class BuildParameters : ITranslatable private bool _reportFileAccesses; + /// + /// The configuration for allowed unknown attributes/elements during parsing. + /// Loaded on the main node and serialized to worker nodes. + /// + private UnknownElementsConfiguration _unknownElementsConfiguration; + /// /// Constructor for those who intend to set all properties themselves. /// @@ -262,6 +268,7 @@ public BuildParameters(ProjectCollection projectCollection) _globalProperties = new PropertyDictionary(projectCollection.GlobalPropertiesCollection); _propertiesFromCommandLine = projectCollection.PropertiesFromCommandLine; + _unknownElementsConfiguration = projectCollection.UnknownElementsConfiguration; } /// @@ -330,6 +337,7 @@ internal BuildParameters(BuildParameters other, bool resetEnvironment = false) IsTelemetryEnabled = other.IsTelemetryEnabled; ProjectCacheDescriptor = other.ProjectCacheDescriptor; _enableTargetOutputLogging = other.EnableTargetOutputLogging; + _unknownElementsConfiguration = other._unknownElementsConfiguration; } /// @@ -822,6 +830,16 @@ public ProjectLoadSettings ProjectLoadSettings set => _projectLoadSettings = value; } + /// + /// Gets or sets the configuration for allowed unknown attributes/elements during parsing. + /// When set, this configuration is used for parsing and evaluation. + /// + internal UnknownElementsConfiguration UnknownElementsConfiguration + { + get => _unknownElementsConfiguration; + set => _unknownElementsConfiguration = value; + } + /// /// Gets or sets a value indicating if the build is allowed to interact with the user. /// @@ -994,6 +1012,7 @@ void ITranslatable.Translate(ITranslator translator) translator.Translate(ref _reportFileAccesses); translator.Translate(ref _enableTargetOutputLogging); translator.Translate(ref _multiThreaded); + translator.Translate(ref _unknownElementsConfiguration, UnknownElementsConfiguration.FactoryForDeserialization); // ProjectRootElementCache is not transmitted. // ResetCaches is not transmitted. diff --git a/src/Build/Construction/ProjectRootElement.cs b/src/Build/Construction/ProjectRootElement.cs index ca5e64245be..b6f0e1350d4 100644 --- a/src/Build/Construction/ProjectRootElement.cs +++ b/src/Build/Construction/ProjectRootElement.cs @@ -181,7 +181,7 @@ internal ProjectRootElement(XmlReader xmlReader, ProjectRootElementCacheBase pro XmlDocumentWithLocation document = LoadDocument(xmlReader, preserveFormatting); - ProjectParser.Parse(document, this); + ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); } private readonly bool _isEphemeral = false; @@ -217,7 +217,7 @@ private ProjectRootElement(ProjectRootElementCacheBase projectRootElementCache, document.Load(xr); } - ProjectParser.Parse(document, this); + ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); } /// @@ -241,7 +241,7 @@ private ProjectRootElement( XmlDocumentWithLocation document = LoadDocument(path, preserveFormatting, projectRootElementCache.LoadProjectsReadOnly); - ProjectParser.Parse(document, this); + ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); } /// @@ -261,7 +261,7 @@ private ProjectRootElement(XmlDocumentWithLocation document, ProjectRootElementC _directory = Environment.CurrentDirectory; IncrementVersion(); - ProjectParser.Parse(document, this); + ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); } /// @@ -273,7 +273,7 @@ private ProjectRootElement(XmlDocumentWithLocation document, ProjectRootElementC /// private ProjectRootElement(XmlDocumentWithLocation document) { - ProjectParser.Parse(document, this); + ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); } /// @@ -1721,7 +1721,7 @@ private void ReloadFrom(Func documentProducer, bo RemoveAllChildren(); - ProjectParser.Parse(newDocument, this); + ProjectParser.Parse(newDocument, this, ProjectRootElementCache.UnknownElementsConfiguration); MarkDirty("Project reloaded", null); } diff --git a/src/Build/Definition/ProjectCollection.cs b/src/Build/Definition/ProjectCollection.cs index 9bb0a95a5ab..dd91d7c9ebe 100644 --- a/src/Build/Definition/ProjectCollection.cs +++ b/src/Build/Definition/ProjectCollection.cs @@ -205,6 +205,8 @@ public class ProjectCollection : IToolsetProvider, IBuildComponent, IDisposable /// private int _maxNodeCount; + private UnknownElementsConfiguration _unknownElementsConfiguration; + /// /// LoggingService Logger mode. /// If Asynchronous mode is used @@ -387,6 +389,13 @@ private ProjectCollection(IDictionary globalProperties, IEnumera } } + // Load the global Directory.Parse.config unless explicitly provided or disabled. + if (_unknownElementsConfiguration is null && !Traits.Instance.EscapeHatches.DisableParseConfig) + { + _unknownElementsConfiguration = UnknownElementsConfiguration.LoadGlobalConfig(); + ProjectRootElementCache.UnknownElementsConfiguration = _unknownElementsConfiguration; + } + OnlyLogCriticalEvents = onlyLogCriticalEvents; EnableTargetOutputLogging = enableTargetOutputLogging; @@ -563,6 +572,20 @@ public static string DisplayVersion /// public ICollection PropertiesFromCommandLine { get; set; } + /// + /// Gets or sets the configuration for allowed unknown attributes/elements during parsing. + /// When set, this configuration will be used by builds started from this collection. + /// + internal UnknownElementsConfiguration UnknownElementsConfiguration + { + get => _unknownElementsConfiguration; + set + { + _unknownElementsConfiguration = value; + ProjectRootElementCache.UnknownElementsConfiguration = value; + } + } + /// /// The default tools version of this project collection. Projects use this tools version if they /// aren't otherwise told what tools version to use. diff --git a/src/Build/Evaluation/Evaluator.cs b/src/Build/Evaluation/Evaluator.cs index feec137d877..10d3cbc6718 100644 --- a/src/Build/Evaluation/Evaluator.cs +++ b/src/Build/Evaluation/Evaluator.cs @@ -192,6 +192,8 @@ internal class Evaluator /// private readonly ProjectRootElementCacheBase _projectRootElementCache; + private UnknownElementsConfiguration _unknownElementsConfiguration; + /// /// The logging context to be used and piped down throughout evaluation. /// @@ -307,6 +309,37 @@ private Evaluator( _streamImports.Add(string.Empty); } + private void InitializeUnknownElementsConfiguration() + { + _unknownElementsConfiguration = _projectRootElementCache.UnknownElementsConfiguration; + + if (Traits.Instance.EscapeHatches.DisableParseConfig || string.IsNullOrEmpty(_projectRootElement.FullPath)) + { + return; + } + + string projectConfigPath = FileUtilities.GetPathOfFileAbove(UnknownElementsConfiguration.ConfigFileName, _projectRootElement.DirectoryPath); + if (string.IsNullOrEmpty(projectConfigPath)) + { + return; + } + + if (_unknownElementsConfiguration is null) + { + _unknownElementsConfiguration = UnknownElementsConfiguration.LoadFromFile(projectConfigPath); + } + else if (!_unknownElementsConfiguration.ContainsLoadedFile(projectConfigPath)) + { + _unknownElementsConfiguration = _unknownElementsConfiguration.Merge(UnknownElementsConfiguration.LoadFromFile(projectConfigPath)); + } + else + { + return; + } + + _projectRootElementCache.UnknownElementsConfiguration = _unknownElementsConfiguration; + } + /// /// Delegate passed to methods to provide basic expression evaluation /// ability, without having a language service. @@ -392,6 +425,12 @@ internal static void Evaluate( items = evaluator._data.Items; } + string skippedMessage = evaluator._unknownElementsConfiguration?.GetSkippedSummaryMessage(); + if (skippedMessage is not null) + { + evaluator._evaluationLoggingContext.LogCommentFromText(MessageImportance.Low, skippedMessage); + } + evaluator._evaluationLoggingContext.LogProjectEvaluationFinished(globalProperties, properties, items, evaluator._evaluationProfiler.ProfiledResult); } @@ -662,6 +701,14 @@ private void Evaluate() _data.EvaluationId = _evaluationLoggingContext.BuildEventContext.EvaluationId; _evaluationLoggingContext.LogProjectEvaluationStarted(); + InitializeUnknownElementsConfiguration(); + + string configMessage = _unknownElementsConfiguration?.GetLoadedConfigsMessage(); + if (configMessage is not null) + { + _evaluationLoggingContext.LogCommentFromText(MessageImportance.Low, configMessage); + } + // Track loads only after start of evaluation was actually logged using var assemblyLoadsTracker = AssemblyLoadsTracker.StartTracking(_evaluationLoggingContext, AssemblyLoadingContext.Evaluation); diff --git a/src/Build/Evaluation/ProjectParser.cs b/src/Build/Evaluation/ProjectParser.cs index 5170d52db24..722ba86962d 100644 --- a/src/Build/Evaluation/ProjectParser.cs +++ b/src/Build/Evaluation/ProjectParser.cs @@ -1,9 +1,10 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Xml; +using Microsoft.Build.Evaluation; using Microsoft.Build.Eventing; using Microsoft.Build.Framework; using Microsoft.Build.Shared; @@ -85,6 +86,8 @@ internal class ProjectParser /// private readonly XmlDocumentWithLocation _document; + private readonly UnknownElementsConfiguration _unknownElementsConfiguration; + /// /// Whether a ProjectExtensions node has been encountered already. /// It's not supposed to appear more than once. @@ -94,13 +97,14 @@ internal class ProjectParser /// /// Private constructor to give static semantics /// - private ProjectParser(XmlDocumentWithLocation document, ProjectRootElement project) + private ProjectParser(XmlDocumentWithLocation document, ProjectRootElement project, UnknownElementsConfiguration unknownElementsConfiguration) { Assumed.NotNull(project); Assumed.NotNull(document); _document = document; _project = project; + _unknownElementsConfiguration = unknownElementsConfiguration; } /// @@ -111,11 +115,11 @@ private ProjectParser(XmlDocumentWithLocation document, ProjectRootElement proje /// The code markers here used to be around the Project class constructor in the old code. /// In the new code, that's not very interesting; we are repurposing to wrap parsing the XML. /// - internal static void Parse(XmlDocumentWithLocation document, ProjectRootElement projectRootElement) + internal static void Parse(XmlDocumentWithLocation document, ProjectRootElement projectRootElement, UnknownElementsConfiguration unknownElementsConfiguration) { MSBuildEventSource.Log.ParseStart(projectRootElement.ProjectFileLocation.File); { - ProjectParser parser = new ProjectParser(document, projectRootElement); + ProjectParser parser = new ProjectParser(document, projectRootElement, unknownElementsConfiguration); parser.Parse(); } MSBuildEventSource.Log.ParseStop(projectRootElement.ProjectFileLocation.File); @@ -204,7 +208,11 @@ private void Parse() break; default: - ProjectXmlUtilities.ThrowProjectInvalidChildElement(childElement.Name, childElement.ParentNode.Name, childElement.Location); + if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, childElement.ParentNode.Name, childElement.Location, _unknownElementsConfiguration)) + { + continue; + } + break; } } @@ -215,13 +223,13 @@ private void Parse() /// private ProjectPropertyGroupElement ParseProjectPropertyGroupElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration); ProjectPropertyGroupElement propertyGroup = new ProjectPropertyGroupElement(element, parent, _project); foreach (XmlElementWithLocation childElement in ProjectXmlUtilities.GetVerifyThrowProjectChildElements(element)) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnlyConditionAndLabel); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration, "Property"); XmlUtilities.VerifyThrowProjectValidElementName(childElement); ProjectErrorUtilities.VerifyThrowInvalidProject(!XMakeElements.ReservedItemNames.Contains(childElement.Name) && !ReservedPropertyNames.IsReservedProperty(childElement.Name), childElement.Location, "CannotModifyReservedProperty", childElement.Name); @@ -239,7 +247,7 @@ private ProjectPropertyGroupElement ParseProjectPropertyGroupElement(XmlElementW /// private ProjectItemGroupElement ParseProjectItemGroupElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration); ProjectItemGroupElement itemGroup = new ProjectItemGroupElement(element, parent, _project); @@ -320,7 +328,10 @@ private ProjectItemElement ParseProjectItemElement(XmlElementWithLocation elemen if (!isKnownAttribute && !isValidMetadataNameInAttribute) { - ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); + if (_unknownElementsConfiguration?.CheckSkipAttribute("Item", attribute.Name) != true) + { + ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); + } } else if (isValidMetadataNameInAttribute) { @@ -392,7 +403,7 @@ internal static void CheckMetadataAsAttributeName(string name, out bool isReserv /// private ProjectMetadataElement ParseProjectMetadataElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration, "Metadata"); XmlUtilities.VerifyThrowProjectValidElementName(element); @@ -420,7 +431,7 @@ private ProjectMetadataElement ParseProjectMetadataElement(XmlElementWithLocatio /// A ProjectImportGroupElement derived from the XML element passed in private ProjectImportGroupElement ParseProjectImportGroupElement(XmlElementWithLocation element, ProjectRootElement parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration); ProjectImportGroupElement importGroup = new ProjectImportGroupElement(element, parent, _project); @@ -453,9 +464,9 @@ private ProjectImportElement ParseProjectImportElement(XmlElementWithLocation el parent, element); - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnImport); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnImport, _unknownElementsConfiguration); ProjectXmlUtilities.VerifyThrowProjectRequiredAttribute(element, XMakeAttributes.project); - ProjectXmlUtilities.VerifyThrowProjectNoChildElements(element); + ProjectXmlUtilities.VerifyThrowProjectNoChildElements(element, _unknownElementsConfiguration); SdkReference sdk = null; if (element.HasAttribute(XMakeAttributes.sdk)) @@ -475,7 +486,7 @@ private ProjectImportElement ParseProjectImportElement(XmlElementWithLocation el private UsingTaskParameterGroupElement ParseUsingTaskParameterGroupElement(XmlElementWithLocation element, ProjectElementContainer parent) { // There should be no attributes - ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element); + ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _unknownElementsConfiguration); UsingTaskParameterGroupElement parameterGroup = new UsingTaskParameterGroupElement(element, parent, _project); @@ -489,7 +500,7 @@ private UsingTaskParameterGroupElement ParseUsingTaskParameterGroupElement(XmlEl } else { - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskParameter); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskParameter, _unknownElementsConfiguration, "Parameter"); XmlUtilities.VerifyThrowProjectValidElementName(childElement); ProjectUsingTaskParameterElement parameter = new ProjectUsingTaskParameterElement(childElement, parameterGroup, _project); parameterGroup.AppendParentedChildNoChecks(parameter); @@ -507,7 +518,7 @@ private UsingTaskParameterGroupElement ParseUsingTaskParameterGroupElement(XmlEl /// private ProjectUsingTaskElement ParseProjectUsingTaskElement(XmlElementWithLocation element) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnUsingTask); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnUsingTask, _unknownElementsConfiguration); ProjectErrorUtilities.VerifyThrowInvalidProject(element.GetAttribute(XMakeAttributes.taskName).Length > 0, element.Location, "ProjectTaskNameEmpty"); string assemblyName = element.GetAttribute(XMakeAttributes.assemblyName); @@ -550,13 +561,17 @@ private ProjectUsingTaskElement ParseProjectUsingTaskElement(XmlElementWithLocat ProjectXmlUtilities.ThrowProjectInvalidChildElementDueToDuplicate(childElement); } - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskBody); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskBody, _unknownElementsConfiguration, "UsingTaskBody"); child = new ProjectUsingTaskBodyElement(childElement, usingTask, _project); foundTaskElement = true; break; default: - ProjectXmlUtilities.ThrowProjectInvalidChildElement(childElement.Name, element.Name, element.Location); + if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, "Task", element.Location, _unknownElementsConfiguration)) + { + continue; + } + break; } @@ -571,7 +586,7 @@ private ProjectUsingTaskElement ParseProjectUsingTaskElement(XmlElementWithLocat /// private ProjectTargetElement ParseProjectTargetElement(XmlElementWithLocation element) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnTarget); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnTarget, _unknownElementsConfiguration); ProjectXmlUtilities.VerifyThrowProjectRequiredAttribute(element, XMakeAttributes.name); // Orcas compat: all target names are automatically unescaped @@ -613,9 +628,9 @@ private ProjectTargetElement ParseProjectTargetElement(XmlElementWithLocation el case XMakeElements.onError: // Previous OM accidentally didn't verify ExecuteTargets on parse, // but we do, as it makes no sense - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnOnError); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnOnError, _unknownElementsConfiguration); ProjectXmlUtilities.VerifyThrowProjectRequiredAttribute(childElement, XMakeAttributes.executeTargets); - ProjectXmlUtilities.VerifyThrowProjectNoChildElements(childElement); + ProjectXmlUtilities.VerifyThrowProjectNoChildElements(childElement, _unknownElementsConfiguration); child = onError = new ProjectOnErrorElement(childElement, target, _project); break; @@ -665,7 +680,15 @@ private ProjectTaskElement ParseProjectTaskElement(XmlElementWithLocation elemen foreach (XmlElementWithLocation childElement in ProjectXmlUtilities.GetVerifyThrowProjectChildElements(element)) { - ProjectErrorUtilities.VerifyThrowInvalidProject(childElement.Name == XMakeElements.output, childElement.Location, "UnrecognizedChildElement", childElement.Name, task.Name); + if (childElement.Name != XMakeElements.output) + { + if (_unknownElementsConfiguration?.CheckSkipElement("Task", childElement.Name) == true) + { + continue; + } + + ProjectErrorUtilities.ThrowInvalidProject(childElement.Location, "UnrecognizedChildElement", childElement.Name, task.Name); + } ProjectOutputElement output = ParseProjectOutputElement(childElement, task); @@ -680,9 +703,9 @@ private ProjectTaskElement ParseProjectTaskElement(XmlElementWithLocation elemen /// private ProjectOutputElement ParseProjectOutputElement(XmlElementWithLocation element, ProjectTaskElement parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnOutput); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnOutput, _unknownElementsConfiguration); ProjectXmlUtilities.VerifyThrowProjectRequiredAttribute(element, XMakeAttributes.taskParameter); - ProjectXmlUtilities.VerifyThrowProjectNoChildElements(element); + ProjectXmlUtilities.VerifyThrowProjectNoChildElements(element, _unknownElementsConfiguration); XmlAttributeWithLocation itemNameAttribute = element.GetAttributeWithLocation(XMakeAttributes.itemName); XmlAttributeWithLocation propertyNameAttribute = element.GetAttributeWithLocation(XMakeAttributes.propertyName); @@ -706,7 +729,7 @@ private ProjectOutputElement ParseProjectOutputElement(XmlElementWithLocation el /// private ProjectItemDefinitionGroupElement ParseProjectItemDefinitionGroupElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration); ProjectItemDefinitionGroupElement itemDefinitionGroup = new ProjectItemDefinitionGroupElement(element, parent, _project); @@ -737,7 +760,10 @@ private ProjectItemDefinitionElement ParseProjectItemDefinitionXml(XmlElementWit if (!isKnownAttribute && !isValidMetadataNameInAttribute) { - ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); + if (_unknownElementsConfiguration?.CheckSkipAttribute("ItemDefinition", attribute.Name) != true) + { + ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); + } } else if (isValidMetadataNameInAttribute) { @@ -749,7 +775,10 @@ private ProjectItemDefinitionElement ParseProjectItemDefinitionXml(XmlElementWit } else if (!ValidAttributesOnlyConditionAndLabel.Contains(attribute.Name)) { - ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); + if (_unknownElementsConfiguration?.CheckSkipAttribute("ItemDefinition", attribute.Name) != true) + { + ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); + } } } @@ -768,7 +797,7 @@ private ProjectItemDefinitionElement ParseProjectItemDefinitionXml(XmlElementWit /// private ProjectChooseElement ParseProjectChooseElement(XmlElementWithLocation element, ProjectElementContainer parent, int nestingDepth) { - ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element); + ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _unknownElementsConfiguration); ProjectChooseElement choose = new ProjectChooseElement(element, parent, _project); @@ -797,7 +826,11 @@ private ProjectChooseElement ParseProjectChooseElement(XmlElementWithLocation el break; default: - ProjectXmlUtilities.ThrowProjectInvalidChildElement(childElement.Name, element.Name, element.Location); + if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, element.Name, element.Location, _unknownElementsConfiguration)) + { + continue; + } + break; } @@ -828,7 +861,7 @@ private ProjectWhenElement ParseProjectWhenElement(XmlElementWithLocation elemen /// private ProjectOtherwiseElement ParseProjectOtherwiseElement(XmlElementWithLocation element, ProjectChooseElement parent, int nestingDepth) { - ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element); + ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _unknownElementsConfiguration); ProjectOtherwiseElement otherwise = new ProjectOtherwiseElement(element, parent, _project); @@ -865,7 +898,11 @@ private void ParseWhenOtherwiseChildren(XmlElementWithLocation element, ProjectE break; default: - ProjectXmlUtilities.ThrowProjectInvalidChildElement(childElement.Name, element.Name, element.Location); + if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, element.Name, element.Location, _unknownElementsConfiguration)) + { + continue; + } + break; } @@ -880,7 +917,7 @@ private ProjectExtensionsElement ParseProjectExtensionsElement(XmlElementWithLoc { // ProjectExtensions are only found in the main project file - in fact, the code used to ignore them in imported // files. We don't. - ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element); + ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _unknownElementsConfiguration); ProjectErrorUtilities.VerifyThrowInvalidProject(!_seenProjectExtensions, element.Location, "DuplicateProjectExtensions"); _seenProjectExtensions = true; diff --git a/src/Build/Evaluation/ProjectRootElementCacheBase.cs b/src/Build/Evaluation/ProjectRootElementCacheBase.cs index fc556c1eec9..6d725586905 100644 --- a/src/Build/Evaluation/ProjectRootElementCacheBase.cs +++ b/src/Build/Evaluation/ProjectRootElementCacheBase.cs @@ -12,6 +12,8 @@ internal abstract class ProjectRootElementCacheBase { public bool LoadProjectsReadOnly { get; protected set; } + internal UnknownElementsConfiguration UnknownElementsConfiguration { get; set; } + /// /// Handler for which project root element just got added to the cache /// diff --git a/src/Build/Evaluation/UnknownElementsConfiguration.cs b/src/Build/Evaluation/UnknownElementsConfiguration.cs new file mode 100644 index 00000000000..b362ddc6575 --- /dev/null +++ b/src/Build/Evaluation/UnknownElementsConfiguration.cs @@ -0,0 +1,326 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Microsoft.Build.BackEnd; +using Microsoft.Build.Framework; +using Microsoft.Build.Shared; +using Microsoft.Build.Shared.FileSystem; + +namespace Microsoft.Build.Evaluation +{ + /// + /// Manages a set of allowed unknown attributes and elements that should be silently skipped + /// during project parsing instead of throwing an InvalidProjectFileException. + /// Configuration is loaded from Directory.Parse.config files discovered additively from: + /// 1. Next to the MSBuild executable + /// 2. User profile (~/.msbuild/) + /// 3. MSBUILD_PARSE_CONFIG environment variable paths + /// + internal sealed class UnknownElementsConfiguration : ITranslatable + { + internal const string ConfigFileName = "Directory.Parse.config"; + internal const string EnvironmentVariableName = "MSBUILD_PARSE_CONFIG"; + + private const string UserProfileSubfolder = ".msbuild"; + + private Dictionary> _allowedAttributes; + private Dictionary> _allowedChildren; + private HashSet _loadedConfigFiles; + private readonly ConcurrentDictionary _skippedItems = new(StringComparer.OrdinalIgnoreCase); + + private UnknownElementsConfiguration() + { + _allowedAttributes = new Dictionary>(StringComparer.OrdinalIgnoreCase); + _allowedChildren = new Dictionary>(StringComparer.OrdinalIgnoreCase); + _loadedConfigFiles = new HashSet(StringComparer.OrdinalIgnoreCase); + } + + private UnknownElementsConfiguration(ITranslator translator) + : this() + { + ((ITranslatable)this).Translate(translator); + } + + internal IReadOnlyCollection LoadedConfigFiles => _loadedConfigFiles; + + internal static UnknownElementsConfiguration Empty { get; } = new UnknownElementsConfiguration(); + + /// + /// Checks whether the given file path has already been loaded into this configuration. + /// + internal bool ContainsLoadedFile(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + { + return false; + } + + try + { + return _loadedConfigFiles.Contains(FileUtilities.NormalizePath(filePath)); + } + catch + { + return false; + } + } + + internal bool CheckSkipAttribute(string elementName, string attributeName) + { + if (_allowedAttributes.Count == 0) + { + return false; + } + + if (!_allowedAttributes.TryGetValue(elementName, out HashSet? allowedAttributes) || !allowedAttributes.Contains(attributeName)) + { + return false; + } + + RecordSkippedItem($"Attribute:{elementName}:{attributeName}"); + return true; + } + + internal bool CheckSkipElement(string parentElementName, string childElementName) + { + if (_allowedChildren.Count == 0) + { + return false; + } + + if (!_allowedChildren.TryGetValue(parentElementName, out HashSet? allowedChildren) || !allowedChildren.Contains(childElementName)) + { + return false; + } + + RecordSkippedItem($"Element:{parentElementName}:{childElementName}"); + return true; + } + + internal string? GetSkippedSummaryMessage() + { + if (_skippedItems.IsEmpty) + { + return null; + } + + var sb = new StringBuilder("Skipped unrecognized items allowed by Directory.Parse.config:"); + foreach (var kvp in _skippedItems) + { + sb.Append($" {kvp.Key} ({kvp.Value} occurrence{(kvp.Value > 1 ? "s" : string.Empty)});"); + } + + sb.Length--; + return sb.ToString(); + } + + internal string? GetLoadedConfigsMessage() + { + if (_loadedConfigFiles.Count == 0) + { + return null; + } + + return $"Loaded Directory.Parse.config from: {string.Join(", ", _loadedConfigFiles)}"; + } + + internal UnknownElementsConfiguration Merge(UnknownElementsConfiguration other) + { + ArgumentNullException.ThrowIfNull(other); + + var merged = new UnknownElementsConfiguration(); + + UnionEntries(merged._allowedAttributes, _allowedAttributes); + UnionEntries(merged._allowedAttributes, other._allowedAttributes); + UnionEntries(merged._allowedChildren, _allowedChildren); + UnionEntries(merged._allowedChildren, other._allowedChildren); + merged._loadedConfigFiles.UnionWith(_loadedConfigFiles); + merged._loadedConfigFiles.UnionWith(other._loadedConfigFiles); + MergeSkippedItems(merged._skippedItems, _skippedItems); + MergeSkippedItems(merged._skippedItems, other._skippedItems); + + return merged; + } + + internal static UnknownElementsConfiguration LoadFromFile(string filePath) + { + var config = new UnknownElementsConfiguration(); + config.LoadFile(filePath); + return config; + } + + internal static UnknownElementsConfiguration LoadGlobalConfig(string? startingDirectory = null) + { + var config = new UnknownElementsConfiguration(); + + string? msbuildExeDir = BuildEnvironmentHelper.Instance?.CurrentMSBuildToolsDirectory; + if (!string.IsNullOrEmpty(msbuildExeDir)) + { + config.LoadFile(Path.Combine(msbuildExeDir, ConfigFileName)); + } + + string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + if (!string.IsNullOrEmpty(userProfile)) + { + config.LoadFile(Path.Combine(userProfile, UserProfileSubfolder, ConfigFileName)); + } + + string? envValue = Environment.GetEnvironmentVariable(EnvironmentVariableName); + if (!string.IsNullOrEmpty(envValue)) + { + string[] paths = envValue.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries); + foreach (string path in paths) + { + string trimmedPath = path.Trim(); + if (trimmedPath.Length > 0) + { + config.LoadFile(trimmedPath); + } + } + } + + // Walk up from the starting directory looking for a Directory.Parse.config + if (!string.IsNullOrEmpty(startingDirectory)) + { + string directoryConfigPath = FileUtilities.GetPathOfFileAbove(ConfigFileName, startingDirectory!); + if (!string.IsNullOrEmpty(directoryConfigPath) && !config.ContainsLoadedFile(directoryConfigPath)) + { + config.LoadFile(directoryConfigPath); + } + } + + return config; + } + + void ITranslatable.Translate(ITranslator translator) + { + translator.TranslateDictionary(ref _allowedAttributes, StringComparer.OrdinalIgnoreCase, TranslateHashSetValue, HashSetValueFactory); + translator.TranslateDictionary(ref _allowedChildren, StringComparer.OrdinalIgnoreCase, TranslateHashSetValue, HashSetValueFactory); + translator.Translate(ref _loadedConfigFiles); + } + + private static void TranslateHashSetValue(ITranslator translator, NodePacketValueFactory> factory, ref HashSet value) + { + translator.Translate(ref value); + } + + private static HashSet HashSetValueFactory(ITranslator translator) + { + HashSet? set = null; + translator.Translate(ref set); + return set ?? new HashSet(StringComparer.OrdinalIgnoreCase); + } + + internal static UnknownElementsConfiguration FactoryForDeserialization(ITranslator translator) + { + return new UnknownElementsConfiguration(translator); + } + + private static void UnionEntries(Dictionary> destination, Dictionary> source) + { + foreach (var kvp in source) + { + if (!destination.TryGetValue(kvp.Key, out HashSet? names)) + { + names = new HashSet(StringComparer.OrdinalIgnoreCase); + destination[kvp.Key] = names; + } + + names.UnionWith(kvp.Value); + } + } + + private static void MergeSkippedItems(ConcurrentDictionary destination, ConcurrentDictionary source) + { + foreach (var kvp in source) + { + destination.AddOrUpdate(kvp.Key, kvp.Value, (_, count) => count + kvp.Value); + } + } + + private void RecordSkippedItem(string key) + { + _skippedItems.AddOrUpdate(key, 1, static (_, count) => count + 1); + } + + private void LoadFile(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + { + return; + } + + string fullPath; + try + { + fullPath = FileUtilities.NormalizePath(filePath); + } + catch + { + return; + } + + if (!FileSystems.Default.FileExists(fullPath) || !_loadedConfigFiles.Add(fullPath)) + { + return; + } + + foreach (string rawLine in File.ReadLines(filePath)) + { + string entry = rawLine.Trim(); + if (string.IsNullOrEmpty(entry) || entry[0] == '#') + { + continue; + } + + int firstColon = entry.IndexOf(':'); + if (firstColon < 0) + { + continue; + } + + int secondColon = entry.IndexOf(':', firstColon + 1); + if (secondColon < 0 || entry.IndexOf(':', secondColon + 1) >= 0) + { + continue; + } + + string type = entry.Substring(0, firstColon).Trim(); + string elementName = entry.Substring(firstColon + 1, secondColon - firstColon - 1).Trim(); + string unknownName = entry.Substring(secondColon + 1).Trim(); + + if (type.Length == 0 || elementName.Length == 0 || unknownName.Length == 0) + { + continue; + } + + if (type.Equals("ATTRIBUTE", StringComparison.OrdinalIgnoreCase)) + { + AddAllowedName(_allowedAttributes, elementName, unknownName); + } + else if (type.Equals("ELEMENT", StringComparison.OrdinalIgnoreCase)) + { + AddAllowedName(_allowedChildren, elementName, unknownName); + } + } + + _loadedConfigFiles.Add(fullPath); + } + + private static void AddAllowedName(Dictionary> destination, string elementName, string unknownName) + { + if (!destination.TryGetValue(elementName, out HashSet? names)) + { + names = new HashSet(StringComparer.OrdinalIgnoreCase); + destination[elementName] = names; + } + + names.Add(unknownName); + } + } +} diff --git a/src/Build/Microsoft.Build.csproj b/src/Build/Microsoft.Build.csproj index 2edd2f2474e..e1b55579326 100644 --- a/src/Build/Microsoft.Build.csproj +++ b/src/Build/Microsoft.Build.csproj @@ -544,6 +544,7 @@ + diff --git a/src/Build/Xml/ProjectXmlUtilities.XmlElementChildIterator.cs b/src/Build/Xml/ProjectXmlUtilities.XmlElementChildIterator.cs index 8fc5e75a7b5..2543fbff0e3 100644 --- a/src/Build/Xml/ProjectXmlUtilities.XmlElementChildIterator.cs +++ b/src/Build/Xml/ProjectXmlUtilities.XmlElementChildIterator.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -97,7 +97,7 @@ private readonly XmlElementWithLocation GetNextNode(XmlNode child) } if (_throwForInvalidNodeTypes) { - ThrowProjectInvalidChildElement(child.Name, _element.Name, _element.Location); + ThrowIfProjectInvalidChildElement(child.Name, _element.Name, _element.Location, config: null); } break; } diff --git a/src/Build/Xml/ProjectXmlUtilities.cs b/src/Build/Xml/ProjectXmlUtilities.cs index 43672a07329..458198133e6 100644 --- a/src/Build/Xml/ProjectXmlUtilities.cs +++ b/src/Build/Xml/ProjectXmlUtilities.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -6,6 +6,7 @@ using System.IO; using System.Xml; using Microsoft.Build.Construction; +using Microsoft.Build.Evaluation; using Microsoft.Build.Framework.BuildException; using Microsoft.Build.Shared; @@ -55,11 +56,11 @@ private static XmlElementChildIterator GetChildElements(XmlElementWithLocation e /// /// Throw an invalid project exception if there are any child elements at all /// - internal static void VerifyThrowProjectNoChildElements(XmlElementWithLocation element) + internal static void VerifyThrowProjectNoChildElements(XmlElementWithLocation element, UnknownElementsConfiguration config = null) { foreach (var child in GetVerifyThrowProjectChildElements(element)) { - ThrowProjectInvalidChildElement(child.Name, element.Name, element.Location); + ThrowIfProjectInvalidChildElement(child.Name, element.Name, element.Location, config); } } @@ -72,14 +73,6 @@ internal static void ThrowProjectInvalidChildElementDueToDuplicate(XmlElementWit ProjectErrorUtilities.ThrowInvalidProject(child.Location, "InvalidChildElementDueToDuplication", child.Name, child.ParentNode.Name); } - /// - /// Throw an invalid project exception indicating that the child is not valid beneath the element - /// - internal static void ThrowProjectInvalidChildElement(string name, string parentName, ElementLocation location) - { - ProjectErrorUtilities.ThrowInvalidProject(location, "UnrecognizedChildElement", name, parentName); - } - /// /// Verify that if a namespace is specified it matches the default MSBuild namespace. /// @@ -145,12 +138,17 @@ internal static void VerifyThrowProjectAttributeEitherMissingOrNotEmpty(XmlEleme /// /// If there are any attributes on the element, throws an InvalidProjectFileException complaining that the attribute is not valid on this element. /// - internal static void VerifyThrowProjectNoAttributes(XmlElementWithLocation element) + internal static void VerifyThrowProjectNoAttributes(XmlElementWithLocation element, UnknownElementsConfiguration config = null) { if (element.HasAttributes) { foreach (XmlAttributeWithLocation attribute in element.Attributes) { + if (config?.CheckSkipAttribute(element.Name, attribute.Name) == true) + { + continue; + } + ThrowProjectInvalidAttribute(attribute); } } @@ -177,14 +175,40 @@ internal static void VerifyThrowProjectRequiredAttribute(XmlElementWithLocation } /// - /// Verify that all attributes on the element are on the list of legal attributes + /// Verify that all attributes on the element are on the list of legal attributes. + /// When genericElementName is provided, only that name is checked in the config (not the actual element name). /// - internal static void VerifyThrowProjectAttributes(XmlElementWithLocation element, HashSet validAttributes) + internal static void VerifyThrowProjectAttributes(XmlElementWithLocation element, HashSet validAttributes, UnknownElementsConfiguration config = null, string genericElementName = null) { foreach (XmlAttributeWithLocation attribute in element.Attributes) { - ProjectXmlUtilities.VerifyThrowProjectInvalidAttribute(validAttributes.Contains(attribute.Name), attribute); + if (!validAttributes.Contains(attribute.Name)) + { + string configElementName = genericElementName ?? element.Name; + if (config?.CheckSkipAttribute(configElementName, attribute.Name) == true) + { + continue; + } + + ThrowProjectInvalidAttribute(attribute); + } + } + } + + /// + /// Throws an InvalidProjectFileException if the child element is not allowed by configuration. + /// If the element is allowed, it is silently skipped. + /// + /// True if the element was skipped (caller should continue), false if the element was not in config and an exception was thrown. + internal static bool ThrowIfProjectInvalidChildElement(string name, string parentName, ElementLocation location, UnknownElementsConfiguration config = null) + { + if (config?.CheckSkipElement(parentName, name) == true) + { + return true; } + + ProjectErrorUtilities.ThrowInvalidProject(location, "UnrecognizedChildElement", name, parentName); + return false; // Unreachable, but needed for compiler } /// diff --git a/src/Framework/Traits.cs b/src/Framework/Traits.cs index 8c6b2fe8846..1bea24823e6 100644 --- a/src/Framework/Traits.cs +++ b/src/Framework/Traits.cs @@ -275,6 +275,13 @@ internal class EscapeHatches /// public readonly bool AlwaysEvaluateDangerousGlobs = Environment.GetEnvironmentVariable("MSBuildAlwaysEvaluateDangerousGlobs") == "1"; + /// + /// Disables automatic loading of Directory.Parse.config from global locations + /// (MSBuild exe directory, user profile, MSBUILD_PARSE_CONFIG env var). + /// When set, configuration must be explicitly provided via ProjectCollection or BuildParameters. + /// + public readonly bool DisableParseConfig = Environment.GetEnvironmentVariable("MSBUILD_DISABLE_PARSE_CONFIG") == "1"; + /// /// Disables skipping full up to date check for immutable files. See FileClassifier class. /// From 7dee3746e246e5b6455c6894273b9ec8340733d2 Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Fri, 31 Jul 2026 14:30:34 -0400 Subject: [PATCH 02/20] Switch Directory.Parse.config to XML format Change config file format from custom text (Type:Element:Name) to XML: Also adds HasSameLoadedFiles() for config comparison (used by next commit). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- documentation/specs/directory-parse-config.md | 35 ++++---- .../UnknownElementsConfiguration_Tests.cs | 61 ++++++++------ .../UnknownElementsConfiguration.cs | 84 +++++++++++++------ 3 files changed, 111 insertions(+), 69 deletions(-) diff --git a/documentation/specs/directory-parse-config.md b/documentation/specs/directory-parse-config.md index 73cbcd9c444..94e514b72c7 100644 --- a/documentation/specs/directory-parse-config.md +++ b/documentation/specs/directory-parse-config.md @@ -8,26 +8,29 @@ This enables compatibility scenarios where project files may include attributes/ ## Configuration File Format -`Directory.Parse.config` is a plain text file with one entry per line: - -``` -# Lines starting with # are comments -# Empty lines are ignored - -# Format: Type:Name:AllowedName -Attribute:Target:CustomAttr -Element:Project:CustomElement -Attribute:PropertyGroup:NewFeatureFlag +`Directory.Parse.config` is an XML file: + +```xml + + + + + + + + + + ``` -- **Type**: Either `Attribute` or `Element` (case-insensitive) -- **Name**: `Attribute`: the name/type of the element; `Element`: the name/type of the parent element -- **AllowedName**: The name of the attribute or child element to allow +- **Root element**: `` +- **``**: Contains `` entries for attributes to skip. Appears 0 or 1 times. +- **``**: Contains `` entries for child elements to skip. Appears 0 or 1 times. +- **``**: Each entry has `Element` (the parent/owner element name) and `Name` (the attribute or child to allow). -Matching is case-insensitive. -Invalid lines (wrong format, unknown type, wrong number of colons) are silently ignored. +Matching is case-insensitive. Entries with missing or empty `Element`/`Name` attributes are silently ignored. Unrecognized sections or elements are ignored. -For more details on `Name`: +For more details on `Element`: ### Valid Attribute Names diff --git a/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs b/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs index 16cb7672d1c..2fcf3a598de 100644 --- a/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs +++ b/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs @@ -34,13 +34,15 @@ public void Dispose() public void ParsesValidConfigFile() { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, @" -# This is a comment -Attribute:Target:Foo -Element:Project:CustomThing - -Attribute:PropertyGroup:Bar -"); + File.WriteAllText(configPath, @" + + + + + + + +"); var config = UnknownElementsConfiguration.LoadFromFile(configPath); @@ -54,7 +56,7 @@ public void ParsesValidConfigFile() public void IsCaseInsensitive() { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + File.WriteAllText(configPath, @""); var config = UnknownElementsConfiguration.LoadFromFile(configPath); @@ -67,7 +69,7 @@ public void IsCaseInsensitive() public void RejectsNonAllowedItems() { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + File.WriteAllText(configPath, @""); var config = UnknownElementsConfiguration.LoadFromFile(configPath); @@ -77,23 +79,30 @@ public void RejectsNonAllowedItems() } [Fact] - public void IgnoresInvalidLines() + public void IgnoresInvalidEntries() { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, @" -# Comment -InvalidType:Target:Foo -Attribute:Target -Attribute -:Target:Foo -Attribute:Target:Foo:ExtraColon -Attribute:Target:ValidOne -"); + File.WriteAllText(configPath, @" + + + + + + + + + + + +"); var config = UnknownElementsConfiguration.LoadFromFile(configPath); config.CheckSkipAttribute("Target", "ValidOne").ShouldBeTrue(); config.CheckSkipAttribute("Target", "Foo").ShouldBeFalse(); + config.CheckSkipAttribute("Target", "Bar").ShouldBeFalse(); + config.CheckSkipAttribute("Target", "Nope").ShouldBeFalse(); + config.CheckSkipAttribute("Target", "Nope2").ShouldBeFalse(); } [Fact] @@ -109,10 +118,10 @@ public void ReturnsEmptyWhenNoConfigExists() public void MergeCombinesEntriesAndDeduplicatesFiles() { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + File.WriteAllText(configPath, @""); string extraConfigPath = Path.Combine(_testDir, "extra.config"); - File.WriteAllText(extraConfigPath, "Element:Project:CustomThing\n"); + File.WriteAllText(extraConfigPath, @""); var merged = UnknownElementsConfiguration.LoadFromFile(configPath) .Merge(UnknownElementsConfiguration.LoadFromFile(extraConfigPath)) @@ -127,7 +136,7 @@ public void MergeCombinesEntriesAndDeduplicatesFiles() public void LoadGlobalConfigLoadsEnvironmentVariablePaths() { string envConfigPath = Path.Combine(_testDir, "env.config"); - File.WriteAllText(envConfigPath, "Element:Project:CustomThing\n"); + File.WriteAllText(envConfigPath, @""); string oldEnv = Environment.GetEnvironmentVariable(UnknownElementsConfiguration.EnvironmentVariableName); try @@ -147,7 +156,7 @@ public void LoadGlobalConfigLoadsEnvironmentVariablePaths() public void RecordsSkippedItems() { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + File.WriteAllText(configPath, @""); var config = UnknownElementsConfiguration.LoadFromFile(configPath); @@ -173,7 +182,7 @@ public void GetLoadedConfigsMessageReturnsNullWhenEmpty() public void GetLoadedConfigsMessageListsFiles() { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, "Attribute:Target:Foo\n"); + File.WriteAllText(configPath, @""); var config = UnknownElementsConfiguration.LoadFromFile(configPath); @@ -186,7 +195,7 @@ public void GetLoadedConfigsMessageListsFiles() public void AllowedAttributeDoesNotThrowDuringParsing() { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, "Attribute:Target:CustomAttr\n"); + File.WriteAllText(configPath, @""); string projectContent = @" @@ -226,7 +235,7 @@ public void NonAllowedAttributeStillThrows() public void AllowedChildElementDoesNotThrowDuringParsing() { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, "Element:Project:CustomElement\n"); + File.WriteAllText(configPath, @""); string projectContent = @" diff --git a/src/Build/Evaluation/UnknownElementsConfiguration.cs b/src/Build/Evaluation/UnknownElementsConfiguration.cs index b362ddc6575..cbe8d096760 100644 --- a/src/Build/Evaluation/UnknownElementsConfiguration.cs +++ b/src/Build/Evaluation/UnknownElementsConfiguration.cs @@ -50,6 +50,15 @@ private UnknownElementsConfiguration(ITranslator translator) internal static UnknownElementsConfiguration Empty { get; } = new UnknownElementsConfiguration(); + /// + /// Returns true if this config has the same set of loaded files as the other config. + /// Used by worker nodes to detect if the config changed between builds. + /// + internal bool HasSameLoadedFiles(UnknownElementsConfiguration other) + { + return _loadedConfigFiles.SetEquals(other._loadedConfigFiles); + } + /// /// Checks whether the given file path has already been loaded into this configuration. /// @@ -270,46 +279,67 @@ private void LoadFile(string filePath) return; } - foreach (string rawLine in File.ReadLines(filePath)) + try { - string entry = rawLine.Trim(); - if (string.IsNullOrEmpty(entry) || entry[0] == '#') + var settings = new System.Xml.XmlReaderSettings { DtdProcessing = System.Xml.DtdProcessing.Prohibit }; + var doc = new System.Xml.XmlDocument(); + using (var stream = File.OpenRead(fullPath)) + using (var reader = System.Xml.XmlReader.Create(stream, settings)) { - continue; + doc.Load(reader); } - int firstColon = entry.IndexOf(':'); - if (firstColon < 0) + System.Xml.XmlElement? root = doc.DocumentElement; + if (root is null || !root.Name.Equals("ParseConfig", StringComparison.OrdinalIgnoreCase)) { - continue; + return; } - int secondColon = entry.IndexOf(':', firstColon + 1); - if (secondColon < 0 || entry.IndexOf(':', secondColon + 1) >= 0) + foreach (System.Xml.XmlNode child in root.ChildNodes) { - continue; - } + if (child.NodeType != System.Xml.XmlNodeType.Element) + { + continue; + } - string type = entry.Substring(0, firstColon).Trim(); - string elementName = entry.Substring(firstColon + 1, secondColon - firstColon - 1).Trim(); - string unknownName = entry.Substring(secondColon + 1).Trim(); + Dictionary>? target = null; + if (child.Name.Equals("IgnoreAttributes", StringComparison.OrdinalIgnoreCase)) + { + target = _allowedAttributes; + } + else if (child.Name.Equals("IgnoreChildren", StringComparison.OrdinalIgnoreCase)) + { + target = _allowedChildren; + } - if (type.Length == 0 || elementName.Length == 0 || unknownName.Length == 0) - { - continue; - } + if (target is null) + { + continue; + } - if (type.Equals("ATTRIBUTE", StringComparison.OrdinalIgnoreCase)) - { - AddAllowedName(_allowedAttributes, elementName, unknownName); - } - else if (type.Equals("ELEMENT", StringComparison.OrdinalIgnoreCase)) - { - AddAllowedName(_allowedChildren, elementName, unknownName); + foreach (System.Xml.XmlNode ignoreNode in child.ChildNodes) + { + if (ignoreNode.NodeType != System.Xml.XmlNodeType.Element + || !ignoreNode.Name.Equals("Ignore", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + System.Xml.XmlElement ignoreElement = (System.Xml.XmlElement)ignoreNode; + string elementName = ignoreElement.GetAttribute("Element"); + string name = ignoreElement.GetAttribute("Name"); + + if (!string.IsNullOrEmpty(elementName) && !string.IsNullOrEmpty(name)) + { + AddAllowedName(target, elementName, name); + } + } } } - - _loadedConfigFiles.Add(fullPath); + catch + { + // If the file can't be parsed as XML, silently skip it + } } private static void AddAllowedName(Dictionary> destination, string elementName, string unknownName) From 7a06433201ead73f14456f3e759532a790f1da7d Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Mon, 3 Aug 2026 08:30:15 -0400 Subject: [PATCH 03/20] Fix config lifecycle: startup-dir loading, server isolation, worker nodes - ProjectRootElementCacheBase: SetUnknownElementsConfiguration with invalidation - ProjectCollection: LoadParseConfigForStartup/UnloadParseConfigForStartup - XMake.BuildProject: calls LoadParseConfigForStartup before loading projects - BuildManager: reads config from cache for serialization to workers - OutOfProcNode: uses SetUnknownElementsConfiguration on worker cache - UnknownElementsConfiguration: static Merge, static Equals, remove LoadAdditionalFile - CollectionHelpers: DictionaryEquals with value comparer Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- .../UnknownElementsConfiguration_Tests.cs | 7 +- .../BackEnd/BuildManager/BuildManager.cs | 5 +- src/Build/BackEnd/Node/OutOfProcNode.cs | 2 + src/Build/Definition/ProjectCollection.cs | 71 +++++++++++++++---- src/Build/Evaluation/Evaluator.cs | 6 +- .../Evaluation/ProjectRootElementCacheBase.cs | 13 +++- .../UnknownElementsConfiguration.cs | 41 ++++++----- src/Framework/Utilities/CollectionHelpers.cs | 16 ++++- src/MSBuild/XMake.cs | 4 ++ 9 files changed, 122 insertions(+), 43 deletions(-) diff --git a/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs b/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs index 2fcf3a598de..b3657d90e4a 100644 --- a/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs +++ b/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs @@ -123,9 +123,10 @@ public void MergeCombinesEntriesAndDeduplicatesFiles() string extraConfigPath = Path.Combine(_testDir, "extra.config"); File.WriteAllText(extraConfigPath, @""); - var merged = UnknownElementsConfiguration.LoadFromFile(configPath) - .Merge(UnknownElementsConfiguration.LoadFromFile(extraConfigPath)) - .Merge(UnknownElementsConfiguration.LoadFromFile(configPath)); + var merged = UnknownElementsConfiguration.Merge( + UnknownElementsConfiguration.LoadFromFile(configPath), + UnknownElementsConfiguration.LoadFromFile(extraConfigPath)); + merged = UnknownElementsConfiguration.Merge(merged, UnknownElementsConfiguration.LoadFromFile(configPath)); merged.CheckSkipAttribute("Target", "Foo").ShouldBeTrue(); merged.CheckSkipElement("Project", "CustomThing").ShouldBeTrue(); diff --git a/src/Build/BackEnd/BuildManager/BuildManager.cs b/src/Build/BackEnd/BuildManager/BuildManager.cs index 212c584a806..67fc3edbfcc 100644 --- a/src/Build/BackEnd/BuildManager/BuildManager.cs +++ b/src/Build/BackEnd/BuildManager/BuildManager.cs @@ -618,10 +618,9 @@ public void BeginBuild(BuildParameters parameters) // Initialize additional build parameters. _buildParameters.BuildId = GetNextBuildId(); - if (_buildParameters.UnknownElementsConfiguration is null && !Traits.Instance.EscapeHatches.DisableParseConfig) + if (!Traits.Instance.EscapeHatches.DisableParseConfig) { - _buildParameters.UnknownElementsConfiguration = UnknownElementsConfiguration.LoadGlobalConfig(BuildParameters.StartupDirectory); - _buildParameters.ProjectRootElementCache.UnknownElementsConfiguration = _buildParameters.UnknownElementsConfiguration; + _buildParameters.UnknownElementsConfiguration = _buildParameters.ProjectRootElementCache.UnknownElementsConfiguration; } if (_buildParameters.UsesCachedResults() && _buildParameters.ProjectIsolationMode == ProjectIsolationMode.False) diff --git a/src/Build/BackEnd/Node/OutOfProcNode.cs b/src/Build/BackEnd/Node/OutOfProcNode.cs index 30bd35c548f..12ff5118703 100644 --- a/src/Build/BackEnd/Node/OutOfProcNode.cs +++ b/src/Build/BackEnd/Node/OutOfProcNode.cs @@ -715,6 +715,8 @@ private void HandleNodeConfiguration(NodeConfiguration configuration) // Grab the system parameters. _buildParameters = configuration.BuildParameters; + s_projectRootElementCacheBase.SetUnknownElementsConfiguration(configuration.BuildParameters.UnknownElementsConfiguration); + _buildParameters.ProjectRootElementCache = s_projectRootElementCacheBase; // Snapshot the current environment diff --git a/src/Build/Definition/ProjectCollection.cs b/src/Build/Definition/ProjectCollection.cs index dd91d7c9ebe..55b1966b5a1 100644 --- a/src/Build/Definition/ProjectCollection.cs +++ b/src/Build/Definition/ProjectCollection.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -205,8 +205,6 @@ public class ProjectCollection : IToolsetProvider, IBuildComponent, IDisposable /// private int _maxNodeCount; - private UnknownElementsConfiguration _unknownElementsConfiguration; - /// /// LoggingService Logger mode. /// If Asynchronous mode is used @@ -383,19 +381,18 @@ private ProjectCollection(IDictionary globalProperties, IEnumera // we do not need to auto reload. bool autoReloadFromDisk = reuseProjectRootElementCache; ProjectRootElementCache = new ProjectRootElementCache(autoReloadFromDisk, loadProjectsReadOnly); + + if (!Traits.Instance.EscapeHatches.DisableParseConfig) + { + ProjectRootElementCache.SetUnknownElementsConfiguration(UnknownElementsConfiguration.LoadGlobalConfig()); + } + if (reuseProjectRootElementCache) { s_projectRootElementCache = ProjectRootElementCache; } } - // Load the global Directory.Parse.config unless explicitly provided or disabled. - if (_unknownElementsConfiguration is null && !Traits.Instance.EscapeHatches.DisableParseConfig) - { - _unknownElementsConfiguration = UnknownElementsConfiguration.LoadGlobalConfig(); - ProjectRootElementCache.UnknownElementsConfiguration = _unknownElementsConfiguration; - } - OnlyLogCriticalEvents = onlyLogCriticalEvents; EnableTargetOutputLogging = enableTargetOutputLogging; @@ -578,11 +575,57 @@ public static string DisplayVersion /// internal UnknownElementsConfiguration UnknownElementsConfiguration { - get => _unknownElementsConfiguration; - set + get => ProjectRootElementCache.UnknownElementsConfiguration; + set => ProjectRootElementCache.SetUnknownElementsConfiguration(value); + } + + /// + /// The config state before LoadParseConfigForStartup was called, used to restore on unload. + /// + private UnknownElementsConfiguration _preStartupUnknownElementsConfiguration; + + /// + /// Loads a Directory.Parse.config by walking up from the specified directory + /// and adds it to the current parse configuration. Call + /// to restore the previous state after the build completes. + /// + /// The directory to start searching from (typically the build's working directory). + /// Thrown if startup config is already loaded. + public void LoadParseConfigForStartup(string startingDirectory) + { + if (_preStartupUnknownElementsConfiguration is not null) + { + throw new InvalidOperationException("LoadParseConfigForStartup called while startup config is already loaded. Call UnloadParseConfigForStartup first."); + } + + if (Traits.Instance.EscapeHatches.DisableParseConfig || string.IsNullOrEmpty(startingDirectory)) + { + return; + } + + var config = ProjectRootElementCache.UnknownElementsConfiguration; + if (config is null) + { + return; + } + + string configPath = FileUtilities.GetPathOfFileAbove(UnknownElementsConfiguration.ConfigFileName, startingDirectory); + if (!string.IsNullOrEmpty(configPath) && !config.ContainsLoadedFile(configPath)) + { + _preStartupUnknownElementsConfiguration = config; + ProjectRootElementCache.SetUnknownElementsConfiguration(UnknownElementsConfiguration.Merge(config, UnknownElementsConfiguration.LoadFromFile(configPath))); + } + } + + /// + /// Restores the parse configuration to the state before was called. + /// + public void UnloadParseConfigForStartup() + { + if (_preStartupUnknownElementsConfiguration is not null) { - _unknownElementsConfiguration = value; - ProjectRootElementCache.UnknownElementsConfiguration = value; + ProjectRootElementCache.SetUnknownElementsConfiguration(_preStartupUnknownElementsConfiguration); + _preStartupUnknownElementsConfiguration = null; } } diff --git a/src/Build/Evaluation/Evaluator.cs b/src/Build/Evaluation/Evaluator.cs index 10d3cbc6718..5efc97948f4 100644 --- a/src/Build/Evaluation/Evaluator.cs +++ b/src/Build/Evaluation/Evaluator.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -330,14 +330,14 @@ private void InitializeUnknownElementsConfiguration() } else if (!_unknownElementsConfiguration.ContainsLoadedFile(projectConfigPath)) { - _unknownElementsConfiguration = _unknownElementsConfiguration.Merge(UnknownElementsConfiguration.LoadFromFile(projectConfigPath)); + _unknownElementsConfiguration = UnknownElementsConfiguration.Merge(_unknownElementsConfiguration, UnknownElementsConfiguration.LoadFromFile(projectConfigPath)); } else { return; } - _projectRootElementCache.UnknownElementsConfiguration = _unknownElementsConfiguration; + _projectRootElementCache.SetUnknownElementsConfiguration(_unknownElementsConfiguration); } /// diff --git a/src/Build/Evaluation/ProjectRootElementCacheBase.cs b/src/Build/Evaluation/ProjectRootElementCacheBase.cs index 6d725586905..198c958ee28 100644 --- a/src/Build/Evaluation/ProjectRootElementCacheBase.cs +++ b/src/Build/Evaluation/ProjectRootElementCacheBase.cs @@ -12,7 +12,7 @@ internal abstract class ProjectRootElementCacheBase { public bool LoadProjectsReadOnly { get; protected set; } - internal UnknownElementsConfiguration UnknownElementsConfiguration { get; set; } + public UnknownElementsConfiguration UnknownElementsConfiguration { get; protected set; } /// /// Handler for which project root element just got added to the cache @@ -72,6 +72,17 @@ internal abstract ProjectRootElement Get(string projectFile, OpenProjectRootElem internal abstract void DiscardAnyWeakReference(ProjectRootElement projectRootElement); + internal void SetUnknownElementsConfiguration(UnknownElementsConfiguration configuration) + { + if (UnknownElementsConfiguration.Equals(UnknownElementsConfiguration, configuration)) + { + return; + } + + DiscardImplicitReferences(); + UnknownElementsConfiguration = configuration; + } + /// /// Raises the event. /// diff --git a/src/Build/Evaluation/UnknownElementsConfiguration.cs b/src/Build/Evaluation/UnknownElementsConfiguration.cs index cbe8d096760..f891681ad1c 100644 --- a/src/Build/Evaluation/UnknownElementsConfiguration.cs +++ b/src/Build/Evaluation/UnknownElementsConfiguration.cs @@ -50,13 +50,21 @@ private UnknownElementsConfiguration(ITranslator translator) internal static UnknownElementsConfiguration Empty { get; } = new UnknownElementsConfiguration(); - /// - /// Returns true if this config has the same set of loaded files as the other config. - /// Used by worker nodes to detect if the config changed between builds. - /// - internal bool HasSameLoadedFiles(UnknownElementsConfiguration other) + public static bool Equals(UnknownElementsConfiguration? left, UnknownElementsConfiguration? right) { - return _loadedConfigFiles.SetEquals(other._loadedConfigFiles); + if (ReferenceEquals(left, right)) + { + return true; + } + + if (left is null || right is null) + { + return false; + } + + return left._loadedConfigFiles.SetEquals(right._loadedConfigFiles) + && CollectionHelpers.DictionaryEquals(left._allowedAttributes, right._allowedAttributes, HashSet.CreateSetComparer()) + && CollectionHelpers.DictionaryEquals(left._allowedChildren, right._allowedChildren, HashSet.CreateSetComparer()); } /// @@ -138,20 +146,21 @@ internal bool CheckSkipElement(string parentElementName, string childElementName return $"Loaded Directory.Parse.config from: {string.Join(", ", _loadedConfigFiles)}"; } - internal UnknownElementsConfiguration Merge(UnknownElementsConfiguration other) + internal static UnknownElementsConfiguration Merge(UnknownElementsConfiguration left, UnknownElementsConfiguration right) { - ArgumentNullException.ThrowIfNull(other); + ArgumentNullException.ThrowIfNull(left); + ArgumentNullException.ThrowIfNull(right); var merged = new UnknownElementsConfiguration(); - UnionEntries(merged._allowedAttributes, _allowedAttributes); - UnionEntries(merged._allowedAttributes, other._allowedAttributes); - UnionEntries(merged._allowedChildren, _allowedChildren); - UnionEntries(merged._allowedChildren, other._allowedChildren); - merged._loadedConfigFiles.UnionWith(_loadedConfigFiles); - merged._loadedConfigFiles.UnionWith(other._loadedConfigFiles); - MergeSkippedItems(merged._skippedItems, _skippedItems); - MergeSkippedItems(merged._skippedItems, other._skippedItems); + UnionEntries(merged._allowedAttributes, left._allowedAttributes); + UnionEntries(merged._allowedAttributes, right._allowedAttributes); + UnionEntries(merged._allowedChildren, left._allowedChildren); + UnionEntries(merged._allowedChildren, right._allowedChildren); + merged._loadedConfigFiles.UnionWith(left._loadedConfigFiles); + merged._loadedConfigFiles.UnionWith(right._loadedConfigFiles); + MergeSkippedItems(merged._skippedItems, left._skippedItems); + MergeSkippedItems(merged._skippedItems, right._skippedItems); return merged; } diff --git a/src/Framework/Utilities/CollectionHelpers.cs b/src/Framework/Utilities/CollectionHelpers.cs index 624502e3196..01a2d332306 100644 --- a/src/Framework/Utilities/CollectionHelpers.cs +++ b/src/Framework/Utilities/CollectionHelpers.cs @@ -54,7 +54,7 @@ internal static bool SetEquivalent(IEnumerable a, IEnumerable b) return a.ToHashSet().SetEquals(b); } - internal static bool DictionaryEquals(IReadOnlyDictionary a, IReadOnlyDictionary b) + internal static bool DictionaryEquals(IReadOnlyDictionary a, IReadOnlyDictionary b, IEqualityComparer valueComparer = null) { if (a.Count != b.Count) { @@ -68,9 +68,19 @@ internal static bool DictionaryEquals(IReadOnlyDictionary a, IReadOn return false; } - if (!Equals(aKvp.Value, bValue)) + if (valueComparer != null) { - return false; + if (!valueComparer.Equals(aKvp.Value, bValue)) + { + return false; + } + } + else + { + if (!Equals(aKvp.Value, bValue)) + { + return false; + } } } diff --git a/src/MSBuild/XMake.cs b/src/MSBuild/XMake.cs index 989fbda0b6d..8044cf6223b 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -1708,6 +1708,9 @@ .. distributedLoggerRecords.Select(d => d.CentralLogger).Where(l => l is not nul // globalProperties collection contains values only from CommandLine at this stage populated by ProcessCommandLineSwitches projectCollection.PropertiesFromCommandLine = [.. globalProperties.Keys]; + // Load startup-directory parse config into the collection's cache before any project is loaded. + projectCollection.LoadParseConfigForStartup(Environment.CurrentDirectory); + if (toolsVersion != null && !projectCollection.ContainsToolset(toolsVersion)) { ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, toolsVersion); @@ -2006,6 +2009,7 @@ .. distributedLoggerRecords.Select(d => d.CentralLogger).Where(l => l is not nul } finally { + projectCollection?.UnloadParseConfigForStartup(); projectCollection?.Dispose(); FileUtilities.ClearCacheDirectory(); From af672ecd3243d94a450f665925834925c9a26cfa Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Mon, 3 Aug 2026 09:29:50 -0400 Subject: [PATCH 04/20] Make UnknownElementsConfiguration config parameter explicit on all validation methods Remove default null from config parameter on VerifyThrowProjectNoChildElements, VerifyThrowProjectNoAttributes, VerifyThrowProjectAttributes, and ThrowIfProjectInvalidChildElement. All callers must now explicitly pass the config or null. Fix TaskRegistry.VerifyThrowProjectNoChildElements to pass the config from the containing project's cache. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- src/Build/Instance/TaskRegistry.cs | 2 +- src/Build/Xml/ProjectXmlUtilities.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Build/Instance/TaskRegistry.cs b/src/Build/Instance/TaskRegistry.cs index d3114ec80bf..dc506f45b7a 100644 --- a/src/Build/Instance/TaskRegistry.cs +++ b/src/Build/Instance/TaskRegistry.cs @@ -320,7 +320,7 @@ private static void RegisterTasksFromUsingTaskElement if (String.IsNullOrEmpty(taskFactory) || taskFactory.Equals(RegisteredTaskRecord.AssemblyTaskFactory, StringComparison.OrdinalIgnoreCase) || taskFactory.Equals(RegisteredTaskRecord.TaskHostFactory, StringComparison.OrdinalIgnoreCase)) { - ProjectXmlUtilities.VerifyThrowProjectNoChildElements(projectUsingTaskXml.XmlElement); + ProjectXmlUtilities.VerifyThrowProjectNoChildElements(projectUsingTaskXml.XmlElement, projectUsingTaskXml.ContainingProject.ProjectRootElementCache.UnknownElementsConfiguration); } if (projectUsingTaskXml.AssemblyFile.Length > 0) diff --git a/src/Build/Xml/ProjectXmlUtilities.cs b/src/Build/Xml/ProjectXmlUtilities.cs index 458198133e6..467aa185ce0 100644 --- a/src/Build/Xml/ProjectXmlUtilities.cs +++ b/src/Build/Xml/ProjectXmlUtilities.cs @@ -56,7 +56,7 @@ private static XmlElementChildIterator GetChildElements(XmlElementWithLocation e /// /// Throw an invalid project exception if there are any child elements at all /// - internal static void VerifyThrowProjectNoChildElements(XmlElementWithLocation element, UnknownElementsConfiguration config = null) + internal static void VerifyThrowProjectNoChildElements(XmlElementWithLocation element, UnknownElementsConfiguration config) { foreach (var child in GetVerifyThrowProjectChildElements(element)) { @@ -138,7 +138,7 @@ internal static void VerifyThrowProjectAttributeEitherMissingOrNotEmpty(XmlEleme /// /// If there are any attributes on the element, throws an InvalidProjectFileException complaining that the attribute is not valid on this element. /// - internal static void VerifyThrowProjectNoAttributes(XmlElementWithLocation element, UnknownElementsConfiguration config = null) + internal static void VerifyThrowProjectNoAttributes(XmlElementWithLocation element, UnknownElementsConfiguration config) { if (element.HasAttributes) { @@ -178,7 +178,7 @@ internal static void VerifyThrowProjectRequiredAttribute(XmlElementWithLocation /// Verify that all attributes on the element are on the list of legal attributes. /// When genericElementName is provided, only that name is checked in the config (not the actual element name). /// - internal static void VerifyThrowProjectAttributes(XmlElementWithLocation element, HashSet validAttributes, UnknownElementsConfiguration config = null, string genericElementName = null) + internal static void VerifyThrowProjectAttributes(XmlElementWithLocation element, HashSet validAttributes, UnknownElementsConfiguration config, string genericElementName = null) { foreach (XmlAttributeWithLocation attribute in element.Attributes) { @@ -200,7 +200,7 @@ internal static void VerifyThrowProjectAttributes(XmlElementWithLocation element /// If the element is allowed, it is silently skipped. /// /// True if the element was skipped (caller should continue), false if the element was not in config and an exception was thrown. - internal static bool ThrowIfProjectInvalidChildElement(string name, string parentName, ElementLocation location, UnknownElementsConfiguration config = null) + internal static bool ThrowIfProjectInvalidChildElement(string name, string parentName, ElementLocation location, UnknownElementsConfiguration config) { if (config?.CheckSkipElement(parentName, name) == true) { From 1d70e71684a180baf1cc739144f378e403f08e33 Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Mon, 3 Aug 2026 11:54:54 -0400 Subject: [PATCH 05/20] Simplify config sources: env var + project directory walk only Remove MSBuild exe-dir and user-profile config loading. Remove startingDirectory parameter from LoadGlobalConfig. Config is now discovered from: - MSBUILD_PARSE_CONFIG environment variable (always) - Project file directory walk via LoadParseConfigForStartup (CLI path) XMake.BuildProject passes the project file's directory to LoadParseConfigForStartup instead of Environment.CurrentDirectory. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- .../UnknownElementsConfiguration.cs | 26 +------------------ src/MSBuild/XMake.cs | 4 +-- 2 files changed, 3 insertions(+), 27 deletions(-) diff --git a/src/Build/Evaluation/UnknownElementsConfiguration.cs b/src/Build/Evaluation/UnknownElementsConfiguration.cs index f891681ad1c..6ffc76d04a6 100644 --- a/src/Build/Evaluation/UnknownElementsConfiguration.cs +++ b/src/Build/Evaluation/UnknownElementsConfiguration.cs @@ -26,8 +26,6 @@ internal sealed class UnknownElementsConfiguration : ITranslatable internal const string ConfigFileName = "Directory.Parse.config"; internal const string EnvironmentVariableName = "MSBUILD_PARSE_CONFIG"; - private const string UserProfileSubfolder = ".msbuild"; - private Dictionary> _allowedAttributes; private Dictionary> _allowedChildren; private HashSet _loadedConfigFiles; @@ -172,22 +170,10 @@ internal static UnknownElementsConfiguration LoadFromFile(string filePath) return config; } - internal static UnknownElementsConfiguration LoadGlobalConfig(string? startingDirectory = null) + internal static UnknownElementsConfiguration LoadGlobalConfig() { var config = new UnknownElementsConfiguration(); - string? msbuildExeDir = BuildEnvironmentHelper.Instance?.CurrentMSBuildToolsDirectory; - if (!string.IsNullOrEmpty(msbuildExeDir)) - { - config.LoadFile(Path.Combine(msbuildExeDir, ConfigFileName)); - } - - string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - if (!string.IsNullOrEmpty(userProfile)) - { - config.LoadFile(Path.Combine(userProfile, UserProfileSubfolder, ConfigFileName)); - } - string? envValue = Environment.GetEnvironmentVariable(EnvironmentVariableName); if (!string.IsNullOrEmpty(envValue)) { @@ -202,16 +188,6 @@ internal static UnknownElementsConfiguration LoadGlobalConfig(string? startingDi } } - // Walk up from the starting directory looking for a Directory.Parse.config - if (!string.IsNullOrEmpty(startingDirectory)) - { - string directoryConfigPath = FileUtilities.GetPathOfFileAbove(ConfigFileName, startingDirectory!); - if (!string.IsNullOrEmpty(directoryConfigPath) && !config.ContainsLoadedFile(directoryConfigPath)) - { - config.LoadFile(directoryConfigPath); - } - } - return config; } diff --git a/src/MSBuild/XMake.cs b/src/MSBuild/XMake.cs index 8044cf6223b..4d9645f7a9a 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -1708,8 +1708,8 @@ .. distributedLoggerRecords.Select(d => d.CentralLogger).Where(l => l is not nul // globalProperties collection contains values only from CommandLine at this stage populated by ProcessCommandLineSwitches projectCollection.PropertiesFromCommandLine = [.. globalProperties.Keys]; - // Load startup-directory parse config into the collection's cache before any project is loaded. - projectCollection.LoadParseConfigForStartup(Environment.CurrentDirectory); + // Load parse config from the project file's directory before any project is loaded. + projectCollection.LoadParseConfigForStartup(Path.GetDirectoryName(Path.GetFullPath(projectFile))); if (toolsVersion != null && !projectCollection.ContainsToolset(toolsVersion)) { From f163eba92ca4332f33017c06bb25aac68bfb9433 Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Mon, 3 Aug 2026 12:10:19 -0400 Subject: [PATCH 06/20] Embed Directory.Parse.config files in binlog via ProjectImportedEventArgs Log each loaded config file as a ProjectImportedEventArgs during evaluation start, which causes the binary logger to embed the file content in the binlog's ProjectImportArchive. This allows binlog viewers to inspect what parse config was active during the build. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- src/Build/Evaluation/Evaluator.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/Build/Evaluation/Evaluator.cs b/src/Build/Evaluation/Evaluator.cs index 5efc97948f4..a83e05a5d4e 100644 --- a/src/Build/Evaluation/Evaluator.cs +++ b/src/Build/Evaluation/Evaluator.cs @@ -707,6 +707,23 @@ private void Evaluate() if (configMessage is not null) { _evaluationLoggingContext.LogCommentFromText(MessageImportance.Low, configMessage); + + // Embed the config files in the binlog by logging them as imports + foreach (string configFile in _unknownElementsConfiguration.LoadedConfigFiles) + { + var importArgs = new ProjectImportedEventArgs( + -1, + -1, + "Loaded Directory.Parse.config: {0}", + configFile) + { + BuildEventContext = _evaluationLoggingContext.BuildEventContext, + ImportedProjectFile = configFile, + ProjectFile = _projectRootElement.FullPath, + }; + + _evaluationLoggingContext.LogBuildEvent(importArgs); + } } // Track loads only after start of evaluation was actually logged From 4c55cde8c098dff128208c50f4a11690c33acf97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Provazn=C3=ADk?= Date: Tue, 4 Aug 2026 14:09:32 +0200 Subject: [PATCH 07/20] Update src/Build/Construction/ProjectRootElement.cs --- src/Build/Construction/ProjectRootElement.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Build/Construction/ProjectRootElement.cs b/src/Build/Construction/ProjectRootElement.cs index b6f0e1350d4..3aaa3497cd0 100644 --- a/src/Build/Construction/ProjectRootElement.cs +++ b/src/Build/Construction/ProjectRootElement.cs @@ -273,7 +273,9 @@ private ProjectRootElement(XmlDocumentWithLocation document, ProjectRootElementC /// private ProjectRootElement(XmlDocumentWithLocation document) { - ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); + // This constructor is only used by ThrowIfDocumentHasParsingErrors to check whether a document + // parses; it deliberately has no cache, so there is no configuration to apply. + ProjectParser.Parse(document, this, ProjectRootElementCache?.UnknownElementsConfiguration); } /// From ae86faa4798000c69f606b3fea24b912049814d7 Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Tue, 4 Aug 2026 11:27:06 -0400 Subject: [PATCH 08/20] Wire ImportGroup child validation through UnknownElementsConfiguration ImportGroup was using VerifyThrowInvalidProject directly for unknown children, bypassing the config check. Changed to check CheckSkipElement first. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- src/Build/Evaluation/ProjectParser.cs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/Build/Evaluation/ProjectParser.cs b/src/Build/Evaluation/ProjectParser.cs index 722ba86962d..f6dd2fbbd96 100644 --- a/src/Build/Evaluation/ProjectParser.cs +++ b/src/Build/Evaluation/ProjectParser.cs @@ -437,12 +437,19 @@ private ProjectImportGroupElement ParseProjectImportGroupElement(XmlElementWithL foreach (XmlElementWithLocation childElement in ProjectXmlUtilities.GetVerifyThrowProjectChildElements(element)) { - ProjectErrorUtilities.VerifyThrowInvalidProject( - childElement.Name == XMakeElements.import, - childElement.Location, - "UnrecognizedChildElement", - childElement.Name, - element.Name); + if (childElement.Name != XMakeElements.import) + { + if (_unknownElementsConfiguration?.CheckSkipElement(element.Name, childElement.Name) == true) + { + continue; + } + + ProjectErrorUtilities.ThrowInvalidProject( + childElement.Location, + "UnrecognizedChildElement", + childElement.Name, + element.Name); + } ProjectImportElement item = ParseProjectImportElement(childElement, importGroup); @@ -567,7 +574,7 @@ private ProjectUsingTaskElement ParseProjectUsingTaskElement(XmlElementWithLocat foundTaskElement = true; break; default: - if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, "Task", element.Location, _unknownElementsConfiguration)) + if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, element.Name, element.Location, _unknownElementsConfiguration)) { continue; } From 93625a3da30f3890180e63b96dc713a6a419031f Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Tue, 4 Aug 2026 11:48:21 -0400 Subject: [PATCH 09/20] Update spec documentation to reflect current implementation - Remove exe-dir and user-profile from discovery sources - Document env var + project directory walk as the two sources - Add ImportGroup, Task to valid children; add ItemDefinition to generic names - Add ProjectExtensions to not-applicable children list - Document LoadParseConfigForStartup/UnloadParseConfigForStartup API - Add feature flag, binlog embedding, and XML format examples Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- documentation/specs/directory-parse-config.md | 96 ++++++++++--------- 1 file changed, 50 insertions(+), 46 deletions(-) diff --git a/documentation/specs/directory-parse-config.md b/documentation/specs/directory-parse-config.md index 94e514b72c7..00566707685 100644 --- a/documentation/specs/directory-parse-config.md +++ b/documentation/specs/directory-parse-config.md @@ -30,11 +30,9 @@ This enables compatibility scenarios where project files may include attributes/ Matching is case-insensitive. Entries with missing or empty `Element`/`Name` attributes are silently ignored. Unrecognized sections or elements are ignored. -For more details on `Element`: +### Valid `IgnoreAttributes` Elements -### Valid Attribute Names - -For attributes the `Name` can be the name of the following MSBuild elements: +The `Element` attribute in `` entries can be: - `Target` - `PropertyGroup` - `ItemGroup` @@ -47,19 +45,24 @@ For attributes the `Name` can be the name of the following MSBuild elements: - `Otherwise` - `ProjectExtensions` -Although the following are not elements, they can be specified to target attributes on these types of elements: -- `Property`: attributes on elements inside a `PropertyGroup` -- `Item`: attributes on elements inside a `ItemGroup` -- `Metadata`: attributes on elements inside an `Item` or `ItemDefinitionGroup` -- `Parameter`: attributes on elements in a ParameterGroup inside a UsingTask -- `UsingTaskBody`: attributes on Task elements inside a UsingTask +Generic names for dynamically-named elements: + +| Generic Name | Applies To | +|---|---| +| `Property` | Any property element (child of `PropertyGroup`) | +| `Item` | Any item element (child of `ItemGroup`) | +| `ItemDefinition` | Any item definition element (child of `ItemDefinitionGroup`) | +| `Metadata` | Any metadata element (child of an `Item` or `ItemDefinition`) | +| `Parameter` | Any parameter element in a `ParameterGroup` inside `UsingTask` | +| `UsingTaskBody` | The `Task` element inside `UsingTask` | -### Valid Element Names +### Valid `IgnoreChildren` Elements -The following names can be specified: +The `Element` attribute in `` entries can be: - `Project` - `Import` - `ImportGroup` +- `Task` - `UsingTask` - `OnError` - `Output` @@ -67,66 +70,67 @@ The following names can be specified: - `When` - `Otherwise` -The following cannot be specified since their children are by definition always valid: +Not applicable (children are free-form by design): + - `Target` - `PropertyGroup` - `ItemGroup` +- `ItemDefinitionGroup` - `ProjectExtensions` ## Discovery and Loading -Configuration files are discovered and merged additively: +Configuration is discovered from two sources: + +1. **`MSBUILD_PARSE_CONFIG` environment variable** — Semicolon-separated (Windows) or colon-separated (Unix) list of config file paths. Always loaded when a `ProjectCollection` is created. + +2. **Project directory walk** — The CLI walks up from the target project file's directory looking for `Directory.Parse.config` (same pattern as `Directory.Build.rsp`). Called via `ProjectCollection.LoadParseConfigForStartup(directory)` before any project is loaded. + +These are merged additively — entries from either source are combined. -1. **Global config at build start** - - Next to the MSBuild executable - - User profile: `%USERPROFILE%\.msbuild\Directory.Parse.config` (Windows) or `$HOME/.msbuild/Directory.Parse.config` (Unix) - - Paths listed in `MSBUILD_PARSE_CONFIG`, split using the platform path separator - - The startup directory of MSBuild +## Public API -2. **Directory-specific config at evaluation start** - - MSBuild walks up from the project file's directory looking for `Directory.Parse.config` - - If found and that file was not already loaded globally, it is loaded and merged for that evaluation +### `ProjectCollection.LoadParseConfigForStartup(string startingDirectory)` -## Centralized Loading (BuildManager) +Walks up from `startingDirectory` to find a `Directory.Parse.config`, merges it with the current config, and sets it on the cache. Must be called before loading projects. Call `UnloadParseConfigForStartup()` after the build to restore the previous state. -In a normal build flow, the main node loads global config once during `BuildManager.BeginBuild()`. The config is: -- Stored on `BuildParameters.UnknownElementsConfiguration` -- Serialized to worker nodes via the standard `ITranslatable` mechanism -- Set on the shared `ProjectRootElementCache`, so parsing uses the same configuration +### `ProjectCollection.UnloadParseConfigForStartup()` -At evaluation start, MSBuild may merge in one additional `Directory.Parse.config` discovered from the project file's directory walk. +Restores the parse configuration to the state before `LoadParseConfigForStartup` was called. -Users of the `ProjectCollection` API can also set `ProjectCollection.UnknownElementsConfiguration` directly, which flows into `BuildParameters` when builds are started. ## Logging -During evaluation, two low-importance messages can be logged to the binary log: +- **Config files loaded**: Logged at evaluation start (`MessageImportance.Low`). Lists all loaded config file paths. +- **Config files embedded**: Each loaded config file is logged as a `ProjectImportedEventArgs`, causing the binary logger to embed the file content in the binlog. +- **Skipped items summary**: Logged after evaluation completes (`MessageImportance.Low`). Lists all skipped attributes/elements with occurrence counts. -- **Config files loaded**: Lists all discovered and loaded config file paths. -- **Skipped items summary**: Lists all unrecognized attributes/elements that were skipped, with occurrence counts. This is logged after evaluation work has completed so it reflects actual skips from that evaluation. +## Feature Flag -Example log messages: -``` -Loaded Directory.Parse.config from: C:\repo\Directory.Parse.config, C:\Users\me\.msbuild\Directory.Parse.config -Skipped unrecognized items allowed by Directory.Parse.config: Attribute:Target:CustomAttr (2 occurrences); Element:Project:Widget (1 occurrence) -``` +Set `MSBUILD_DISABLE_PARSE_CONFIG=1` to disable all automatic config loading. ## Examples -### Allow a custom attribute on Target elements +### Allow a custom attribute on all Target elements -Directory.Parse.config: -``` -Attribute:Target:CustomAttr +```xml + + + + + ``` -This allows `` without error. +Allows `` without error. ### Allow a custom child element under Project -Directory.Parse.config: -``` -Element:Project:ToolConfiguration +```xml + + + + + ``` -This allows `` as a direct child of `` without error. +Allows `` as a direct child of `` without error. From 4f795cbc13e3da75e70710e04320dcc088dfbdc2 Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Tue, 4 Aug 2026 12:01:26 -0400 Subject: [PATCH 10/20] Embed config files in binlog via projectImportsCollector instead of fake imports Replace ProjectImportedEventArgs approach (which polluted the imports tree) with the same pattern used for .editorconfig files: collect paths during loading, then add them via projectImportsCollector.AddFile() in BinaryLogger.Shutdown. Config files appear as embedded content without being counted as project imports. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- src/Build/Evaluation/Evaluator.cs | 17 ----------------- .../Evaluation/UnknownElementsConfiguration.cs | 17 +++++++++++++++++ src/Build/Logging/BinaryLogger/BinaryLogger.cs | 8 ++++++++ 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/Build/Evaluation/Evaluator.cs b/src/Build/Evaluation/Evaluator.cs index a83e05a5d4e..5efc97948f4 100644 --- a/src/Build/Evaluation/Evaluator.cs +++ b/src/Build/Evaluation/Evaluator.cs @@ -707,23 +707,6 @@ private void Evaluate() if (configMessage is not null) { _evaluationLoggingContext.LogCommentFromText(MessageImportance.Low, configMessage); - - // Embed the config files in the binlog by logging them as imports - foreach (string configFile in _unknownElementsConfiguration.LoadedConfigFiles) - { - var importArgs = new ProjectImportedEventArgs( - -1, - -1, - "Loaded Directory.Parse.config: {0}", - configFile) - { - BuildEventContext = _evaluationLoggingContext.BuildEventContext, - ImportedProjectFile = configFile, - ProjectFile = _projectRootElement.FullPath, - }; - - _evaluationLoggingContext.LogBuildEvent(importArgs); - } } // Track loads only after start of evaluation was actually logged diff --git a/src/Build/Evaluation/UnknownElementsConfiguration.cs b/src/Build/Evaluation/UnknownElementsConfiguration.cs index 6ffc76d04a6..df72aa142a2 100644 --- a/src/Build/Evaluation/UnknownElementsConfiguration.cs +++ b/src/Build/Evaluation/UnknownElementsConfiguration.cs @@ -26,6 +26,21 @@ internal sealed class UnknownElementsConfiguration : ITranslatable internal const string ConfigFileName = "Directory.Parse.config"; internal const string EnvironmentVariableName = "MSBUILD_PARSE_CONFIG"; + /// + /// Static collection of config file paths to embed in the binlog. + /// Populated during config loading, consumed by BinaryLogger.Shutdown. + /// + private static ConcurrentBag s_binlogEmbedPaths = new(); + + /// Paths collected for binlog embedding. + internal static IEnumerable BinlogEmbedPaths => s_binlogEmbedPaths; + + /// Clears the embed paths after they've been written to the binlog. + internal static void ClearBinlogEmbedPaths() + { + s_binlogEmbedPaths = new ConcurrentBag(); + } + private Dictionary> _allowedAttributes; private Dictionary> _allowedChildren; private HashSet _loadedConfigFiles; @@ -264,6 +279,8 @@ private void LoadFile(string filePath) return; } + s_binlogEmbedPaths.Add(fullPath); + try { var settings = new System.Xml.XmlReaderSettings { DtdProcessing = System.Xml.DtdProcessing.Prohibit }; diff --git a/src/Build/Logging/BinaryLogger/BinaryLogger.cs b/src/Build/Logging/BinaryLogger/BinaryLogger.cs index e5d73a3bf3f..59e4b96a463 100644 --- a/src/Build/Logging/BinaryLogger/BinaryLogger.cs +++ b/src/Build/Logging/BinaryLogger/BinaryLogger.cs @@ -511,6 +511,14 @@ public void Shutdown() projectImportsCollector.AddFile(filePath); } EditorConfigParser.ClearEditorConfigFilePaths(); + + // Write the Directory.Parse.config file paths to the log + foreach (var filePath in Evaluation.UnknownElementsConfiguration.BinlogEmbedPaths) + { + projectImportsCollector.AddFile(filePath); + } + Evaluation.UnknownElementsConfiguration.ClearBinlogEmbedPaths(); + projectImportsCollector.Close(); if (CollectProjectImports == ProjectImportsCollectionMode.Embed) From e6882624c8642880e861fae5a55d0872b4de692b Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Tue, 4 Aug 2026 13:15:05 -0400 Subject: [PATCH 11/20] Clarify Item attributes --- documentation/specs/directory-parse-config.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/documentation/specs/directory-parse-config.md b/documentation/specs/directory-parse-config.md index 00566707685..f224b009abf 100644 --- a/documentation/specs/directory-parse-config.md +++ b/documentation/specs/directory-parse-config.md @@ -56,6 +56,8 @@ Generic names for dynamically-named elements: | `Parameter` | Any parameter element in a `ParameterGroup` inside `UsingTask` | | `UsingTaskBody` | The `Task` element inside `UsingTask` | +Note: `Item` only applies to attributes with leading underscores as any other attributes are interpreted as metadata names. + ### Valid `IgnoreChildren` Elements The `Element` attribute in `` entries can be: From ce7cf93eb31358abf2c98ae82ce9f001846639b9 Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Tue, 4 Aug 2026 13:41:03 -0400 Subject: [PATCH 12/20] Add comprehensive data-driven tests for all documented elements Theory tests with MemberData cover all IgnoreAttributes elements (Target, PropertyGroup, Property, ItemGroup, Item, Import, ImportGroup, UsingTask, OnError, Output, Choose, Otherwise, ItemDefinition, Metadata, UsingTaskBody, Parameter, ProjectExtensions) and all IgnoreChildren elements (Project, UsingTask, ImportGroup, Choose, When, Otherwise, Task). Each case is tested both for skip-when-configured and throw-without-config. Item and ItemDefinition are excluded from throw tests since they accept any valid XML name as metadata-as-attribute. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- .../UnknownElementsConfiguration_Tests.cs | 146 ++++++++---------- 1 file changed, 63 insertions(+), 83 deletions(-) diff --git a/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs b/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs index b3657d90e4a..f13888628e5 100644 --- a/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs +++ b/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Collections.Generic; using System.IO; using Microsoft.Build.Exceptions; using Microsoft.Build.Evaluation; @@ -65,19 +66,6 @@ public void IsCaseInsensitive() config.CheckSkipAttribute("Target", "Foo").ShouldBeTrue(); } - [Fact] - public void RejectsNonAllowedItems() - { - string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, @""); - - var config = UnknownElementsConfiguration.LoadFromFile(configPath); - - config.CheckSkipAttribute("Target", "Bar").ShouldBeFalse(); - config.CheckSkipElement("Target", "Foo").ShouldBeFalse(); - config.CheckSkipAttribute("ItemGroup", "Foo").ShouldBeFalse(); - } - [Fact] public void IgnoresInvalidEntries() { @@ -172,108 +160,100 @@ public void RecordsSkippedItems() summary.ShouldContain("2 occurrences"); } - [Fact] - public void GetLoadedConfigsMessageReturnsNullWhenEmpty() - { - var config = UnknownElementsConfiguration.LoadFromFile(Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName)); - config.GetLoadedConfigsMessage().ShouldBeNull(); - } - - [Fact] - public void GetLoadedConfigsMessageListsFiles() + [Theory] + [MemberData(nameof(AttributeSkipCases))] + public void AllowedAttributeIsSkipped(string configElement, string configName, string projectXml) { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, @""); - - var config = UnknownElementsConfiguration.LoadFromFile(configPath); - - string message = config.GetLoadedConfigsMessage(); - message.ShouldNotBeNull(); - message.ShouldContain(_testDir); - } - - [Fact] - public void AllowedAttributeDoesNotThrowDuringParsing() - { - string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, @""); - - string projectContent = @" - - - -"; - + File.WriteAllText(configPath, $@""); string projectFile = Path.Combine(_testDir, "test.proj"); - File.WriteAllText(projectFile, projectContent); + File.WriteAllText(projectFile, projectXml); - using (var projectCollection = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(configPath))) + using (var pc = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(configPath))) { - var project = new Project(projectFile, null, null, projectCollection); + var project = new Project(projectFile, null, null, pc, ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports); project.ShouldNotBeNull(); } } - [Fact] - public void NonAllowedAttributeStillThrows() + [Theory] + [MemberData(nameof(AttributeSkipCases))] + public void NonAllowedAttributeThrows(string configElement, string configName, string projectXml) { - string projectContent = @" - - - -"; - + _ = configElement; + _ = configName; string projectFile = Path.Combine(_testDir, "test.proj"); - File.WriteAllText(projectFile, projectContent); + File.WriteAllText(projectFile, projectXml); - using (var projectCollection = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName)))) + using (var pc = CreateProjectCollection(UnknownElementsConfiguration.Empty)) { - Should.Throw(() => new Project(projectFile, null, null, projectCollection)); + Should.Throw(() => new Project(projectFile, null, null, pc, ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports)); } } - [Fact] - public void AllowedChildElementDoesNotThrowDuringParsing() + [Theory] + [MemberData(nameof(ChildSkipCases))] + public void AllowedChildIsSkipped(string configElement, string configName, string projectXml) { string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); - File.WriteAllText(configPath, @""); - - string projectContent = @" - - - - -"; - + File.WriteAllText(configPath, $@""); string projectFile = Path.Combine(_testDir, "test.proj"); - File.WriteAllText(projectFile, projectContent); + File.WriteAllText(projectFile, projectXml); - using (var projectCollection = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(configPath))) + using (var pc = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(configPath))) { - var project = new Project(projectFile, null, null, projectCollection); + var project = new Project(projectFile, null, null, pc, ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports); project.ShouldNotBeNull(); } } - [Fact] - public void NonAllowedChildElementStillThrows() + [Theory] + [MemberData(nameof(ChildSkipCases))] + public void NonAllowedChildThrows(string configElement, string configName, string projectXml) { - string projectContent = @" - - - - -"; - + _ = configElement; + _ = configName; string projectFile = Path.Combine(_testDir, "test.proj"); - File.WriteAllText(projectFile, projectContent); + File.WriteAllText(projectFile, projectXml); - using (var projectCollection = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName)))) + using (var pc = CreateProjectCollection(UnknownElementsConfiguration.Empty)) { - Should.Throw(() => new Project(projectFile, null, null, projectCollection)); + Should.Throw(() => new Project(projectFile, null, null, pc, ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports)); } } + public static IEnumerable AttributeSkipCases => new[] + { + new object[] { "Target", "X", @"" }, + new object[] { "PropertyGroup", "X", @"1" }, + new object[] { "Property", "X", @"1" }, + new object[] { "ItemGroup", "X", @"" }, + new object[] { "Item", "_X", @"" }, + new object[] { "Import", "X", @"" }, + new object[] { "ImportGroup", "X", @"" }, + new object[] { "UsingTask", "X", @"" }, + new object[] { "OnError", "X", @"" }, + new object[] { "Output", "X", @"" }, + new object[] { "Choose", "X", @"1" }, + new object[] { "Otherwise", "X", @"12" }, + new object[] { "ItemDefinition", "_X", @"" }, + new object[] { "Metadata", "X", @"val" }, + new object[] { "UsingTaskBody", "X", @"" }, + new object[] { "Parameter", "X", @"" }, + new object[] { "ProjectExtensions", "X", @"bar" }, + }; + + public static IEnumerable ChildSkipCases => new[] + { + new object[] { "Project", "Custom", @"" }, + new object[] { "UsingTask", "Custom", @"" }, + new object[] { "ImportGroup", "Custom", @"" }, + new object[] { "Choose", "Custom", @"1" }, + new object[] { "When", "Custom", @"1" }, + new object[] { "Otherwise", "Custom", @"12" }, + new object[] { "Task", "Custom", @"" }, + }; + private static ProjectCollection CreateProjectCollection(UnknownElementsConfiguration config) { var projectCollection = new ProjectCollection(); From 19094811ebc205cf6b1164fedaf2b3e58db286fd Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Mon, 10 Aug 2026 16:21:12 -0400 Subject: [PATCH 13/20] Rename UnknownElementsConfiguration to ParserIgnoreConfiguration Pure mechanical rename of the class, file, and all references. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- ....cs => ParserIgnoreConfiguration_Tests.cs} | 56 +++++++-------- .../BackEnd/BuildManager/BuildManager.cs | 4 +- .../BackEnd/BuildManager/BuildParameters.cs | 16 ++--- src/Build/BackEnd/Node/OutOfProcNode.cs | 2 +- src/Build/Construction/ProjectRootElement.cs | 14 ++-- src/Build/Definition/ProjectCollection.cs | 26 +++---- src/Build/Evaluation/Evaluator.cs | 24 +++---- ...ration.cs => ParserIgnoreConfiguration.cs} | 26 +++---- src/Build/Evaluation/ProjectParser.cs | 68 +++++++++---------- .../Evaluation/ProjectRootElementCacheBase.cs | 8 +-- src/Build/Instance/TaskRegistry.cs | 4 +- .../Logging/BinaryLogger/BinaryLogger.cs | 6 +- src/Build/Microsoft.Build.csproj | 2 +- src/Build/Xml/ProjectXmlUtilities.cs | 8 +-- 14 files changed, 132 insertions(+), 132 deletions(-) rename src/Build.UnitTests/Evaluation/{UnknownElementsConfiguration_Tests.cs => ParserIgnoreConfiguration_Tests.cs} (82%) rename src/Build/Evaluation/{UnknownElementsConfiguration.cs => ParserIgnoreConfiguration.cs} (92%) diff --git a/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs b/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs similarity index 82% rename from src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs rename to src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs index f13888628e5..a19f0eba984 100644 --- a/src/Build.UnitTests/Evaluation/UnknownElementsConfiguration_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs @@ -13,11 +13,11 @@ namespace Microsoft.Build.UnitTests.Evaluation { - public class UnknownElementsConfiguration_Tests : IDisposable + public class ParserIgnoreConfiguration_Tests : IDisposable { private readonly string _testDir; - public UnknownElementsConfiguration_Tests() + public ParserIgnoreConfiguration_Tests() { _testDir = Path.Combine(Path.GetTempPath(), "MSBuildTest_UnknownElements_" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(_testDir); @@ -34,7 +34,7 @@ public void Dispose() [Fact] public void ParsesValidConfigFile() { - string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + string configPath = Path.Combine(_testDir, ParserIgnoreConfiguration.ConfigFileName); File.WriteAllText(configPath, @" @@ -45,7 +45,7 @@ public void ParsesValidConfigFile() "); - var config = UnknownElementsConfiguration.LoadFromFile(configPath); + var config = ParserIgnoreConfiguration.LoadFromFile(configPath); config.LoadedConfigFiles.Count.ShouldBe(1); config.CheckSkipAttribute("Target", "Foo").ShouldBeTrue(); @@ -56,10 +56,10 @@ public void ParsesValidConfigFile() [Fact] public void IsCaseInsensitive() { - string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + string configPath = Path.Combine(_testDir, ParserIgnoreConfiguration.ConfigFileName); File.WriteAllText(configPath, @""); - var config = UnknownElementsConfiguration.LoadFromFile(configPath); + var config = ParserIgnoreConfiguration.LoadFromFile(configPath); config.CheckSkipAttribute("target", "foo").ShouldBeTrue(); config.CheckSkipAttribute("TARGET", "FOO").ShouldBeTrue(); @@ -69,7 +69,7 @@ public void IsCaseInsensitive() [Fact] public void IgnoresInvalidEntries() { - string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + string configPath = Path.Combine(_testDir, ParserIgnoreConfiguration.ConfigFileName); File.WriteAllText(configPath, @" @@ -84,7 +84,7 @@ public void IgnoresInvalidEntries() "); - var config = UnknownElementsConfiguration.LoadFromFile(configPath); + var config = ParserIgnoreConfiguration.LoadFromFile(configPath); config.CheckSkipAttribute("Target", "ValidOne").ShouldBeTrue(); config.CheckSkipAttribute("Target", "Foo").ShouldBeFalse(); @@ -96,7 +96,7 @@ public void IgnoresInvalidEntries() [Fact] public void ReturnsEmptyWhenNoConfigExists() { - var config = UnknownElementsConfiguration.LoadFromFile(Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName)); + var config = ParserIgnoreConfiguration.LoadFromFile(Path.Combine(_testDir, ParserIgnoreConfiguration.ConfigFileName)); config.LoadedConfigFiles.Count.ShouldBe(0); config.CheckSkipAttribute("Target", "Foo").ShouldBeFalse(); @@ -105,16 +105,16 @@ public void ReturnsEmptyWhenNoConfigExists() [Fact] public void MergeCombinesEntriesAndDeduplicatesFiles() { - string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + string configPath = Path.Combine(_testDir, ParserIgnoreConfiguration.ConfigFileName); File.WriteAllText(configPath, @""); string extraConfigPath = Path.Combine(_testDir, "extra.config"); File.WriteAllText(extraConfigPath, @""); - var merged = UnknownElementsConfiguration.Merge( - UnknownElementsConfiguration.LoadFromFile(configPath), - UnknownElementsConfiguration.LoadFromFile(extraConfigPath)); - merged = UnknownElementsConfiguration.Merge(merged, UnknownElementsConfiguration.LoadFromFile(configPath)); + var merged = ParserIgnoreConfiguration.Merge( + ParserIgnoreConfiguration.LoadFromFile(configPath), + ParserIgnoreConfiguration.LoadFromFile(extraConfigPath)); + merged = ParserIgnoreConfiguration.Merge(merged, ParserIgnoreConfiguration.LoadFromFile(configPath)); merged.CheckSkipAttribute("Target", "Foo").ShouldBeTrue(); merged.CheckSkipElement("Project", "CustomThing").ShouldBeTrue(); @@ -127,27 +127,27 @@ public void LoadGlobalConfigLoadsEnvironmentVariablePaths() string envConfigPath = Path.Combine(_testDir, "env.config"); File.WriteAllText(envConfigPath, @""); - string oldEnv = Environment.GetEnvironmentVariable(UnknownElementsConfiguration.EnvironmentVariableName); + string oldEnv = Environment.GetEnvironmentVariable(ParserIgnoreConfiguration.EnvironmentVariableName); try { - Environment.SetEnvironmentVariable(UnknownElementsConfiguration.EnvironmentVariableName, envConfigPath); - var config = UnknownElementsConfiguration.LoadGlobalConfig(); + Environment.SetEnvironmentVariable(ParserIgnoreConfiguration.EnvironmentVariableName, envConfigPath); + var config = ParserIgnoreConfiguration.LoadGlobalConfig(); config.CheckSkipElement("Project", "CustomThing").ShouldBeTrue(); } finally { - Environment.SetEnvironmentVariable(UnknownElementsConfiguration.EnvironmentVariableName, oldEnv); + Environment.SetEnvironmentVariable(ParserIgnoreConfiguration.EnvironmentVariableName, oldEnv); } } [Fact] public void RecordsSkippedItems() { - string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + string configPath = Path.Combine(_testDir, ParserIgnoreConfiguration.ConfigFileName); File.WriteAllText(configPath, @""); - var config = UnknownElementsConfiguration.LoadFromFile(configPath); + var config = ParserIgnoreConfiguration.LoadFromFile(configPath); config.GetSkippedSummaryMessage().ShouldBeNull(); @@ -164,12 +164,12 @@ public void RecordsSkippedItems() [MemberData(nameof(AttributeSkipCases))] public void AllowedAttributeIsSkipped(string configElement, string configName, string projectXml) { - string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + string configPath = Path.Combine(_testDir, ParserIgnoreConfiguration.ConfigFileName); File.WriteAllText(configPath, $@""); string projectFile = Path.Combine(_testDir, "test.proj"); File.WriteAllText(projectFile, projectXml); - using (var pc = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(configPath))) + using (var pc = CreateProjectCollection(ParserIgnoreConfiguration.LoadFromFile(configPath))) { var project = new Project(projectFile, null, null, pc, ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports); project.ShouldNotBeNull(); @@ -185,7 +185,7 @@ public void NonAllowedAttributeThrows(string configElement, string configName, s string projectFile = Path.Combine(_testDir, "test.proj"); File.WriteAllText(projectFile, projectXml); - using (var pc = CreateProjectCollection(UnknownElementsConfiguration.Empty)) + using (var pc = CreateProjectCollection(ParserIgnoreConfiguration.Empty)) { Should.Throw(() => new Project(projectFile, null, null, pc, ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports)); } @@ -195,12 +195,12 @@ public void NonAllowedAttributeThrows(string configElement, string configName, s [MemberData(nameof(ChildSkipCases))] public void AllowedChildIsSkipped(string configElement, string configName, string projectXml) { - string configPath = Path.Combine(_testDir, UnknownElementsConfiguration.ConfigFileName); + string configPath = Path.Combine(_testDir, ParserIgnoreConfiguration.ConfigFileName); File.WriteAllText(configPath, $@""); string projectFile = Path.Combine(_testDir, "test.proj"); File.WriteAllText(projectFile, projectXml); - using (var pc = CreateProjectCollection(UnknownElementsConfiguration.LoadFromFile(configPath))) + using (var pc = CreateProjectCollection(ParserIgnoreConfiguration.LoadFromFile(configPath))) { var project = new Project(projectFile, null, null, pc, ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports); project.ShouldNotBeNull(); @@ -216,7 +216,7 @@ public void NonAllowedChildThrows(string configElement, string configName, strin string projectFile = Path.Combine(_testDir, "test.proj"); File.WriteAllText(projectFile, projectXml); - using (var pc = CreateProjectCollection(UnknownElementsConfiguration.Empty)) + using (var pc = CreateProjectCollection(ParserIgnoreConfiguration.Empty)) { Should.Throw(() => new Project(projectFile, null, null, pc, ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports)); } @@ -254,10 +254,10 @@ public void NonAllowedChildThrows(string configElement, string configName, strin new object[] { "Task", "Custom", @"" }, }; - private static ProjectCollection CreateProjectCollection(UnknownElementsConfiguration config) + private static ProjectCollection CreateProjectCollection(ParserIgnoreConfiguration config) { var projectCollection = new ProjectCollection(); - projectCollection.UnknownElementsConfiguration = config; + projectCollection.ParserIgnoreConfiguration = config; return projectCollection; } } diff --git a/src/Build/BackEnd/BuildManager/BuildManager.cs b/src/Build/BackEnd/BuildManager/BuildManager.cs index 67fc3edbfcc..d1f9048d640 100644 --- a/src/Build/BackEnd/BuildManager/BuildManager.cs +++ b/src/Build/BackEnd/BuildManager/BuildManager.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -620,7 +620,7 @@ public void BeginBuild(BuildParameters parameters) if (!Traits.Instance.EscapeHatches.DisableParseConfig) { - _buildParameters.UnknownElementsConfiguration = _buildParameters.ProjectRootElementCache.UnknownElementsConfiguration; + _buildParameters.ParserIgnoreConfiguration = _buildParameters.ProjectRootElementCache.ParserIgnoreConfiguration; } if (_buildParameters.UsesCachedResults() && _buildParameters.ProjectIsolationMode == ProjectIsolationMode.False) diff --git a/src/Build/BackEnd/BuildManager/BuildParameters.cs b/src/Build/BackEnd/BuildManager/BuildParameters.cs index a110cf50b92..f96ab1f0c83 100644 --- a/src/Build/BackEnd/BuildManager/BuildParameters.cs +++ b/src/Build/BackEnd/BuildManager/BuildParameters.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -240,7 +240,7 @@ public class BuildParameters : ITranslatable /// The configuration for allowed unknown attributes/elements during parsing. /// Loaded on the main node and serialized to worker nodes. /// - private UnknownElementsConfiguration _unknownElementsConfiguration; + private ParserIgnoreConfiguration _ParserIgnoreConfiguration; /// /// Constructor for those who intend to set all properties themselves. @@ -268,7 +268,7 @@ public BuildParameters(ProjectCollection projectCollection) _globalProperties = new PropertyDictionary(projectCollection.GlobalPropertiesCollection); _propertiesFromCommandLine = projectCollection.PropertiesFromCommandLine; - _unknownElementsConfiguration = projectCollection.UnknownElementsConfiguration; + _ParserIgnoreConfiguration = projectCollection.ParserIgnoreConfiguration; } /// @@ -337,7 +337,7 @@ internal BuildParameters(BuildParameters other, bool resetEnvironment = false) IsTelemetryEnabled = other.IsTelemetryEnabled; ProjectCacheDescriptor = other.ProjectCacheDescriptor; _enableTargetOutputLogging = other.EnableTargetOutputLogging; - _unknownElementsConfiguration = other._unknownElementsConfiguration; + _ParserIgnoreConfiguration = other._ParserIgnoreConfiguration; } /// @@ -834,10 +834,10 @@ public ProjectLoadSettings ProjectLoadSettings /// Gets or sets the configuration for allowed unknown attributes/elements during parsing. /// When set, this configuration is used for parsing and evaluation. /// - internal UnknownElementsConfiguration UnknownElementsConfiguration + internal ParserIgnoreConfiguration ParserIgnoreConfiguration { - get => _unknownElementsConfiguration; - set => _unknownElementsConfiguration = value; + get => _ParserIgnoreConfiguration; + set => _ParserIgnoreConfiguration = value; } /// @@ -1012,7 +1012,7 @@ void ITranslatable.Translate(ITranslator translator) translator.Translate(ref _reportFileAccesses); translator.Translate(ref _enableTargetOutputLogging); translator.Translate(ref _multiThreaded); - translator.Translate(ref _unknownElementsConfiguration, UnknownElementsConfiguration.FactoryForDeserialization); + translator.Translate(ref _ParserIgnoreConfiguration, ParserIgnoreConfiguration.FactoryForDeserialization); // ProjectRootElementCache is not transmitted. // ResetCaches is not transmitted. diff --git a/src/Build/BackEnd/Node/OutOfProcNode.cs b/src/Build/BackEnd/Node/OutOfProcNode.cs index 12ff5118703..31996716697 100644 --- a/src/Build/BackEnd/Node/OutOfProcNode.cs +++ b/src/Build/BackEnd/Node/OutOfProcNode.cs @@ -715,7 +715,7 @@ private void HandleNodeConfiguration(NodeConfiguration configuration) // Grab the system parameters. _buildParameters = configuration.BuildParameters; - s_projectRootElementCacheBase.SetUnknownElementsConfiguration(configuration.BuildParameters.UnknownElementsConfiguration); + s_projectRootElementCacheBase.SetParserIgnoreConfiguration(configuration.BuildParameters.ParserIgnoreConfiguration); _buildParameters.ProjectRootElementCache = s_projectRootElementCacheBase; diff --git a/src/Build/Construction/ProjectRootElement.cs b/src/Build/Construction/ProjectRootElement.cs index 3aaa3497cd0..1a0aaeb1aaf 100644 --- a/src/Build/Construction/ProjectRootElement.cs +++ b/src/Build/Construction/ProjectRootElement.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -181,7 +181,7 @@ internal ProjectRootElement(XmlReader xmlReader, ProjectRootElementCacheBase pro XmlDocumentWithLocation document = LoadDocument(xmlReader, preserveFormatting); - ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); + ProjectParser.Parse(document, this, ProjectRootElementCache.ParserIgnoreConfiguration); } private readonly bool _isEphemeral = false; @@ -217,7 +217,7 @@ private ProjectRootElement(ProjectRootElementCacheBase projectRootElementCache, document.Load(xr); } - ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); + ProjectParser.Parse(document, this, ProjectRootElementCache.ParserIgnoreConfiguration); } /// @@ -241,7 +241,7 @@ private ProjectRootElement( XmlDocumentWithLocation document = LoadDocument(path, preserveFormatting, projectRootElementCache.LoadProjectsReadOnly); - ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); + ProjectParser.Parse(document, this, ProjectRootElementCache.ParserIgnoreConfiguration); } /// @@ -261,7 +261,7 @@ private ProjectRootElement(XmlDocumentWithLocation document, ProjectRootElementC _directory = Environment.CurrentDirectory; IncrementVersion(); - ProjectParser.Parse(document, this, ProjectRootElementCache.UnknownElementsConfiguration); + ProjectParser.Parse(document, this, ProjectRootElementCache.ParserIgnoreConfiguration); } /// @@ -275,7 +275,7 @@ private ProjectRootElement(XmlDocumentWithLocation document) { // This constructor is only used by ThrowIfDocumentHasParsingErrors to check whether a document // parses; it deliberately has no cache, so there is no configuration to apply. - ProjectParser.Parse(document, this, ProjectRootElementCache?.UnknownElementsConfiguration); + ProjectParser.Parse(document, this, ProjectRootElementCache?.ParserIgnoreConfiguration); } /// @@ -1723,7 +1723,7 @@ private void ReloadFrom(Func documentProducer, bo RemoveAllChildren(); - ProjectParser.Parse(newDocument, this, ProjectRootElementCache.UnknownElementsConfiguration); + ProjectParser.Parse(newDocument, this, ProjectRootElementCache.ParserIgnoreConfiguration); MarkDirty("Project reloaded", null); } diff --git a/src/Build/Definition/ProjectCollection.cs b/src/Build/Definition/ProjectCollection.cs index 55b1966b5a1..71fd0ce1a77 100644 --- a/src/Build/Definition/ProjectCollection.cs +++ b/src/Build/Definition/ProjectCollection.cs @@ -384,7 +384,7 @@ private ProjectCollection(IDictionary globalProperties, IEnumera if (!Traits.Instance.EscapeHatches.DisableParseConfig) { - ProjectRootElementCache.SetUnknownElementsConfiguration(UnknownElementsConfiguration.LoadGlobalConfig()); + ProjectRootElementCache.SetParserIgnoreConfiguration(ParserIgnoreConfiguration.LoadGlobalConfig()); } if (reuseProjectRootElementCache) @@ -573,16 +573,16 @@ public static string DisplayVersion /// Gets or sets the configuration for allowed unknown attributes/elements during parsing. /// When set, this configuration will be used by builds started from this collection. /// - internal UnknownElementsConfiguration UnknownElementsConfiguration + internal ParserIgnoreConfiguration ParserIgnoreConfiguration { - get => ProjectRootElementCache.UnknownElementsConfiguration; - set => ProjectRootElementCache.SetUnknownElementsConfiguration(value); + get => ProjectRootElementCache.ParserIgnoreConfiguration; + set => ProjectRootElementCache.SetParserIgnoreConfiguration(value); } /// /// The config state before LoadParseConfigForStartup was called, used to restore on unload. /// - private UnknownElementsConfiguration _preStartupUnknownElementsConfiguration; + private ParserIgnoreConfiguration _preStartupParserIgnoreConfiguration; /// /// Loads a Directory.Parse.config by walking up from the specified directory @@ -593,7 +593,7 @@ internal UnknownElementsConfiguration UnknownElementsConfiguration /// Thrown if startup config is already loaded. public void LoadParseConfigForStartup(string startingDirectory) { - if (_preStartupUnknownElementsConfiguration is not null) + if (_preStartupParserIgnoreConfiguration is not null) { throw new InvalidOperationException("LoadParseConfigForStartup called while startup config is already loaded. Call UnloadParseConfigForStartup first."); } @@ -603,17 +603,17 @@ public void LoadParseConfigForStartup(string startingDirectory) return; } - var config = ProjectRootElementCache.UnknownElementsConfiguration; + var config = ProjectRootElementCache.ParserIgnoreConfiguration; if (config is null) { return; } - string configPath = FileUtilities.GetPathOfFileAbove(UnknownElementsConfiguration.ConfigFileName, startingDirectory); + string configPath = FileUtilities.GetPathOfFileAbove(ParserIgnoreConfiguration.ConfigFileName, startingDirectory); if (!string.IsNullOrEmpty(configPath) && !config.ContainsLoadedFile(configPath)) { - _preStartupUnknownElementsConfiguration = config; - ProjectRootElementCache.SetUnknownElementsConfiguration(UnknownElementsConfiguration.Merge(config, UnknownElementsConfiguration.LoadFromFile(configPath))); + _preStartupParserIgnoreConfiguration = config; + ProjectRootElementCache.SetParserIgnoreConfiguration(ParserIgnoreConfiguration.Merge(config, ParserIgnoreConfiguration.LoadFromFile(configPath))); } } @@ -622,10 +622,10 @@ public void LoadParseConfigForStartup(string startingDirectory) /// public void UnloadParseConfigForStartup() { - if (_preStartupUnknownElementsConfiguration is not null) + if (_preStartupParserIgnoreConfiguration is not null) { - ProjectRootElementCache.SetUnknownElementsConfiguration(_preStartupUnknownElementsConfiguration); - _preStartupUnknownElementsConfiguration = null; + ProjectRootElementCache.SetParserIgnoreConfiguration(_preStartupParserIgnoreConfiguration); + _preStartupParserIgnoreConfiguration = null; } } diff --git a/src/Build/Evaluation/Evaluator.cs b/src/Build/Evaluation/Evaluator.cs index 5efc97948f4..53fc17a2ec6 100644 --- a/src/Build/Evaluation/Evaluator.cs +++ b/src/Build/Evaluation/Evaluator.cs @@ -192,7 +192,7 @@ internal class Evaluator /// private readonly ProjectRootElementCacheBase _projectRootElementCache; - private UnknownElementsConfiguration _unknownElementsConfiguration; + private ParserIgnoreConfiguration _ParserIgnoreConfiguration; /// /// The logging context to be used and piped down throughout evaluation. @@ -309,35 +309,35 @@ private Evaluator( _streamImports.Add(string.Empty); } - private void InitializeUnknownElementsConfiguration() + private void InitializeParserIgnoreConfiguration() { - _unknownElementsConfiguration = _projectRootElementCache.UnknownElementsConfiguration; + _ParserIgnoreConfiguration = _projectRootElementCache.ParserIgnoreConfiguration; if (Traits.Instance.EscapeHatches.DisableParseConfig || string.IsNullOrEmpty(_projectRootElement.FullPath)) { return; } - string projectConfigPath = FileUtilities.GetPathOfFileAbove(UnknownElementsConfiguration.ConfigFileName, _projectRootElement.DirectoryPath); + string projectConfigPath = FileUtilities.GetPathOfFileAbove(ParserIgnoreConfiguration.ConfigFileName, _projectRootElement.DirectoryPath); if (string.IsNullOrEmpty(projectConfigPath)) { return; } - if (_unknownElementsConfiguration is null) + if (_ParserIgnoreConfiguration is null) { - _unknownElementsConfiguration = UnknownElementsConfiguration.LoadFromFile(projectConfigPath); + _ParserIgnoreConfiguration = ParserIgnoreConfiguration.LoadFromFile(projectConfigPath); } - else if (!_unknownElementsConfiguration.ContainsLoadedFile(projectConfigPath)) + else if (!_ParserIgnoreConfiguration.ContainsLoadedFile(projectConfigPath)) { - _unknownElementsConfiguration = UnknownElementsConfiguration.Merge(_unknownElementsConfiguration, UnknownElementsConfiguration.LoadFromFile(projectConfigPath)); + _ParserIgnoreConfiguration = ParserIgnoreConfiguration.Merge(_ParserIgnoreConfiguration, ParserIgnoreConfiguration.LoadFromFile(projectConfigPath)); } else { return; } - _projectRootElementCache.SetUnknownElementsConfiguration(_unknownElementsConfiguration); + _projectRootElementCache.SetParserIgnoreConfiguration(_ParserIgnoreConfiguration); } /// @@ -425,7 +425,7 @@ internal static void Evaluate( items = evaluator._data.Items; } - string skippedMessage = evaluator._unknownElementsConfiguration?.GetSkippedSummaryMessage(); + string skippedMessage = evaluator._ParserIgnoreConfiguration?.GetSkippedSummaryMessage(); if (skippedMessage is not null) { evaluator._evaluationLoggingContext.LogCommentFromText(MessageImportance.Low, skippedMessage); @@ -701,9 +701,9 @@ private void Evaluate() _data.EvaluationId = _evaluationLoggingContext.BuildEventContext.EvaluationId; _evaluationLoggingContext.LogProjectEvaluationStarted(); - InitializeUnknownElementsConfiguration(); + InitializeParserIgnoreConfiguration(); - string configMessage = _unknownElementsConfiguration?.GetLoadedConfigsMessage(); + string configMessage = _ParserIgnoreConfiguration?.GetLoadedConfigsMessage(); if (configMessage is not null) { _evaluationLoggingContext.LogCommentFromText(MessageImportance.Low, configMessage); diff --git a/src/Build/Evaluation/UnknownElementsConfiguration.cs b/src/Build/Evaluation/ParserIgnoreConfiguration.cs similarity index 92% rename from src/Build/Evaluation/UnknownElementsConfiguration.cs rename to src/Build/Evaluation/ParserIgnoreConfiguration.cs index df72aa142a2..c75a650c374 100644 --- a/src/Build/Evaluation/UnknownElementsConfiguration.cs +++ b/src/Build/Evaluation/ParserIgnoreConfiguration.cs @@ -21,7 +21,7 @@ namespace Microsoft.Build.Evaluation /// 2. User profile (~/.msbuild/) /// 3. MSBUILD_PARSE_CONFIG environment variable paths /// - internal sealed class UnknownElementsConfiguration : ITranslatable + internal sealed class ParserIgnoreConfiguration : ITranslatable { internal const string ConfigFileName = "Directory.Parse.config"; internal const string EnvironmentVariableName = "MSBUILD_PARSE_CONFIG"; @@ -46,14 +46,14 @@ internal static void ClearBinlogEmbedPaths() private HashSet _loadedConfigFiles; private readonly ConcurrentDictionary _skippedItems = new(StringComparer.OrdinalIgnoreCase); - private UnknownElementsConfiguration() + private ParserIgnoreConfiguration() { _allowedAttributes = new Dictionary>(StringComparer.OrdinalIgnoreCase); _allowedChildren = new Dictionary>(StringComparer.OrdinalIgnoreCase); _loadedConfigFiles = new HashSet(StringComparer.OrdinalIgnoreCase); } - private UnknownElementsConfiguration(ITranslator translator) + private ParserIgnoreConfiguration(ITranslator translator) : this() { ((ITranslatable)this).Translate(translator); @@ -61,9 +61,9 @@ private UnknownElementsConfiguration(ITranslator translator) internal IReadOnlyCollection LoadedConfigFiles => _loadedConfigFiles; - internal static UnknownElementsConfiguration Empty { get; } = new UnknownElementsConfiguration(); + internal static ParserIgnoreConfiguration Empty { get; } = new ParserIgnoreConfiguration(); - public static bool Equals(UnknownElementsConfiguration? left, UnknownElementsConfiguration? right) + public static bool Equals(ParserIgnoreConfiguration? left, ParserIgnoreConfiguration? right) { if (ReferenceEquals(left, right)) { @@ -159,12 +159,12 @@ internal bool CheckSkipElement(string parentElementName, string childElementName return $"Loaded Directory.Parse.config from: {string.Join(", ", _loadedConfigFiles)}"; } - internal static UnknownElementsConfiguration Merge(UnknownElementsConfiguration left, UnknownElementsConfiguration right) + internal static ParserIgnoreConfiguration Merge(ParserIgnoreConfiguration left, ParserIgnoreConfiguration right) { ArgumentNullException.ThrowIfNull(left); ArgumentNullException.ThrowIfNull(right); - var merged = new UnknownElementsConfiguration(); + var merged = new ParserIgnoreConfiguration(); UnionEntries(merged._allowedAttributes, left._allowedAttributes); UnionEntries(merged._allowedAttributes, right._allowedAttributes); @@ -178,16 +178,16 @@ internal static UnknownElementsConfiguration Merge(UnknownElementsConfiguration return merged; } - internal static UnknownElementsConfiguration LoadFromFile(string filePath) + internal static ParserIgnoreConfiguration LoadFromFile(string filePath) { - var config = new UnknownElementsConfiguration(); + var config = new ParserIgnoreConfiguration(); config.LoadFile(filePath); return config; } - internal static UnknownElementsConfiguration LoadGlobalConfig() + internal static ParserIgnoreConfiguration LoadGlobalConfig() { - var config = new UnknownElementsConfiguration(); + var config = new ParserIgnoreConfiguration(); string? envValue = Environment.GetEnvironmentVariable(EnvironmentVariableName); if (!string.IsNullOrEmpty(envValue)) @@ -225,9 +225,9 @@ private static HashSet HashSetValueFactory(ITranslator translator) return set ?? new HashSet(StringComparer.OrdinalIgnoreCase); } - internal static UnknownElementsConfiguration FactoryForDeserialization(ITranslator translator) + internal static ParserIgnoreConfiguration FactoryForDeserialization(ITranslator translator) { - return new UnknownElementsConfiguration(translator); + return new ParserIgnoreConfiguration(translator); } private static void UnionEntries(Dictionary> destination, Dictionary> source) diff --git a/src/Build/Evaluation/ProjectParser.cs b/src/Build/Evaluation/ProjectParser.cs index f6dd2fbbd96..469da4afbe0 100644 --- a/src/Build/Evaluation/ProjectParser.cs +++ b/src/Build/Evaluation/ProjectParser.cs @@ -86,7 +86,7 @@ internal class ProjectParser /// private readonly XmlDocumentWithLocation _document; - private readonly UnknownElementsConfiguration _unknownElementsConfiguration; + private readonly ParserIgnoreConfiguration _ParserIgnoreConfiguration; /// /// Whether a ProjectExtensions node has been encountered already. @@ -97,14 +97,14 @@ internal class ProjectParser /// /// Private constructor to give static semantics /// - private ProjectParser(XmlDocumentWithLocation document, ProjectRootElement project, UnknownElementsConfiguration unknownElementsConfiguration) + private ProjectParser(XmlDocumentWithLocation document, ProjectRootElement project, ParserIgnoreConfiguration ParserIgnoreConfiguration) { Assumed.NotNull(project); Assumed.NotNull(document); _document = document; _project = project; - _unknownElementsConfiguration = unknownElementsConfiguration; + _ParserIgnoreConfiguration = ParserIgnoreConfiguration; } /// @@ -115,11 +115,11 @@ private ProjectParser(XmlDocumentWithLocation document, ProjectRootElement proje /// The code markers here used to be around the Project class constructor in the old code. /// In the new code, that's not very interesting; we are repurposing to wrap parsing the XML. /// - internal static void Parse(XmlDocumentWithLocation document, ProjectRootElement projectRootElement, UnknownElementsConfiguration unknownElementsConfiguration) + internal static void Parse(XmlDocumentWithLocation document, ProjectRootElement projectRootElement, ParserIgnoreConfiguration ParserIgnoreConfiguration) { MSBuildEventSource.Log.ParseStart(projectRootElement.ProjectFileLocation.File); { - ProjectParser parser = new ProjectParser(document, projectRootElement, unknownElementsConfiguration); + ProjectParser parser = new ProjectParser(document, projectRootElement, ParserIgnoreConfiguration); parser.Parse(); } MSBuildEventSource.Log.ParseStop(projectRootElement.ProjectFileLocation.File); @@ -208,7 +208,7 @@ private void Parse() break; default: - if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, childElement.ParentNode.Name, childElement.Location, _unknownElementsConfiguration)) + if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, childElement.ParentNode.Name, childElement.Location, _ParserIgnoreConfiguration)) { continue; } @@ -223,13 +223,13 @@ private void Parse() /// private ProjectPropertyGroupElement ParseProjectPropertyGroupElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration); ProjectPropertyGroupElement propertyGroup = new ProjectPropertyGroupElement(element, parent, _project); foreach (XmlElementWithLocation childElement in ProjectXmlUtilities.GetVerifyThrowProjectChildElements(element)) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration, "Property"); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration, "Property"); XmlUtilities.VerifyThrowProjectValidElementName(childElement); ProjectErrorUtilities.VerifyThrowInvalidProject(!XMakeElements.ReservedItemNames.Contains(childElement.Name) && !ReservedPropertyNames.IsReservedProperty(childElement.Name), childElement.Location, "CannotModifyReservedProperty", childElement.Name); @@ -247,7 +247,7 @@ private ProjectPropertyGroupElement ParseProjectPropertyGroupElement(XmlElementW /// private ProjectItemGroupElement ParseProjectItemGroupElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration); ProjectItemGroupElement itemGroup = new ProjectItemGroupElement(element, parent, _project); @@ -328,7 +328,7 @@ private ProjectItemElement ParseProjectItemElement(XmlElementWithLocation elemen if (!isKnownAttribute && !isValidMetadataNameInAttribute) { - if (_unknownElementsConfiguration?.CheckSkipAttribute("Item", attribute.Name) != true) + if (_ParserIgnoreConfiguration?.CheckSkipAttribute("Item", attribute.Name) != true) { ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); } @@ -403,7 +403,7 @@ internal static void CheckMetadataAsAttributeName(string name, out bool isReserv /// private ProjectMetadataElement ParseProjectMetadataElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration, "Metadata"); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration, "Metadata"); XmlUtilities.VerifyThrowProjectValidElementName(element); @@ -431,7 +431,7 @@ private ProjectMetadataElement ParseProjectMetadataElement(XmlElementWithLocatio /// A ProjectImportGroupElement derived from the XML element passed in private ProjectImportGroupElement ParseProjectImportGroupElement(XmlElementWithLocation element, ProjectRootElement parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration); ProjectImportGroupElement importGroup = new ProjectImportGroupElement(element, parent, _project); @@ -439,7 +439,7 @@ private ProjectImportGroupElement ParseProjectImportGroupElement(XmlElementWithL { if (childElement.Name != XMakeElements.import) { - if (_unknownElementsConfiguration?.CheckSkipElement(element.Name, childElement.Name) == true) + if (_ParserIgnoreConfiguration?.CheckSkipElement(element.Name, childElement.Name) == true) { continue; } @@ -471,9 +471,9 @@ private ProjectImportElement ParseProjectImportElement(XmlElementWithLocation el parent, element); - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnImport, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnImport, _ParserIgnoreConfiguration); ProjectXmlUtilities.VerifyThrowProjectRequiredAttribute(element, XMakeAttributes.project); - ProjectXmlUtilities.VerifyThrowProjectNoChildElements(element, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectNoChildElements(element, _ParserIgnoreConfiguration); SdkReference sdk = null; if (element.HasAttribute(XMakeAttributes.sdk)) @@ -493,7 +493,7 @@ private ProjectImportElement ParseProjectImportElement(XmlElementWithLocation el private UsingTaskParameterGroupElement ParseUsingTaskParameterGroupElement(XmlElementWithLocation element, ProjectElementContainer parent) { // There should be no attributes - ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _ParserIgnoreConfiguration); UsingTaskParameterGroupElement parameterGroup = new UsingTaskParameterGroupElement(element, parent, _project); @@ -507,7 +507,7 @@ private UsingTaskParameterGroupElement ParseUsingTaskParameterGroupElement(XmlEl } else { - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskParameter, _unknownElementsConfiguration, "Parameter"); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskParameter, _ParserIgnoreConfiguration, "Parameter"); XmlUtilities.VerifyThrowProjectValidElementName(childElement); ProjectUsingTaskParameterElement parameter = new ProjectUsingTaskParameterElement(childElement, parameterGroup, _project); parameterGroup.AppendParentedChildNoChecks(parameter); @@ -525,7 +525,7 @@ private UsingTaskParameterGroupElement ParseUsingTaskParameterGroupElement(XmlEl /// private ProjectUsingTaskElement ParseProjectUsingTaskElement(XmlElementWithLocation element) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnUsingTask, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnUsingTask, _ParserIgnoreConfiguration); ProjectErrorUtilities.VerifyThrowInvalidProject(element.GetAttribute(XMakeAttributes.taskName).Length > 0, element.Location, "ProjectTaskNameEmpty"); string assemblyName = element.GetAttribute(XMakeAttributes.assemblyName); @@ -568,13 +568,13 @@ private ProjectUsingTaskElement ParseProjectUsingTaskElement(XmlElementWithLocat ProjectXmlUtilities.ThrowProjectInvalidChildElementDueToDuplicate(childElement); } - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskBody, _unknownElementsConfiguration, "UsingTaskBody"); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskBody, _ParserIgnoreConfiguration, "UsingTaskBody"); child = new ProjectUsingTaskBodyElement(childElement, usingTask, _project); foundTaskElement = true; break; default: - if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, element.Name, element.Location, _unknownElementsConfiguration)) + if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, element.Name, element.Location, _ParserIgnoreConfiguration)) { continue; } @@ -593,7 +593,7 @@ private ProjectUsingTaskElement ParseProjectUsingTaskElement(XmlElementWithLocat /// private ProjectTargetElement ParseProjectTargetElement(XmlElementWithLocation element) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnTarget, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnTarget, _ParserIgnoreConfiguration); ProjectXmlUtilities.VerifyThrowProjectRequiredAttribute(element, XMakeAttributes.name); // Orcas compat: all target names are automatically unescaped @@ -635,9 +635,9 @@ private ProjectTargetElement ParseProjectTargetElement(XmlElementWithLocation el case XMakeElements.onError: // Previous OM accidentally didn't verify ExecuteTargets on parse, // but we do, as it makes no sense - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnOnError, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnOnError, _ParserIgnoreConfiguration); ProjectXmlUtilities.VerifyThrowProjectRequiredAttribute(childElement, XMakeAttributes.executeTargets); - ProjectXmlUtilities.VerifyThrowProjectNoChildElements(childElement, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectNoChildElements(childElement, _ParserIgnoreConfiguration); child = onError = new ProjectOnErrorElement(childElement, target, _project); break; @@ -689,7 +689,7 @@ private ProjectTaskElement ParseProjectTaskElement(XmlElementWithLocation elemen { if (childElement.Name != XMakeElements.output) { - if (_unknownElementsConfiguration?.CheckSkipElement("Task", childElement.Name) == true) + if (_ParserIgnoreConfiguration?.CheckSkipElement("Task", childElement.Name) == true) { continue; } @@ -710,9 +710,9 @@ private ProjectTaskElement ParseProjectTaskElement(XmlElementWithLocation elemen /// private ProjectOutputElement ParseProjectOutputElement(XmlElementWithLocation element, ProjectTaskElement parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnOutput, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnOutput, _ParserIgnoreConfiguration); ProjectXmlUtilities.VerifyThrowProjectRequiredAttribute(element, XMakeAttributes.taskParameter); - ProjectXmlUtilities.VerifyThrowProjectNoChildElements(element, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectNoChildElements(element, _ParserIgnoreConfiguration); XmlAttributeWithLocation itemNameAttribute = element.GetAttributeWithLocation(XMakeAttributes.itemName); XmlAttributeWithLocation propertyNameAttribute = element.GetAttributeWithLocation(XMakeAttributes.propertyName); @@ -736,7 +736,7 @@ private ProjectOutputElement ParseProjectOutputElement(XmlElementWithLocation el /// private ProjectItemDefinitionGroupElement ParseProjectItemDefinitionGroupElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration); ProjectItemDefinitionGroupElement itemDefinitionGroup = new ProjectItemDefinitionGroupElement(element, parent, _project); @@ -767,7 +767,7 @@ private ProjectItemDefinitionElement ParseProjectItemDefinitionXml(XmlElementWit if (!isKnownAttribute && !isValidMetadataNameInAttribute) { - if (_unknownElementsConfiguration?.CheckSkipAttribute("ItemDefinition", attribute.Name) != true) + if (_ParserIgnoreConfiguration?.CheckSkipAttribute("ItemDefinition", attribute.Name) != true) { ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); } @@ -782,7 +782,7 @@ private ProjectItemDefinitionElement ParseProjectItemDefinitionXml(XmlElementWit } else if (!ValidAttributesOnlyConditionAndLabel.Contains(attribute.Name)) { - if (_unknownElementsConfiguration?.CheckSkipAttribute("ItemDefinition", attribute.Name) != true) + if (_ParserIgnoreConfiguration?.CheckSkipAttribute("ItemDefinition", attribute.Name) != true) { ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); } @@ -804,7 +804,7 @@ private ProjectItemDefinitionElement ParseProjectItemDefinitionXml(XmlElementWit /// private ProjectChooseElement ParseProjectChooseElement(XmlElementWithLocation element, ProjectElementContainer parent, int nestingDepth) { - ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _ParserIgnoreConfiguration); ProjectChooseElement choose = new ProjectChooseElement(element, parent, _project); @@ -833,7 +833,7 @@ private ProjectChooseElement ParseProjectChooseElement(XmlElementWithLocation el break; default: - if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, element.Name, element.Location, _unknownElementsConfiguration)) + if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, element.Name, element.Location, _ParserIgnoreConfiguration)) { continue; } @@ -868,7 +868,7 @@ private ProjectWhenElement ParseProjectWhenElement(XmlElementWithLocation elemen /// private ProjectOtherwiseElement ParseProjectOtherwiseElement(XmlElementWithLocation element, ProjectChooseElement parent, int nestingDepth) { - ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _ParserIgnoreConfiguration); ProjectOtherwiseElement otherwise = new ProjectOtherwiseElement(element, parent, _project); @@ -905,7 +905,7 @@ private void ParseWhenOtherwiseChildren(XmlElementWithLocation element, ProjectE break; default: - if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, element.Name, element.Location, _unknownElementsConfiguration)) + if (ProjectXmlUtilities.ThrowIfProjectInvalidChildElement(childElement.Name, element.Name, element.Location, _ParserIgnoreConfiguration)) { continue; } @@ -924,7 +924,7 @@ private ProjectExtensionsElement ParseProjectExtensionsElement(XmlElementWithLoc { // ProjectExtensions are only found in the main project file - in fact, the code used to ignore them in imported // files. We don't. - ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _unknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectNoAttributes(element, _ParserIgnoreConfiguration); ProjectErrorUtilities.VerifyThrowInvalidProject(!_seenProjectExtensions, element.Location, "DuplicateProjectExtensions"); _seenProjectExtensions = true; diff --git a/src/Build/Evaluation/ProjectRootElementCacheBase.cs b/src/Build/Evaluation/ProjectRootElementCacheBase.cs index 198c958ee28..9fe3cd83649 100644 --- a/src/Build/Evaluation/ProjectRootElementCacheBase.cs +++ b/src/Build/Evaluation/ProjectRootElementCacheBase.cs @@ -12,7 +12,7 @@ internal abstract class ProjectRootElementCacheBase { public bool LoadProjectsReadOnly { get; protected set; } - public UnknownElementsConfiguration UnknownElementsConfiguration { get; protected set; } + public ParserIgnoreConfiguration ParserIgnoreConfiguration { get; protected set; } /// /// Handler for which project root element just got added to the cache @@ -72,15 +72,15 @@ internal abstract ProjectRootElement Get(string projectFile, OpenProjectRootElem internal abstract void DiscardAnyWeakReference(ProjectRootElement projectRootElement); - internal void SetUnknownElementsConfiguration(UnknownElementsConfiguration configuration) + internal void SetParserIgnoreConfiguration(ParserIgnoreConfiguration configuration) { - if (UnknownElementsConfiguration.Equals(UnknownElementsConfiguration, configuration)) + if (ParserIgnoreConfiguration.Equals(ParserIgnoreConfiguration, configuration)) { return; } DiscardImplicitReferences(); - UnknownElementsConfiguration = configuration; + ParserIgnoreConfiguration = configuration; } /// diff --git a/src/Build/Instance/TaskRegistry.cs b/src/Build/Instance/TaskRegistry.cs index dc506f45b7a..32e35cebca5 100644 --- a/src/Build/Instance/TaskRegistry.cs +++ b/src/Build/Instance/TaskRegistry.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -320,7 +320,7 @@ private static void RegisterTasksFromUsingTaskElement if (String.IsNullOrEmpty(taskFactory) || taskFactory.Equals(RegisteredTaskRecord.AssemblyTaskFactory, StringComparison.OrdinalIgnoreCase) || taskFactory.Equals(RegisteredTaskRecord.TaskHostFactory, StringComparison.OrdinalIgnoreCase)) { - ProjectXmlUtilities.VerifyThrowProjectNoChildElements(projectUsingTaskXml.XmlElement, projectUsingTaskXml.ContainingProject.ProjectRootElementCache.UnknownElementsConfiguration); + ProjectXmlUtilities.VerifyThrowProjectNoChildElements(projectUsingTaskXml.XmlElement, projectUsingTaskXml.ContainingProject.ProjectRootElementCache.ParserIgnoreConfiguration); } if (projectUsingTaskXml.AssemblyFile.Length > 0) diff --git a/src/Build/Logging/BinaryLogger/BinaryLogger.cs b/src/Build/Logging/BinaryLogger/BinaryLogger.cs index 59e4b96a463..3dd6cc52663 100644 --- a/src/Build/Logging/BinaryLogger/BinaryLogger.cs +++ b/src/Build/Logging/BinaryLogger/BinaryLogger.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -513,11 +513,11 @@ public void Shutdown() EditorConfigParser.ClearEditorConfigFilePaths(); // Write the Directory.Parse.config file paths to the log - foreach (var filePath in Evaluation.UnknownElementsConfiguration.BinlogEmbedPaths) + foreach (var filePath in Evaluation.ParserIgnoreConfiguration.BinlogEmbedPaths) { projectImportsCollector.AddFile(filePath); } - Evaluation.UnknownElementsConfiguration.ClearBinlogEmbedPaths(); + Evaluation.ParserIgnoreConfiguration.ClearBinlogEmbedPaths(); projectImportsCollector.Close(); diff --git a/src/Build/Microsoft.Build.csproj b/src/Build/Microsoft.Build.csproj index e1b55579326..1aa8eef4824 100644 --- a/src/Build/Microsoft.Build.csproj +++ b/src/Build/Microsoft.Build.csproj @@ -544,7 +544,7 @@ - + diff --git a/src/Build/Xml/ProjectXmlUtilities.cs b/src/Build/Xml/ProjectXmlUtilities.cs index 467aa185ce0..c397b26f0f1 100644 --- a/src/Build/Xml/ProjectXmlUtilities.cs +++ b/src/Build/Xml/ProjectXmlUtilities.cs @@ -56,7 +56,7 @@ private static XmlElementChildIterator GetChildElements(XmlElementWithLocation e /// /// Throw an invalid project exception if there are any child elements at all /// - internal static void VerifyThrowProjectNoChildElements(XmlElementWithLocation element, UnknownElementsConfiguration config) + internal static void VerifyThrowProjectNoChildElements(XmlElementWithLocation element, ParserIgnoreConfiguration config) { foreach (var child in GetVerifyThrowProjectChildElements(element)) { @@ -138,7 +138,7 @@ internal static void VerifyThrowProjectAttributeEitherMissingOrNotEmpty(XmlEleme /// /// If there are any attributes on the element, throws an InvalidProjectFileException complaining that the attribute is not valid on this element. /// - internal static void VerifyThrowProjectNoAttributes(XmlElementWithLocation element, UnknownElementsConfiguration config) + internal static void VerifyThrowProjectNoAttributes(XmlElementWithLocation element, ParserIgnoreConfiguration config) { if (element.HasAttributes) { @@ -178,7 +178,7 @@ internal static void VerifyThrowProjectRequiredAttribute(XmlElementWithLocation /// Verify that all attributes on the element are on the list of legal attributes. /// When genericElementName is provided, only that name is checked in the config (not the actual element name). /// - internal static void VerifyThrowProjectAttributes(XmlElementWithLocation element, HashSet validAttributes, UnknownElementsConfiguration config, string genericElementName = null) + internal static void VerifyThrowProjectAttributes(XmlElementWithLocation element, HashSet validAttributes, ParserIgnoreConfiguration config, string genericElementName = null) { foreach (XmlAttributeWithLocation attribute in element.Attributes) { @@ -200,7 +200,7 @@ internal static void VerifyThrowProjectAttributes(XmlElementWithLocation element /// If the element is allowed, it is silently skipped. /// /// True if the element was skipped (caller should continue), false if the element was not in config and an exception was thrown. - internal static bool ThrowIfProjectInvalidChildElement(string name, string parentName, ElementLocation location, UnknownElementsConfiguration config) + internal static bool ThrowIfProjectInvalidChildElement(string name, string parentName, ElementLocation location, ParserIgnoreConfiguration config) { if (config?.CheckSkipElement(parentName, name) == true) { From 530f53600a01d0c015cb84b5651fc06649049462 Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Mon, 10 Aug 2026 20:41:14 -0400 Subject: [PATCH 14/20] Replace hardcoded generic element name strings with constants Add GenericPropertyElement, GenericItemElement, GenericItemDefinitionElement, GenericMetadataElement, and GenericUsingTaskBodyElement constants to ParserIgnoreConfiguration. Use XMakeElements.usingTaskParameter and XMakeElements.usingTaskBody for Parameter and Task since those reference real XML elements. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- .../Evaluation/ParserIgnoreConfiguration.cs | 8 ++++++++ src/Build/Evaluation/ProjectParser.cs | 16 ++++++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/Build/Evaluation/ParserIgnoreConfiguration.cs b/src/Build/Evaluation/ParserIgnoreConfiguration.cs index c75a650c374..69d5aeb88b7 100644 --- a/src/Build/Evaluation/ParserIgnoreConfiguration.cs +++ b/src/Build/Evaluation/ParserIgnoreConfiguration.cs @@ -26,6 +26,14 @@ internal sealed class ParserIgnoreConfiguration : ITranslatable internal const string ConfigFileName = "Directory.Parse.config"; internal const string EnvironmentVariableName = "MSBUILD_PARSE_CONFIG"; + // Generic element names for dynamically-named elements in the config. + // These allow rules like Attribute:Property:X to apply to all property elements. + internal const string GenericPropertyElement = "Property"; + internal const string GenericItemElement = "Item"; + internal const string GenericItemDefinitionElement = "ItemDefinition"; + internal const string GenericMetadataElement = "Metadata"; + internal const string GenericUsingTaskBodyElement = "UsingTaskBody"; + /// /// Static collection of config file paths to embed in the binlog. /// Populated during config loading, consumed by BinaryLogger.Shutdown. diff --git a/src/Build/Evaluation/ProjectParser.cs b/src/Build/Evaluation/ProjectParser.cs index 469da4afbe0..e70f0889606 100644 --- a/src/Build/Evaluation/ProjectParser.cs +++ b/src/Build/Evaluation/ProjectParser.cs @@ -229,7 +229,7 @@ private ProjectPropertyGroupElement ParseProjectPropertyGroupElement(XmlElementW foreach (XmlElementWithLocation childElement in ProjectXmlUtilities.GetVerifyThrowProjectChildElements(element)) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration, "Property"); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration, ParserIgnoreConfiguration.GenericPropertyElement); XmlUtilities.VerifyThrowProjectValidElementName(childElement); ProjectErrorUtilities.VerifyThrowInvalidProject(!XMakeElements.ReservedItemNames.Contains(childElement.Name) && !ReservedPropertyNames.IsReservedProperty(childElement.Name), childElement.Location, "CannotModifyReservedProperty", childElement.Name); @@ -328,7 +328,7 @@ private ProjectItemElement ParseProjectItemElement(XmlElementWithLocation elemen if (!isKnownAttribute && !isValidMetadataNameInAttribute) { - if (_ParserIgnoreConfiguration?.CheckSkipAttribute("Item", attribute.Name) != true) + if (_ParserIgnoreConfiguration?.CheckSkipAttribute(ParserIgnoreConfiguration.GenericItemElement, attribute.Name) != true) { ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); } @@ -403,7 +403,7 @@ internal static void CheckMetadataAsAttributeName(string name, out bool isReserv /// private ProjectMetadataElement ParseProjectMetadataElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration, "Metadata"); + ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnlyConditionAndLabel, _ParserIgnoreConfiguration, ParserIgnoreConfiguration.GenericMetadataElement); XmlUtilities.VerifyThrowProjectValidElementName(element); @@ -507,7 +507,7 @@ private UsingTaskParameterGroupElement ParseUsingTaskParameterGroupElement(XmlEl } else { - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskParameter, _ParserIgnoreConfiguration, "Parameter"); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskParameter, _ParserIgnoreConfiguration, XMakeElements.usingTaskParameter); XmlUtilities.VerifyThrowProjectValidElementName(childElement); ProjectUsingTaskParameterElement parameter = new ProjectUsingTaskParameterElement(childElement, parameterGroup, _project); parameterGroup.AppendParentedChildNoChecks(parameter); @@ -568,7 +568,7 @@ private ProjectUsingTaskElement ParseProjectUsingTaskElement(XmlElementWithLocat ProjectXmlUtilities.ThrowProjectInvalidChildElementDueToDuplicate(childElement); } - ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskBody, _ParserIgnoreConfiguration, "UsingTaskBody"); + ProjectXmlUtilities.VerifyThrowProjectAttributes(childElement, ValidAttributesOnUsingTaskBody, _ParserIgnoreConfiguration, ParserIgnoreConfiguration.GenericUsingTaskBodyElement); child = new ProjectUsingTaskBodyElement(childElement, usingTask, _project); foundTaskElement = true; @@ -689,7 +689,7 @@ private ProjectTaskElement ParseProjectTaskElement(XmlElementWithLocation elemen { if (childElement.Name != XMakeElements.output) { - if (_ParserIgnoreConfiguration?.CheckSkipElement("Task", childElement.Name) == true) + if (_ParserIgnoreConfiguration?.CheckSkipElement(XMakeElements.usingTaskBody, childElement.Name) == true) { continue; } @@ -767,7 +767,7 @@ private ProjectItemDefinitionElement ParseProjectItemDefinitionXml(XmlElementWit if (!isKnownAttribute && !isValidMetadataNameInAttribute) { - if (_ParserIgnoreConfiguration?.CheckSkipAttribute("ItemDefinition", attribute.Name) != true) + if (_ParserIgnoreConfiguration?.CheckSkipAttribute(ParserIgnoreConfiguration.GenericItemDefinitionElement, attribute.Name) != true) { ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); } @@ -782,7 +782,7 @@ private ProjectItemDefinitionElement ParseProjectItemDefinitionXml(XmlElementWit } else if (!ValidAttributesOnlyConditionAndLabel.Contains(attribute.Name)) { - if (_ParserIgnoreConfiguration?.CheckSkipAttribute("ItemDefinition", attribute.Name) != true) + if (_ParserIgnoreConfiguration?.CheckSkipAttribute(ParserIgnoreConfiguration.GenericItemDefinitionElement, attribute.Name) != true) { ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); } From 2ace693bb43e62e7da45b0f5bf40216e9b98514f Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Mon, 10 Aug 2026 22:36:04 -0400 Subject: [PATCH 15/20] Replace Load/UnloadParseConfigForStartup with constructor parameter Add parseConfigDirectory parameter to ProjectCollection constructor. The directory walk is done during construction, merged with the global config from the environment variable. XMake passes the project file's directory. Remove LoadParseConfigForStartup/UnloadParseConfigForStartup methods and the _preStartupParserIgnoreConfiguration field. Remove the per-project walk from Evaluator (now just reads from cache). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- src/Build/Definition/ProjectCollection.cs | 102 +++++++++------------- src/Build/Evaluation/Evaluator.cs | 38 +------- src/MSBuild/XMake.cs | 7 +- 3 files changed, 43 insertions(+), 104 deletions(-) diff --git a/src/Build/Definition/ProjectCollection.cs b/src/Build/Definition/ProjectCollection.cs index 71fd0ce1a77..61c01467f0f 100644 --- a/src/Build/Definition/ProjectCollection.cs +++ b/src/Build/Definition/ProjectCollection.cs @@ -251,7 +251,7 @@ public ProjectCollection(IDictionary globalProperties) /// The loggers to register. May be null. /// The locations from which to load toolsets. public ProjectCollection(IDictionary globalProperties, IEnumerable loggers, ToolsetDefinitionLocations toolsetDefinitionLocations) - : this(globalProperties, loggers, toolsetDefinitionLocations, 1 /* node count */, false /* do not only log critical events */, loadProjectsReadOnly: false, useAsynchronousLogging: false, reuseProjectRootElementCache: false, enableTargetOutputLogging: false) + : this(globalProperties, loggers, toolsetDefinitionLocations, 1 /* node count */, false /* do not only log critical events */, loadProjectsReadOnly: false, useAsynchronousLogging: false, reuseProjectRootElementCache: false, enableTargetOutputLogging: false, parseConfigDirectory: null) { } @@ -338,12 +338,27 @@ public ProjectCollection(IDictionary globalProperties, IEnumerab /// If set to true, loggers will collect and send Target outputs when targets are finished executing. [RequiresUnreferencedCode("Registers loggers, which can load forwarding logger assemblies by reflection at runtime; incompatible with trimming.")] public ProjectCollection(IDictionary globalProperties, IEnumerable loggers, IEnumerable remoteLoggers, ToolsetDefinitionLocations toolsetDefinitionLocations, int maxNodeCount, bool onlyLogCriticalEvents, bool loadProjectsReadOnly, bool useAsynchronousLogging, bool reuseProjectRootElementCache, bool enableTargetOutputLogging) - : this(globalProperties, loggers, toolsetDefinitionLocations, maxNodeCount, onlyLogCriticalEvents, loadProjectsReadOnly, useAsynchronousLogging, reuseProjectRootElementCache, enableTargetOutputLogging) + : this(globalProperties, loggers, toolsetDefinitionLocations, maxNodeCount, onlyLogCriticalEvents, loadProjectsReadOnly, useAsynchronousLogging, reuseProjectRootElementCache, enableTargetOutputLogging, parseConfigDirectory: null) + { + try + { + RegisterForwardingLoggers(remoteLoggers); + } + catch (Exception) + { + ShutDownLoggingService(); + throw; + } + } + + /// + /// Instantiates a project collection with the specified parameters and a directory to search + /// for a Directory.Parse.config file (walked upward from the given directory). + /// + [RequiresUnreferencedCode("Registers loggers, which can load forwarding logger assemblies by reflection at runtime; incompatible with trimming.")] + public ProjectCollection(IDictionary globalProperties, IEnumerable loggers, IEnumerable remoteLoggers, ToolsetDefinitionLocations toolsetDefinitionLocations, int maxNodeCount, bool onlyLogCriticalEvents, bool loadProjectsReadOnly, bool useAsynchronousLogging, bool reuseProjectRootElementCache, bool enableTargetOutputLogging, string parseConfigDirectory) + : this(globalProperties, loggers, toolsetDefinitionLocations, maxNodeCount, onlyLogCriticalEvents, loadProjectsReadOnly, useAsynchronousLogging, reuseProjectRootElementCache, enableTargetOutputLogging, parseConfigDirectory) { - // Forwarding loggers load logger assemblies by reflection, which is incompatible with - // trimming - that is why every overload taking forwarding loggers is RequiresUnreferencedCode - // while the overloads taking none are not. The trim-safe construction happens in the chained - // private constructor above; only this reflective registration is gated behind the attribute. try { RegisterForwardingLoggers(remoteLoggers); @@ -360,7 +375,7 @@ public ProjectCollection(IDictionary globalProperties, IEnumerab /// registers ordinary (non-forwarding) loggers, but does not load forwarding loggers by /// reflection, so the overloads that take none can be called without RequiresUnreferencedCode. /// - private ProjectCollection(IDictionary globalProperties, IEnumerable loggers, ToolsetDefinitionLocations toolsetDefinitionLocations, int maxNodeCount, bool onlyLogCriticalEvents, bool loadProjectsReadOnly, bool useAsynchronousLogging, bool reuseProjectRootElementCache, bool enableTargetOutputLogging) + private ProjectCollection(IDictionary globalProperties, IEnumerable loggers, ToolsetDefinitionLocations toolsetDefinitionLocations, int maxNodeCount, bool onlyLogCriticalEvents, bool loadProjectsReadOnly, bool useAsynchronousLogging, bool reuseProjectRootElementCache, bool enableTargetOutputLogging, string parseConfigDirectory) { _loadedProjects = new LoadedProjectCollection(); ToolsetLocations = toolsetDefinitionLocations; @@ -381,11 +396,6 @@ private ProjectCollection(IDictionary globalProperties, IEnumera // we do not need to auto reload. bool autoReloadFromDisk = reuseProjectRootElementCache; ProjectRootElementCache = new ProjectRootElementCache(autoReloadFromDisk, loadProjectsReadOnly); - - if (!Traits.Instance.EscapeHatches.DisableParseConfig) - { - ProjectRootElementCache.SetParserIgnoreConfiguration(ParserIgnoreConfiguration.LoadGlobalConfig()); - } if (reuseProjectRootElementCache) { @@ -393,6 +403,22 @@ private ProjectCollection(IDictionary globalProperties, IEnumera } } + if (!Traits.Instance.EscapeHatches.DisableParseConfig) + { + var config = ParserIgnoreConfiguration.LoadGlobalConfig(); + + if (!string.IsNullOrEmpty(parseConfigDirectory)) + { + string configPath = FileUtilities.GetPathOfFileAbove(ParserIgnoreConfiguration.ConfigFileName, parseConfigDirectory); + if (!string.IsNullOrEmpty(configPath) && !config.ContainsLoadedFile(configPath)) + { + config = ParserIgnoreConfiguration.Merge(config, ParserIgnoreConfiguration.LoadFromFile(configPath)); + } + } + + ProjectRootElementCache.SetParserIgnoreConfiguration(config); + } + OnlyLogCriticalEvents = onlyLogCriticalEvents; EnableTargetOutputLogging = enableTargetOutputLogging; @@ -498,7 +524,7 @@ public static ProjectCollection GlobalProjectCollection // Take care to ensure that there is never more than one value observed // from this property even in the case of race conditions while lazily initializing. var local = new ProjectCollection(null, null, ToolsetDefinitionLocations.Default, - maxNodeCount: 1, onlyLogCriticalEvents: false, loadProjectsReadOnly: false, useAsynchronousLogging: true, reuseProjectRootElementCache: false, enableTargetOutputLogging: false); + maxNodeCount: 1, onlyLogCriticalEvents: false, loadProjectsReadOnly: false, useAsynchronousLogging: true, reuseProjectRootElementCache: false, enableTargetOutputLogging: false, parseConfigDirectory: null); if (Interlocked.CompareExchange(ref s_globalProjectCollection, local, null) != null) { @@ -579,56 +605,6 @@ internal ParserIgnoreConfiguration ParserIgnoreConfiguration set => ProjectRootElementCache.SetParserIgnoreConfiguration(value); } - /// - /// The config state before LoadParseConfigForStartup was called, used to restore on unload. - /// - private ParserIgnoreConfiguration _preStartupParserIgnoreConfiguration; - - /// - /// Loads a Directory.Parse.config by walking up from the specified directory - /// and adds it to the current parse configuration. Call - /// to restore the previous state after the build completes. - /// - /// The directory to start searching from (typically the build's working directory). - /// Thrown if startup config is already loaded. - public void LoadParseConfigForStartup(string startingDirectory) - { - if (_preStartupParserIgnoreConfiguration is not null) - { - throw new InvalidOperationException("LoadParseConfigForStartup called while startup config is already loaded. Call UnloadParseConfigForStartup first."); - } - - if (Traits.Instance.EscapeHatches.DisableParseConfig || string.IsNullOrEmpty(startingDirectory)) - { - return; - } - - var config = ProjectRootElementCache.ParserIgnoreConfiguration; - if (config is null) - { - return; - } - - string configPath = FileUtilities.GetPathOfFileAbove(ParserIgnoreConfiguration.ConfigFileName, startingDirectory); - if (!string.IsNullOrEmpty(configPath) && !config.ContainsLoadedFile(configPath)) - { - _preStartupParserIgnoreConfiguration = config; - ProjectRootElementCache.SetParserIgnoreConfiguration(ParserIgnoreConfiguration.Merge(config, ParserIgnoreConfiguration.LoadFromFile(configPath))); - } - } - - /// - /// Restores the parse configuration to the state before was called. - /// - public void UnloadParseConfigForStartup() - { - if (_preStartupParserIgnoreConfiguration is not null) - { - ProjectRootElementCache.SetParserIgnoreConfiguration(_preStartupParserIgnoreConfiguration); - _preStartupParserIgnoreConfiguration = null; - } - } - /// /// The default tools version of this project collection. Projects use this tools version if they /// aren't otherwise told what tools version to use. diff --git a/src/Build/Evaluation/Evaluator.cs b/src/Build/Evaluation/Evaluator.cs index 53fc17a2ec6..49ad7302692 100644 --- a/src/Build/Evaluation/Evaluator.cs +++ b/src/Build/Evaluation/Evaluator.cs @@ -192,8 +192,6 @@ internal class Evaluator /// private readonly ProjectRootElementCacheBase _projectRootElementCache; - private ParserIgnoreConfiguration _ParserIgnoreConfiguration; - /// /// The logging context to be used and piped down throughout evaluation. /// @@ -309,36 +307,6 @@ private Evaluator( _streamImports.Add(string.Empty); } - private void InitializeParserIgnoreConfiguration() - { - _ParserIgnoreConfiguration = _projectRootElementCache.ParserIgnoreConfiguration; - - if (Traits.Instance.EscapeHatches.DisableParseConfig || string.IsNullOrEmpty(_projectRootElement.FullPath)) - { - return; - } - - string projectConfigPath = FileUtilities.GetPathOfFileAbove(ParserIgnoreConfiguration.ConfigFileName, _projectRootElement.DirectoryPath); - if (string.IsNullOrEmpty(projectConfigPath)) - { - return; - } - - if (_ParserIgnoreConfiguration is null) - { - _ParserIgnoreConfiguration = ParserIgnoreConfiguration.LoadFromFile(projectConfigPath); - } - else if (!_ParserIgnoreConfiguration.ContainsLoadedFile(projectConfigPath)) - { - _ParserIgnoreConfiguration = ParserIgnoreConfiguration.Merge(_ParserIgnoreConfiguration, ParserIgnoreConfiguration.LoadFromFile(projectConfigPath)); - } - else - { - return; - } - - _projectRootElementCache.SetParserIgnoreConfiguration(_ParserIgnoreConfiguration); - } /// /// Delegate passed to methods to provide basic expression evaluation @@ -425,7 +393,7 @@ internal static void Evaluate( items = evaluator._data.Items; } - string skippedMessage = evaluator._ParserIgnoreConfiguration?.GetSkippedSummaryMessage(); + string skippedMessage = evaluator._projectRootElementCache.ParserIgnoreConfiguration?.GetSkippedSummaryMessage(); if (skippedMessage is not null) { evaluator._evaluationLoggingContext.LogCommentFromText(MessageImportance.Low, skippedMessage); @@ -701,9 +669,7 @@ private void Evaluate() _data.EvaluationId = _evaluationLoggingContext.BuildEventContext.EvaluationId; _evaluationLoggingContext.LogProjectEvaluationStarted(); - InitializeParserIgnoreConfiguration(); - - string configMessage = _ParserIgnoreConfiguration?.GetLoadedConfigsMessage(); + string configMessage = _projectRootElementCache.ParserIgnoreConfiguration?.GetLoadedConfigsMessage(); if (configMessage is not null) { _evaluationLoggingContext.LogCommentFromText(MessageImportance.Low, configMessage); diff --git a/src/MSBuild/XMake.cs b/src/MSBuild/XMake.cs index 4d9645f7a9a..b4596c068a9 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -1703,14 +1703,12 @@ .. distributedLoggerRecords.Select(d => d.CentralLogger).Where(l => l is not nul enableTargetOutputLogging: isTaskAndTargetItemLoggingRequired, loadProjectsReadOnly: !isPreprocess, useAsynchronousLogging: true, - reuseProjectRootElementCache: s_isServerNode); + reuseProjectRootElementCache: s_isServerNode, + parseConfigDirectory: Path.GetDirectoryName(Path.GetFullPath(projectFile))); // globalProperties collection contains values only from CommandLine at this stage populated by ProcessCommandLineSwitches projectCollection.PropertiesFromCommandLine = [.. globalProperties.Keys]; - // Load parse config from the project file's directory before any project is loaded. - projectCollection.LoadParseConfigForStartup(Path.GetDirectoryName(Path.GetFullPath(projectFile))); - if (toolsVersion != null && !projectCollection.ContainsToolset(toolsVersion)) { ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, toolsVersion); @@ -2009,7 +2007,6 @@ .. distributedLoggerRecords.Select(d => d.CentralLogger).Where(l => l is not nul } finally { - projectCollection?.UnloadParseConfigForStartup(); projectCollection?.Dispose(); FileUtilities.ClearCacheDirectory(); From 5891abcd9fc69d5b751753686880ae832790c07e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Provazn=C3=ADk?= Date: Tue, 11 Aug 2026 11:51:18 +0200 Subject: [PATCH 16/20] Fix NotImplementedException when applying parse config to a new cache Every ProjectCollection constructor now calls SetParserIgnoreConfiguration. Because ProjectRootElementCacheBase.ParserIgnoreConfiguration starts null while LoadGlobalConfig always returns a non-null instance, the comparison never matched and DiscardImplicitReferences ran on every newly created cache - allocating a fresh weak cache and strong cache list each time, and throwing NotImplementedException outright on SimpleProjectRootElementCache. That broke ProjectCollection_Tests.ProjectRootElementCache_IsDeterminedByEnvironmentVariable on every CI leg. A cache that has not had a configuration applied yet holds nothing parsed under a different one, so skip the discard on that first initialization. Track it with a dedicated flag rather than a null configuration, which is itself a legitimate value produced by the escape hatch. Also implement DiscardImplicitReferences on SimpleProjectRootElementCache: it ignores isExplicitlyLoaded in Get, so every entry it holds is an implicit reference and clearing them all is correct. Replacing an already applied configuration reaches this path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e95248c0-c3a9-452d-b7da-bdc502cb3af3 --- .../ParserIgnoreConfiguration_Tests.cs | 21 +++++++++++++++++++ .../SimpleProjectRootElementCache_Tests.cs | 14 +++++++++++++ .../Evaluation/ProjectRootElementCacheBase.cs | 18 +++++++++++++++- .../SimpleProjectRootElementCache.cs | 4 +++- 4 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs b/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs index a19f0eba984..4eff64b50bf 100644 --- a/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs @@ -141,6 +141,27 @@ public void LoadGlobalConfigLoadsEnvironmentVariablePaths() } } + [Fact] + public void ConfigurationIsAppliedToSimpleProjectRootElementCache() + { + string envConfigPath = Path.Combine(_testDir, "env.config"); + File.WriteAllText(envConfigPath, @""); + + using TestEnvironment env = TestEnvironment.Create(); + env.SetEnvironmentVariable("MsBuildUseSimpleProjectRootElementCacheConcurrency", "true"); + env.SetEnvironmentVariable(ParserIgnoreConfiguration.EnvironmentVariableName, envConfigPath); + + using var projectCollection = new ProjectCollection(); + + projectCollection.ProjectRootElementCache.ShouldBeOfType(); + projectCollection.ParserIgnoreConfiguration.CheckSkipElement("Project", "CustomThing").ShouldBeTrue(); + + // Replacing the configuration invalidates what the cache parsed under the old one, which the simple + // cache has to be able to do as well. + projectCollection.ParserIgnoreConfiguration = ParserIgnoreConfiguration.Empty; + projectCollection.ParserIgnoreConfiguration.CheckSkipElement("Project", "CustomThing").ShouldBeFalse(); + } + [Fact] public void RecordsSkippedItems() { diff --git a/src/Build.UnitTests/Evaluation/SimpleProjectRootElementCache_Tests.cs b/src/Build.UnitTests/Evaluation/SimpleProjectRootElementCache_Tests.cs index 947d1dc22c6..10f35453870 100644 --- a/src/Build.UnitTests/Evaluation/SimpleProjectRootElementCache_Tests.cs +++ b/src/Build.UnitTests/Evaluation/SimpleProjectRootElementCache_Tests.cs @@ -26,6 +26,20 @@ public void Dispose() ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); } + [Fact] + public void DiscardImplicitReferences_RemovesAllEntries() + { + string projectFile = NativeMethodsShared.IsUnixLike ? "/foo" : "c:\\foo"; + ProjectRootElement rootElementToCache = ProjectRootElement.Create(projectFile); + + var cache = new SimpleProjectRootElementCache(); + cache.AddEntry(rootElementToCache); + + cache.DiscardImplicitReferences(); + + cache.Get(projectFile, null, false, null).ShouldBeNull(); + } + [Fact] public void Get_GivenCachedProjectFile_ReturnsRootElement() { diff --git a/src/Build/Evaluation/ProjectRootElementCacheBase.cs b/src/Build/Evaluation/ProjectRootElementCacheBase.cs index 9fe3cd83649..05a2065a2ba 100644 --- a/src/Build/Evaluation/ProjectRootElementCacheBase.cs +++ b/src/Build/Evaluation/ProjectRootElementCacheBase.cs @@ -14,6 +14,13 @@ internal abstract class ProjectRootElementCacheBase public ParserIgnoreConfiguration ParserIgnoreConfiguration { get; protected set; } + /// + /// Whether has already been applied to this cache. A null + /// is a legitimate configuration - it is what the escape hatch + /// produces - so it cannot itself stand for "never set". + /// + private bool _parserIgnoreConfigurationInitialized; + /// /// Handler for which project root element just got added to the cache /// @@ -79,7 +86,16 @@ internal void SetParserIgnoreConfiguration(ParserIgnoreConfiguration configurati return; } - DiscardImplicitReferences(); + // Entries parsed under the previous configuration may have skipped - or refused to skip - unknown + // attributes and elements that the new one treats differently, so they must be reparsed. A cache that + // has not had a configuration applied yet holds nothing parsed under a different one, so on that first + // initialization - which happens once per newly created cache - there is nothing to invalidate. + if (_parserIgnoreConfigurationInitialized) + { + DiscardImplicitReferences(); + } + + _parserIgnoreConfigurationInitialized = true; ParserIgnoreConfiguration = configuration; } diff --git a/src/Build/Evaluation/SimpleProjectRootElementCache.cs b/src/Build/Evaluation/SimpleProjectRootElementCache.cs index 646bcdcae40..1b3083756de 100644 --- a/src/Build/Evaluation/SimpleProjectRootElementCache.cs +++ b/src/Build/Evaluation/SimpleProjectRootElementCache.cs @@ -111,7 +111,9 @@ internal override void Clear() internal override void DiscardImplicitReferences() { - throw new NotImplementedException(); + // This cache does not track whether an entry was explicitly loaded - Get ignores isExplicitlyLoaded - + // so every entry it holds is an implicit reference and discarding all of them is the correct behavior. + Clear(); } internal override void DiscardAnyWeakReference(ProjectRootElement projectRootElement) From 9c4b962240b701d0eaf1da3031ee969054724cce Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Tue, 11 Aug 2026 07:40:11 -0400 Subject: [PATCH 17/20] Enable nullable in ParserIgnoreConfiguration_Tests.cs Remove #nullable disable from new test file per repo conventions. Fix two CS8600 warnings with string? annotations. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- .../Evaluation/ParserIgnoreConfiguration_Tests.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs b/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs index 4eff64b50bf..af001490354 100644 --- a/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ParserIgnoreConfiguration_Tests.cs @@ -9,7 +9,6 @@ using Shouldly; using Xunit; -#nullable disable namespace Microsoft.Build.UnitTests.Evaluation { @@ -127,7 +126,7 @@ public void LoadGlobalConfigLoadsEnvironmentVariablePaths() string envConfigPath = Path.Combine(_testDir, "env.config"); File.WriteAllText(envConfigPath, @""); - string oldEnv = Environment.GetEnvironmentVariable(ParserIgnoreConfiguration.EnvironmentVariableName); + string? oldEnv = Environment.GetEnvironmentVariable(ParserIgnoreConfiguration.EnvironmentVariableName); try { Environment.SetEnvironmentVariable(ParserIgnoreConfiguration.EnvironmentVariableName, envConfigPath); @@ -175,7 +174,7 @@ public void RecordsSkippedItems() config.CheckSkipAttribute("Target", "Foo"); config.CheckSkipAttribute("Target", "Foo"); - string summary = config.GetSkippedSummaryMessage(); + string? summary = config.GetSkippedSummaryMessage(); summary.ShouldNotBeNull(); summary.ShouldContain("Attribute:Target:Foo"); summary.ShouldContain("2 occurrences"); From f1f75a9291f684f60d56e10dcb467ad6418d3eea Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Tue, 11 Aug 2026 07:52:21 -0400 Subject: [PATCH 18/20] Default _ParserIgnoreConfiguration to Empty in BuildParameters Avoids null during serialization to worker nodes when no config is loaded. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- src/Build/BackEnd/BuildManager/BuildParameters.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Build/BackEnd/BuildManager/BuildParameters.cs b/src/Build/BackEnd/BuildManager/BuildParameters.cs index f96ab1f0c83..ae8b126be22 100644 --- a/src/Build/BackEnd/BuildManager/BuildParameters.cs +++ b/src/Build/BackEnd/BuildManager/BuildParameters.cs @@ -240,7 +240,7 @@ public class BuildParameters : ITranslatable /// The configuration for allowed unknown attributes/elements during parsing. /// Loaded on the main node and serialized to worker nodes. /// - private ParserIgnoreConfiguration _ParserIgnoreConfiguration; + private ParserIgnoreConfiguration _ParserIgnoreConfiguration = ParserIgnoreConfiguration.Empty; /// /// Constructor for those who intend to set all properties themselves. From 0651131c237c63ea16b9c002b652e47c09a381db Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Tue, 11 Aug 2026 07:54:12 -0400 Subject: [PATCH 19/20] Fix unbounded growth of binlog embed paths and skipped items Clear s_binlogEmbedPaths at the start of each build (ProjectCollection constructor) so it doesn't accumulate across builds in server scenarios. Clear _skippedItems after producing the summary message so it doesn't grow across evaluations on a shared config instance. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- src/Build/Definition/ProjectCollection.cs | 2 ++ src/Build/Evaluation/ParserIgnoreConfiguration.cs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/Build/Definition/ProjectCollection.cs b/src/Build/Definition/ProjectCollection.cs index 61c01467f0f..0e45791b17e 100644 --- a/src/Build/Definition/ProjectCollection.cs +++ b/src/Build/Definition/ProjectCollection.cs @@ -405,6 +405,8 @@ private ProjectCollection(IDictionary globalProperties, IEnumera if (!Traits.Instance.EscapeHatches.DisableParseConfig) { + ParserIgnoreConfiguration.ClearBinlogEmbedPaths(); + var config = ParserIgnoreConfiguration.LoadGlobalConfig(); if (!string.IsNullOrEmpty(parseConfigDirectory)) diff --git a/src/Build/Evaluation/ParserIgnoreConfiguration.cs b/src/Build/Evaluation/ParserIgnoreConfiguration.cs index 69d5aeb88b7..654e4b3d2c9 100644 --- a/src/Build/Evaluation/ParserIgnoreConfiguration.cs +++ b/src/Build/Evaluation/ParserIgnoreConfiguration.cs @@ -153,6 +153,8 @@ internal bool CheckSkipElement(string parentElementName, string childElementName sb.Append($" {kvp.Key} ({kvp.Value} occurrence{(kvp.Value > 1 ? "s" : string.Empty)});"); } + _skippedItems.Clear(); + sb.Length--; return sb.ToString(); } From 7210435fe4440e3b57781ff1364b90924614eb85 Mon Sep 17 00:00:00 2001 From: Ben Witman Date: Tue, 11 Aug 2026 07:55:32 -0400 Subject: [PATCH 20/20] Update spec and class docs to match current implementation Remove references to exe-dir and user-profile loading (removed earlier). Remove LoadParseConfigForStartup/UnloadParseConfigForStartup API docs (replaced by constructor parameter). Clarify that ParserIgnoreConfiguration property is internal. Fix binlog embedding description. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f7bff1-30bc-4b65-9555-b0f0a371f1c5 --- documentation/specs/directory-parse-config.md | 17 ++++++----------- .../Evaluation/ParserIgnoreConfiguration.cs | 7 +++---- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/documentation/specs/directory-parse-config.md b/documentation/specs/directory-parse-config.md index f224b009abf..900620c9459 100644 --- a/documentation/specs/directory-parse-config.md +++ b/documentation/specs/directory-parse-config.md @@ -86,26 +86,21 @@ Configuration is discovered from two sources: 1. **`MSBUILD_PARSE_CONFIG` environment variable** — Semicolon-separated (Windows) or colon-separated (Unix) list of config file paths. Always loaded when a `ProjectCollection` is created. -2. **Project directory walk** — The CLI walks up from the target project file's directory looking for `Directory.Parse.config` (same pattern as `Directory.Build.rsp`). Called via `ProjectCollection.LoadParseConfigForStartup(directory)` before any project is loaded. +2. **Project directory walk** — The CLI walks up from the target project file's directory looking for `Directory.Parse.config` (same pattern as `Directory.Build.rsp`). This is passed as `parseConfigDirectory` to the `ProjectCollection` constructor. These are merged additively — entries from either source are combined. -## Public API +## Integration -### `ProjectCollection.LoadParseConfigForStartup(string startingDirectory)` - -Walks up from `startingDirectory` to find a `Directory.Parse.config`, merges it with the current config, and sets it on the cache. Must be called before loading projects. Call `UnloadParseConfigForStartup()` after the build to restore the previous state. - -### `ProjectCollection.UnloadParseConfigForStartup()` - -Restores the parse configuration to the state before `LoadParseConfigForStartup` was called. +The `ProjectCollection` constructor accepts an optional `parseConfigDirectory` parameter. When provided, it walks up from that directory to find a `Directory.Parse.config` and merges it with the environment variable config. XMake passes the project file's directory. +The `ParserIgnoreConfiguration` property on `ProjectCollection` and `BuildParameters` is `internal`. External hosts that need to configure parse rules should use the constructor parameter or the environment variable. ## Logging - **Config files loaded**: Logged at evaluation start (`MessageImportance.Low`). Lists all loaded config file paths. -- **Config files embedded**: Each loaded config file is logged as a `ProjectImportedEventArgs`, causing the binary logger to embed the file content in the binlog. -- **Skipped items summary**: Logged after evaluation completes (`MessageImportance.Low`). Lists all skipped attributes/elements with occurrence counts. +- **Config files embedded**: Each loaded config file is embedded in the binary log archive (visible as an embedded file, not as a project import). +- **Skipped items summary**: Logged after each evaluation completes (`MessageImportance.Low`). Lists skipped attributes/elements with occurrence counts for that evaluation. ## Feature Flag diff --git a/src/Build/Evaluation/ParserIgnoreConfiguration.cs b/src/Build/Evaluation/ParserIgnoreConfiguration.cs index 654e4b3d2c9..a2eb61ea7c7 100644 --- a/src/Build/Evaluation/ParserIgnoreConfiguration.cs +++ b/src/Build/Evaluation/ParserIgnoreConfiguration.cs @@ -16,10 +16,9 @@ namespace Microsoft.Build.Evaluation /// /// Manages a set of allowed unknown attributes and elements that should be silently skipped /// during project parsing instead of throwing an InvalidProjectFileException. - /// Configuration is loaded from Directory.Parse.config files discovered additively from: - /// 1. Next to the MSBuild executable - /// 2. User profile (~/.msbuild/) - /// 3. MSBUILD_PARSE_CONFIG environment variable paths + /// Configuration is loaded from Directory.Parse.config files discovered from: + /// 1. MSBUILD_PARSE_CONFIG environment variable paths + /// 2. Walking up from the project file's directory (passed via ProjectCollection constructor) /// internal sealed class ParserIgnoreConfiguration : ITranslatable {