Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add StringLiteral#scanmacro method #15397

Closed
homonoidian opened this issue Feb 1, 2025 · 0 comments · Fixed by #15398
Closed

Add StringLiteral#scanmacro method #15397

homonoidian opened this issue Feb 1, 2025 · 0 comments · Fixed by #15398

Comments

@homonoidian
Copy link
Contributor

Feature Request

It is possible to go through all matches using StringLiteral#gsub, but doing that is needlessly cumbersome and... wrong. That's not what it's supposed to do, at the very least. StringLiteral#scan, on the other hand, should simplify this / fill in the gap, which would be very nice. Instead of exposing Regex::MatchData on the macro side we can expose Regex::MatchData#to_h, leaving us with StringLiteral#scan(regex : RegexLiteral) : ArrayLiteral(HashLiteral(NumberLiteral | StringLiteral), StringLiteral | NilLiteral)

In my particular case, I am relying on it heavily -- I have a case macro for my own pattern matching system and to reduce typing on the Crystal side, I want it to be able to interact with Crystal at compile-time a tiny bit, through mutual understanding of certain constructs.

Term.case(...) do
  matchpi %[(%terminal successor_)], %[(%'%let _ successor_)] do
    specificity0?(successor)
    #                ^^^
    # Note the use of successor on the Crystal side, extracted from the string above
    # using StringLiteral#scan
  end
end

A very similar use case to mine would be a macro that takes a regex, extracts named captures, and gives them to a block to reduce typing. The captures can be accessed in the block as variables. Or for example, a macro that takes a URL pattern, extracts parameter names from it, and gives them to the block in parsed form, so they can be accessed as properly typed variables. Similarly, one can imagine a macro that inspects the source code of the program itself for commands or directions, and so on. And much more!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant