Motivation
Multi-line string literals often get used to embed JSON, Yaml, JavaScript, etc. into Swift code, especially in tests.
However, for any given string literal, Swift does not seems to provide any official way to designate syntax its contents are supposed to conform to. Also, I was unable to find any prior suggestion about this. (Please correct me if I'm wrong, happy to withdraw this pitch if I missed something.)
Proposed Solution
To address this, please consider the following suggestion.
The idea is a new feature for multi-line string literals that allows the user to specify what format the nested content should conform to. Swift would provide a String.Syntax enumeration that would allow the programmer to choose amongst a wide range of existing formats to designate the string content as conforming to.
For example:
let foo = """
{ "foo": 42 }
""".syntax(.json)
let demoScript = """
document.getElementById("demo").innerHTML = "Hello JavaScript!"
""".syntax(.ecma.version(6))
let webPage = """
<!DOCTYPE html>
<html><body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='\(demoScript)'>Click Me!</button>
</body></html>
""".syntax(.html.version(3))
Alternatively we could go with:
let demoScript = """.ecma.version(6)
document.getElementById("demo").innerHTML = "Hello JavaScript!"
"""
... inspired by how you specify the format of a multiline string in Markdown.
To specify a syntax not provided in the built-in String.Syntax enum:
"""
/my/weird/&*format/
""".syntax(.custom("myWeirdFormat"))
## Implementation Details
If you are warm to the basic idea, whether it's feasible likely hinges on how it's supposed to be implemented from he compiler's standpoint. So let me pose a few questions to the community to kind of brainstorm how we might approach this:
1. What effect should specifying the syntax of a multiline string literal have, from the standpoint of the compiler?
2. Should this feature be implemented purely as a hook for IDEs/lint-scripts to provide syntax highlighting? If so, how might that change how the syntax for it should look?
3. If the programmer wants the compiler to validate their inset strings according to the specified syntax, how could we alleviate the responsibility of providing grammar-checking implementations from Swift itself? (I.e. how could we add extensibility to Swift that would allow third parties to offer syntax validation plug-ins to the compiler?)
Of course if something like this was already proposed or already exists, please let me know. Thanks!