Macros for method calls

I would like to realize macros that create method applications. But, according to my understanding, method calls cannot be created by macros. What I mean should become clearer with the following example.

In applications that process XML, I would like to have an #xPath macro as follows:

element.#xPath("section[1]/paragraph[3]")

should be translated to the following chain of method calls:

element.children("section")[1]?.children("paragraph")[3]

Given that this is not currently possible, is this a "good" idea, or are there too many "obstacles", or what would the limitations be of such macros if realized?

(Just to avoid misinterpretations of the code: The integer subscripts are not array indexes or another kind of random access, and they start at 1, I am using an "external" XML library here and not the standard XML library of Swift.)

6 Likes

It's not very ergonomic but I think you could do it as a global macro that takes parameters: #xPath(element, "section[1]/paragraph[3]").

1 Like

Yes, not ergonomic — of course this would have to be the current implementation, but I'm really repelled by it, even if it's irrational to a certain extent.

Unless you're dead set on compile time evaluation that optimizes something here (what does the macro actually generate), this seems doable with @dynamicMemberLookup's String version. That way you could have a dynamic path that returns a type with a subscript that you can keep matching on. element.section[1]?.paragraph[3] or something like that.

1 Like

The goal is to be able to use static literal XPath expressions in the code in an efficient way, nothing else is needed, because writing “element.children("section")[1]?.children("paragraph")[3]” is fine, no other notation necessary if it is not for the literal, unchanged XPath expressions.

(Sorry for changing the comment two times, my first answer was stupid and second answer not good…)