Skip to content

Suggestion: type inference #1

@shaps80

Description

@shaps80

Hi, when macros were first available I had the same idea as you.

Its great to have type-safety but also to simply remove the runtime cost of parsing the string.

One suggestion (perhaps improvement) I made in my own version was I didn't want to have multiple #color, #uicolor, #nscolor (I also had a couple others for windows, linux support).

If you use the lexical context in your macros you can workout what type the user is trying to convert to:

let color: UIColor = #color("fff")

// macro -- UIColor
context.lexicalContext.compactMap { $0.as(PatternBindingSyntax.self) }.first?.typeAnnotation?.type

And since I'm 95% of the time working in SwiftUI these days, I just make that the default so in those cases no type-annotation is required.

This approach btw, also allows you to detect when the user is defining an extension. So you can even make "theme" definitions nicer. This occurred to me after I saw @Entry and similar macros in recent SwiftUI releases. I checked and enough context is available from a @freestanding(expression) 👍

extension UIColor {
    static let error = #color("0ff")
}

// macro: extension on UIColor
context.lexicalContext.compactMap { $0.as(ExtensionDeclSyntax.self) }.first?.extendedType

You can even mix these, just use the typeAnnotation as an "override" if its defined inside an extension.

Just an idea. Nice work tho 👏

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions