Quasi-literals for templating?

Axel Rauschmayer axel at rauschma.de
Thu Jun 16 04:02:12 PDT 2011


If I may, let me try again and make the case for a more robust data structure for callSiteId. The reason of my insistence is that I've used a similar array encoding in the past (for message templates) and it has bitten me: people always got indices wrong (in a small library that students of mine used). A list of tokens was a more robust solution and might work for quasis, if an indirection is introduced. Many people will use these data structures, so they should be as fool-proof as possible.

########## Proposal ##########

    handler`aaa${foo}\nbbb`

desugars to:

    const callSiteId1234 = {
        tokens: [
            { raw: "aaa", cooked: "aaa" },
            { key: "foo", valueIndex: 0 },
            { raw: "\\nbbb", cooked: "\nbbb" },
        ]
    };
    handler(callSiteId1234, [foo]);

########## Using the proposal for the default impl. ##########

// default quasi tag impl. with data structures as shown above
function (callSiteId, substArray) {
    var out = [];
    callSiteId.tokens.forEach(function(token) {
        out.push(token.raw !== undefined ? token.raw : substArray[token.valueIndex]);
    });
    return out.join("");
}

// For comparison: default quasi tag impl. from spec
function (callSiteId /* , ...substitutions */) {
    var rawStrs = callSiteId.expandedLP;
    var out = [];
    var i = 0, k = -1, n = rawStrs.length - 1;
    while (i < n) {
        out[++k] = rawStrs[i];
        out[++k] = arguments[++i];
    }
    out[++k] = rawStrs[n];
    // As per the original Array.prototype.slice and Array.prototype.join.
    return out.join("");
}

########## Alternative: types for tokens ##########

One could also introduce types for tokens. Then the iteration body becomes:

    out.push(token instanceof LiteralSection ? token.raw : substArray[token.valueIndex]);
    
This is bike-shedding, but I’d also prefer "uninterpreted" and "interpreted" instead of "raw" and "cooked".

-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com





More information about the es-discuss mailing list