swift-syntax icon indicating copy to clipboard operation
swift-syntax copied to clipboard

MacroSystem expansion detached nodes lose diagnostic context

Open stephencelis opened this issue 1 year ago • 4 comments

Description

Macro expansions create diagnostics that are not relative to the given context (because they're detached), which means that there's no way to collocate diagnostics with the original source.

Steps to Reproduce

You can take the AddBlocker macro demo from swift-macro-examples and expand the given macro:

let x = 1
let y = 2
let z = 3
#addBlocker(x * y + z)

If you expand as is, the context's diagnostic for the "+" will be relative to the #addBlocker expression macro node, not the entire source (starting at let x = 1), so formatting the diagnostics against the original source will render the diagnostic in the wrong place:

let x = 1
let y = 2
//       ╰─ warning: blocked an add; did you mean to subtract?
let z = 3
#addBlocker(x * y + z)

It can be rendered correctly by not detaching the context during expansion here:

-node: node.detach(in: context),
+node: node, //.detach(in: context),
let x = 1
let y = 2
let z = 3
#addBlocker(x * y + z)
//                ╰─ warning: blocked an add; did you mean to subtract?

Diagnostics added during expansion should ideally be adjusted from where they were detached.

stephencelis avatar Aug 12 '23 05:08 stephencelis