Is it possible to disambiguate `class` better?

I am playing with the pointfreeco/swift-html HTML DSL. The core idea of the library is to offer a number of functions to build an HTML node tree using an ergonomic syntax:

let node = div([class("container")], [
    h1([
        a([href("/")], ["Home"])
    ]),
])

This works very well (if you’re in the market for HTML generation, give it a go!), but I keep running into name clashes. One simple case is the class name that’s used both in HTML and in Swift. So this doesn’t compile:

// <small class="sample">whatever</small>
// error: expected expression in list of expressions
// error: consecutive statements on a line must be separated by ';'
// error: expected identifier in class declaration
let foo = small(class("sample"), "whatever")

The class function needs to be disambiguated using backticks or a namespace prefix:

let foo = small(`class`("sample"), "whatever")
let foo = small(Html.class("sample"), "whatever")

But this adds unwanted noise into the DSL. Is there a better solution? Could the compiler be “smarter” about expressions such as class("sample") and not require the backticks, recognizing the function call automatically? Or, in the very least case, bail with a better error message? I realize this may have some significant downsides, but I figured it doesn’t hurt to ask at least.

PS. I am aware of the simple let klass = Html.class sort of workaround, but I am kind of interested in a more general solution.

2 Likes

Swift does have a number of "context-sensitive keywords", which is the compilery term for "being smarter about how something is used", but for something like class, which can appear pretty much anywhere a statement can start, it's not necessarily a good idea to start adding special cases. "Followed by a parenthesis" seems like a pretty good rule until someone wants to add syntax similar to private(set).

(Counterintuitively, allowing this kind of context-sensitivity can also make things worse sometimes.)

That said, we're always glad to have better error messages, and looking for a following parenthesis is probably a good way to detect what happened and recover. Please file a bug at https://bugs.swift.org!

2 Likes