msbuild icon indicating copy to clipboard operation
msbuild copied to clipboard

Add EngineServices.TryGetItemSourceLocation for on-demand item source-location lookup

Open AlesProkop opened this issue 5 months ago • 0 comments

Context

Fixes: https://dev.azure.com/devdiv/DevDiv/_workitems/edit/2905535

Evaluated items (ProjectItemInstance / TaskItem) deliberately drop their XML location, so a NuGet restore warning about a <PackageReference> is reported at line 1 of the project rather than at the declaring element. NuGet cannot recover the location today: it receives items as MSBuild ITaskItems (which carry no source location) and has no XML line-info reading of its own. See #8128.

What this PR does (MSBuild-side enabling half)

Adds an EngineServices v3 API:

bool TryGetItemSourceLocation(string itemType, string itemSpec, out string file, out int lineNumber, out int columnNumber)

It lets a task resolve the file/line/column of the XML item element that declared a given evaluated item, on demand. It inspects only already-cached project XML (the project plus its import closure) via ProjectRootElementCache, so there is no project reload and no per-item memory cost on the normal build path — the "lazy" alternative to carrying location on every item instance.

To avoid reporting a confidently-wrong location, the lookup:

  • returns false for out-of-proc / AppDomain task hosts (cross-domain XML access is unsupported);
  • ignores <Target>-scoped items (produced at execution time, not part of the restore graph);
  • matches literal Includes only (skips $ @ % * ? expressions);
  • returns false when more than one literal match exists (e.g. conditional multi-targeting duplicates whose active condition cannot be determined from XML alone).

Still to be done

  • [ ] NuGet-side consumption — restore must call this API and stamp the resolved file/line/column onto its RestoreLogMessages so warnings land on the real <PackageReference> line. Tracked separately; this PR only supplies the MSBuild capability.
  • [ ] API review — confirm EngineServices (vs. a public IBuildEngineN member) is the right surface, and the Version3 bump.

Testing

  • 3 unit tests in TaskHost_Tests.cs (successful resolution, <Target>-scoped skip, ambiguous-duplicate → false) — green on net10.0 and net472.
  • Manual end-to-end via the bootstrap: an inline task calling the API resolved a <PackageReference> to its exact (line, column) (the Include attribute), while a real NU1701 restore warning on an equivalent project still reports line 1 — confirming the gap this closes.

Opened as draft: MSBuild half only, pending the NuGet follow-up above.

AlesProkop avatar Jun 25 '26 08:06 AlesProkop