[Macros] Accessing the "parent context" of a syntax node passed to a macro

I needed this today to expand a property-wrapper-esque macro differently when contained in a class than when contained in an actor. Keen for this on that basis alone :D

1 Like

What's the unit testing story for this? We've found with extension macros that there's no way for a test to pass the required context (about which conformances to add) through to the macro under test, and had to resort to hackery. This seems like it might suffer from the same kind of problem?

The information provided is purely lexical, so it should be the same in unit tests vs. with the compiler.

Doug

Hey all,

I am finally back to looking at this, with an updated implementation. based on the discussion here. The API is this:

  /// Return an array of enclosing lexical contexts for the purpose of macros,
  /// starting from the syntax node at which the macro expansion occurs
  /// and containing all "context" nodes including functions, closures, types,
  /// properties, subscripts, and extensions.
  ///
  /// Lexical contexts will have many of their details stripped out to prevent
  /// macros from having visibility into unrelated code. For example, functions
  /// and closures have their bodies removed, types and extensions have their
  /// member lists emptied, and properties and subscripts have their accessor
  /// blocks removed.
  ///
  /// The first entry in the array is the innermost context, which could be
  /// the syntax node to which
  var lexicalContext: [Syntax] { get }

And with the new implementation, it's tied in with the compiler.

Doug

16 Likes