[Pitch #2] Expression macros

In addition, there's a sample project repository that you can use with a development toolchain to try out macros.

Doug

5 Likes

Is there any way to debug or get print output from the macro implementation right now? I'd like to explore what we get in there but these are libraries, not executables.

There's a debug dump. Pass -Xfrontend -dump-macro-expansions to the compiler and it'll emit something like this:

Macro expansion of #stringify(_:) in /path/to/MacroExamples/MacroExamples/main.swift:6:7-6:24 as (Int, String)
------------------------------
(x + y, "x + y")
------------------------------

Doug

4 Likes

Macro arguments are type-checked against the parameter types of the macro prior to instantiating the macro.

macro stringify<T>(_: T) -> (T, String)

But what about scenario where I might want to construct type based on the input provided, i.e. building a type from json string:

macro jsonObj<T>(_: String) -> T

let obj = #jsonObj("""
{
"one": 1,
"two": 2
}
""")

Or registering routes in a server framework:

app.get("hello/:name") { req in
    // req could be inferred from the provided string as
    // SomeGenericStruct<(name: String)>
    let name = req.parameters.name
    return "Hello, \(name)!"
}

Although, such scenario can degrade compile-time performance by having to expand the macro for type inference, but having this as an option would be really beneficial.

Hi @soumyamahunt! This pitch is now a proposal under review here—I think it may be helpful to post any questions and clarifications there so that everyone's on the same page.

1 Like