Skip to content

Feature Request: Reader macros #36590

@MasonProtter

Description

@MasonProtter

String macros are fine, but they really make the enclosed code feel like a second class citizen. Sometimes they make sense, but I think it would be really nice to have true reader macros. To copy-paste from my earlier issue #31449 which is apparently orthogonal to a pure-julia parser:


Having a Julia parser would make it possible to define a form of macro where code inside the macro scope is parsed according to user defined rules. These macros would essentially be string macros except you would no longer need to wrap the enclosed code in quotation marks, giving you truly arbitrary syntax inside a macro but retaining things like code highlighting, auto indentation, autocompletion, etc. Depending on the design of the Julia parser, it could also potentially offer more support when building reader macros than we currently offer for building string macros.

Reader macros wouldn't really allow for new features over string macros per se, but I think the fact that string macro code needs to be inside a string substantially hampers their adoption for many potential applications, especially DSL implementation.

Reader Macro Syntax

I'm not deadset on any particular syntax to mark a reader macro, but something like !@ could be used.

As an example Py2Jl.jl transpiler interface would go from

using Py2Jl

py2jl"""
def sum_by(f, seq):
    s = 0
    for e in seq:
        s = s + f(e)
    return s
"""

to

using Py2Jl

!@py2jl(
def sum_by(f, seq):
    s = 0
    for e in seq:
        s = s + f(e)
    return s
)

Obviously, there would have to be certain limitations put on reader macros, ie. if we use parens !@( ... ) to enclose code, then the parser for the macro must respect parenthesis balancing to make sure it doesn't leak out of its scope.


@JeffBezanson said in the earlier issue

I think the main objection people have is that they'd like to at least be able to parse julia code without a full julia runtime available.

I thought a bit about this and I think I'd respond that the parser could still support reader macros without having the full runtime available. We could just lower them to a string macro like representation, e.g. something like

Meta.parse("""
!@py2jl(
def sum_by(f, seq):
    s = 0
    for e in seq:
        s = s + f(e)
    return s
)
"""

#RESULTS 
quote
    !@py2jl"""
def sum_by(f, seq):
    s = 0
    for e in seq:
        s = s + f(e)
    return s
"""
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureIndicates new feature / enhancement requests

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions