usethesource / rascal

The implementation of the Rascal meta-programming language (including interpreter, type checker, parser generator, compiler and JVM based run-time system)
http://www.rascal-mpl.org
Other
404 stars 78 forks source link

string for-loop interpolation with "separator" feature requested #2058

Open jurgenvinju opened 7 hours ago

jurgenvinju commented 7 hours ago

It currently requires more unquoting and quoting than desirable to generate source code that uses separators.

In the following code the newlines are separators. If they would not be, there will be superfluous newlines generated which is not nice.

extends = [trim("<i>") | i <- h.imports, i is \extend];
    imports = [trim("<i>") | i <- h.imports, i is \default];
    grammar = [trim("<i>") | i <- h.imports, i is \syntax];

    newHeader = "<for (i <- sort(extends)) {><i>
                '<}>"[..-1] +
                "<if (extends != []) {>
                '
                '<}><for (i <- sort(imports)) {><i>
                '<}>"[..-1] +
                "<if (imports != [] && grammar != []) {>
                '
                '<}><for (i <- grammar) {><i>
                '<}>"[..-1];

If the for loop could know it was generating separated lists instead of a normal lists, then we would not have to remove the trailing newlines with [..-1] and unquote and quote again after every block, and we would not have to test for emptiness of predecessors:

    extends = [trim("<i>") | i <- h.imports, i is \extend];
    imports = [trim("<i>") | i <- h.imports, i is \default];
    grammar = [trim("<i>") | i <- h.imports, i is \syntax];

    newHeader = "<for-sep (i <- sort(extends)) {><i>
                '<}>
                '<for-sep (i <- sort(imports)) {><i>
                '<}>
                '<for-sep (i <- grammar) {><i>
                '<}>";

Where the literal characters after the last interpolated element would not be printed because that would not be a separator. This code is much cleaner.

The name for-sep is up for debate of course. Alternatives welcome.

jurgenvinju commented 7 hours ago

another option would be to wrap the separator: <sep {> <}>