Skip to content

Swift Testing Macros - empty MacroExpansionContext.lexicalContext #79447

Open
@adammcarter

Description

@adammcarter

Description

Following a discussion here:

https://forums.swift.org/t/generate-swift-testing-code-with-macros/77883

And further DMs to diagnose the issue (quote and credit to @grynspan):

I took a look and this appears it may be a bug in the compiler's macros implementation. There is a MacroExpansionContext.lexicalContext property available to the expansion of @Test that we use to determine if a test is a member of a type or not (and therefore whether thunk functions we emit need the static keyword or not), but it appears to be empty in the context of expanding @SnapshotTest. Please file a bug against the swift or swift-syntax repo?

I was able to get the code to compile by changing the macro expansion so it emitted the @Test function into a structure. This isn't ideal because it will cause the test function to be nested in a suite with an inscrutible name (generated by MacroExpansionContext.makeUniqueName()), but it does allow the macro expansion to compile successfully.

Happy to post more on this, but I think that quote above should give enough explanation.

I've also attached example project as a quick way to see this error and hopefully help diagnose the issue

SnapshotSuite.zip

Steps to Reproduce

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.swift macroFeature → declarations: Swift `macro` declarations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions