Skip to content

Consolidate message code parsing and formatting into MessageParser and MessageFormatter - #14493

Merged
JanProvaznik merged 6 commits into
dotnet:mainfrom
DustinCampbell:consolidate-message-helpers
Jul 23, 2026
Merged

JanProvaznik merged 6 commits into
dotnet:mainfrom
DustinCampbell:consolidate-message-helpers

Conversation

@DustinCampbell

@DustinCampbell DustinCampbell commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

Moves the ad-hoc message-code parsing and string formatting scattered across ResourceUtilities into two focused, testable helpers in Microsoft.Build.Framework:

  • MessageParser replaces ExtractMessageCode. For both MSBnnnn and arbitrary letter+digit codes it offers extract-code-and-message, code-only, and message-only variants, so callers don't allocate what they don't need.
  • MessageFormatter replaces ResourceUtilities.FormatString, centralizing composite formatting and its debug-time argument validation behind one entry point.

Callers are migrated to the new helpers and the old code is deleted, along with ResourceUtilities_Tests (now a subset of the new MessageParser_Tests).

One intentional behavior change: for a message that is a code followed only by whitespace (e.g. "MSB1234: "), ExtractMessageCode returned the full unstripped message; MessageParser now correctly returns an empty message.

Introduce CharExtensions with ASCII classification helpers (IsAsciiLetter, IsAsciiLetterLower/Upper, IsAsciiDigit, IsAsciiLetterOrDigit, IsAsciiHexDigit/Upper/Lower, IsBetween) as an extension block on char, providing the modern System.Char APIs on target frameworks that lack them (#if !NET).

Extend HexConverter with IsHexChar, IsHexUpperChar, and IsHexLowerChar, adapted from the .NET runtime, to back the hex-related CharExtensions helpers. Make HexConverter's helpers available on all target frameworks (not just #if NET) since CharExtensions depends on them.
Add MessageParser to Framework, porting the prefix-stripping logic from
ResourceUtilities.ExtractMessageCode into a focused, testable helper. For each
of the two code shapes -- strict MSBnnnn codes and arbitrary letter+digit codes
-- MessageParser exposes a trio of entry points so callers only pay for what
they need:

  - TryParse* returns both the code and the stripped message.
  - TryGet*   returns only the code, without allocating the message.
  - TryStrip* returns only the stripped message, without allocating the code.

Parsing is centralized in a private Scanner ref struct that walks the text once,
skipping leading whitespace in its constructor and exposing the small grammar
(read/consume a code, consume a delimiter, take the remainder) as instance
methods. This replaces the earlier set of static (string text, ref int i)
helpers. Parsing uses the ASCII char helpers throughout.

Note that this intentionally changes behavior relative to ExtractMessageCode for
one edge case: when the text is a code followed only by whitespace (e.g.
"MSB1234:   "), ExtractMessageCode returned the full, unstripped original
message because its final `if (i < message.Length)` guard was false once
trailing whitespace was skipped. That behavior is never correct, so MessageParser
instead returns an empty message, consistent with the code-only case.

Rewrite ResourceUtilities.ExtractMessageCode to delegate to MessageParser,
deleting the hand-rolled character scanning, the CA1502 complexity suppression,
and the dead BUILDINGAPPXTASKS scaffolding (that symbol is never defined in this
repo).

Add MessageParser_Tests covering valid codes, invalid codes, and code-only
(empty message) cases across the parse/get/strip variants. Remove
ResourceUtilities_Tests, whose ExtractMessageCode cases are now a strict subset
of MessageParser_Tests, and drop its links from the Build, Tasks, and Utilities
unit test projects.
Remove ResourceUtilities.ExtractMessageCode and call MessageParser directly at
every callsite, completing the move begun when MessageParser was introduced.

In ResourceUtilities, the FormatResourceStringStripCodeAndKeyword overloads that
report the code and help keyword call TryParseMSBuildCode inline, returning the
stripped message on success and the original otherwise. The five overloads that
discard the code and keyword now call TryStripMSBuildCode instead of forwarding
through the reporting overloads, so they no longer look up a help keyword or
allocate a code substring only to throw both away.

In TaskLoggingHelper, the public ExtractMessageCode API is retained but
reimplemented on top of TryParseAnyCode. The DEBUG-only sanity checks that assert
a message has no code use the code-only TryGetMSBuildCode overload, and the
exception-logging path uses the code-only TryGetAnyCode overload, so no stripped
message is allocated. The DEBUG asserts are written as Assumed.False with
lazily-formatted interpolated messages and nameof.
The ResourceUtilities.Format* methods that take params arrays were annotated params object?[]? args, allowing the args array itself to be null. That does not match the BCL's string.Format (params object?[] args): a null args array is never meaningful, so callers should get a nullability warning rather than silently passing null. Drop the outer ? so the array is non-nullable while its elements remain nullable.

Apply the same tightening to the ErrorUtilities.ThrowInvalidOperation and ThrowArgument overloads, which forward their args straight to FormatResourceStringStripCodeAndKeyword.

Update callers that relied on the looser annotation: drop the redundant null array passed to the arg-less overloads (ProjectRootElement, ErrorUtilities' internal call sites, ConsoleLogger_Tests) and coalesce a nullable test input to an empty array in MSBuildInternalMessage_Tests. All of these resolve to the same "no formatting" behavior as before, so there is no functional change.
Copilot AI review requested due to automatic review settings July 22, 2026 21:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors message-code parsing and composite-string formatting by moving logic previously embedded in ResourceUtilities into two dedicated helpers in Microsoft.Build.Framework (MessageParser and MessageFormatter), then migrates callers across the repo and updates tests accordingly.

Changes:

  • Introduces MessageParser (code/message extraction) and MessageFormatter (composite formatting + debug validation) under Microsoft.Build.Framework.Utilities.
  • Migrates MSBuild logging and task/host code to use the new helpers and removes the old ResourceUtilities ad-hoc implementations and associated shared tests.
  • Updates test projects and adds new MessageParser unit tests (including the intended behavior change for code-only + whitespace).

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/Utilities.UnitTests/Microsoft.Build.Utilities.UnitTests.csproj Stops compiling the removed shared ResourceUtilities_Tests.
src/Tasks/ErrorFromResources.cs Switches error-code parsing from ResourceUtilities to MessageParser.
src/Tasks.UnitTests/MSBuildInternalMessage_Tests.cs Ensures args passed to formatting helpers are non-null (uses ?? []).
src/Tasks.UnitTests/Microsoft.Build.Tasks.UnitTests.csproj Stops compiling the removed shared ResourceUtilities_Tests.
src/Shared/UnitTests/ResourceUtilities_Tests.cs Removes old ExtractMessageCode tests (superseded by MessageParser_Tests).
src/Shared/TaskLoggingHelper.cs Routes formatting and code parsing through MessageFormatter/MessageParser and updates DEBUG assertions.
src/Shared/ResourceUtilities.cs Deletes ExtractMessageCode/FormatString implementations and forwards to new helpers.
src/Shared/ErrorUtilities.cs Updates params usage patterns (no longer passes null to params).
src/MSBuild/OutOfProcTaskHostNode.cs Uses MessageFormatter for resource formatting and modernizes event-args construction.
src/MSBuild/OutOfProcTaskAppDomainWrapperBase.cs Uses MessageFormatter for error formatting in task-host logging.
src/MSBuild/InitializationException.cs Uses MessageFormatter for exception message formatting.
src/Framework/Utilities/MessageParser.cs Adds new scanner-based parsing helpers for MSB and arbitrary codes.
src/Framework/Utilities/MessageFormatter.cs Adds centralized composite formatting + DEBUG arg validation.
src/Framework/Utilities/HexConverter.cs Extends hex utilities used by ASCII/hex-related polyfills.
src/Framework/Polyfills/CharExtensions.cs Adds non-NET polyfills for char.IsAscii* APIs.
src/Framework.UnitTests/MessageParser_Tests.cs Adds unit test coverage for parsing/stripping codes including whitespace-only message behavior.
src/Build/Construction/ProjectRootElement.cs Updates call to ThrowInvalidOperation to match new params usage.
src/Build.UnitTests/Microsoft.Build.Engine.UnitTests.csproj Stops compiling the removed shared ResourceUtilities_Tests.
src/Build.UnitTests/ConsoleLogger_Tests.cs Updates calls to FormatResourceStringStripCodeAndKeyword to avoid passing null args.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

This is a well-structured refactoring that cleanly separates message parsing (MessageParser) from message formatting (MessageFormatter), removing the monolithic ResourceUtilities.FormatString and ExtractMessageCode. The behavioral semantics are preserved across all callsites.

Findings

MINOR (nit): Double period in MessageFormatter.cs XML doc (line 13): override.. should be override.

Positive observations

  • The ref struct Scanner in MessageParser is allocation-efficient and well-designed.
  • Good use of [NotNullWhen(true)] annotations for nullable flow analysis.
  • Typed overloads (1-3 args) preserved to avoid array allocations on hot paths.
  • Test coverage in MessageParser_Tests.cs is thorough and properly replaces the deleted ResourceUtilities_Tests.cs.
  • Disallowing null args arrays is a good API hygiene improvement.

No blocking issues found

The behavioral contract is preserved: when no code is found, code out params are null and the full message is returned.

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • awmgmcpg

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "awmgmcpg"

See Network Configuration for more information.

Generated by Expert Code Review (on open) for #14493 · 103.1 AIC · ⌖ 5.09 AIC · ⊞ 5K

Add MessageFormatter to Framework, a focused helper for formatting composite
format strings. It exposes overloads for 1-3 arguments (avoiding array
allocations), a params object?[] overload, and, on modern targets, a
params ReadOnlySpan<object?> overload, each with an optional CultureInfo. When no
arguments are supplied the format string is returned unchanged, matching the
previous FormatString behavior.

Move the debug-time argument validation here as well. The old ValidateArgsIfDebug
walked the argument array to catch values whose ToString() just returns their
type name (a common sign of passing the wrong object to a format call); the new
ValidateArg does the same per argument, short-circuiting strings up front and
using Assumed.NotEqual with a lazily-formatted message so nothing is allocated
when the check passes. The single-argument paths validate directly instead of
allocating a throwaway array.

Rewrite the ResourceUtilities.FormatString overloads to delegate to
MessageFormatter, deleting the hand-rolled string.Format calls and the local
ValidateArgsIfDebug helper, and drop the now-unused System.Globalization import.
Delete the internal ResourceUtilities.FormatString overloads and have every
caller use MessageFormatter.Format directly, so there is a single formatting
entry point now that the debug-time argument validation lives in
MessageFormatter.

Within ResourceUtilities, the FormatResourceStringStripCodeAndKeyword and
FormatResourceStringIgnoreCodeAndKeyword families call MessageFormatter.Format
inline. External callers are updated in kind.
@DustinCampbell
DustinCampbell force-pushed the consolidate-message-helpers branch from ce7372b to d3f8c0d Compare July 22, 2026 21:37

@JanProvaznik JanProvaznik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks, nice refactor

@JanProvaznik
JanProvaznik merged commit 8c6eac5 into dotnet:main Jul 23, 2026
12 checks passed
@DustinCampbell

Copy link
Copy Markdown
Member Author

Thanks! Just trying to reduce ResourceUtilities and ErrorUtilities so we can bring the MSBuild string resources to a simpler architecture.

@DustinCampbell
DustinCampbell deleted the consolidate-message-helpers branch July 23, 2026 16:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants