Skip to content

Macro API with Context Parameters#63

Merged
raulraja merged 2 commits intomainfrom
enable-context-parameters
Nov 24, 2025
Merged

Macro API with Context Parameters#63
raulraja merged 2 commits intomainfrom
enable-context-parameters

Conversation

@bloderxd
Copy link
Collaborator

What

This PR brings a design proposal using Kotlin Context Parameters feature to Macros API. The idea is to use the power of context parameter to build elegant and simple macro code, the proposals are:

Context Parameter in Macro functions

Now developers can write macros using the benefits of context parameters:

@Macro(target = Product::class)
context(_: MacroContext)
fun product(firClass: FirClass): MacroCompilation {
  return firClass.transform {
    //language=kotlin
    """
      fun product(): List<Pair<String, *>> {               
        return listOf(${firClass.properties { """"${+it.name}" to this.${+it.name}""" }})
      }
    """.function().create()
  }
}

Some internal functions were also improved, for example properties that is a new version of propertiesOf, letting all macro construction more idiomatic and simple.

Changes in TransformClassCompilation

The proposal in this compilation is to improve members construction in this compilation, so instead of:

firClass.transform {
  property {
    """
      val b = 2
    """
  }
  function {
    """
      fun a() {}
    """
  }
  function {
    """
      fun b() {}
    """
  }
}

This PR proposes:

firClass.transform {
  """
    val b = 2
  """.property().create()
  """
    fun a() {}
  """.function().create()
  """
    fun b() {}
  """.function().create()
}

I'm not totally against curly braces style but I feel it's more clear and simple if we try to let this class transformation scope linear. The idea to divide create function from property and function functions for example, is to separate its concerns letting create function type safe but let me know if you prefer another approach like "val b = 2".createProperty() and "fun a() {}".createFunction

@bloderxd bloderxd self-assigned this Nov 21, 2025
@bloderxd bloderxd changed the title [WIP] Macro API with Context Parameters Macro API with Context Parameters Nov 21, 2025
Copy link
Member

@raulraja raulraja left a comment

Choose a reason for hiding this comment

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

Looks great!

@raulraja raulraja merged commit 16be1cf into main Nov 24, 2025
1 check passed
@raulraja raulraja deleted the enable-context-parameters branch November 24, 2025 16:40
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.

2 participants