Ellery Newcomer wrote:
Are there any good libraries for ctfe/code generation?

I don't know, things like parsing support for compile time strings, string formatting, type <-> string

My project seems to be growing ctfe, and it's all horribly hacky and ugly code.

I've found that the function below improves things immensely. I might propose it for std.metastrings in the next Phobos release.

===============

/** Escape any quotes and backslashes inside the given string,
 * prefixing them with the given escape sequence. Use `\` to escape
 * once, `\\\` to escape twice.
 */
string enquote(string instr, string escape = `\`)
{
    // This function is critical for compilation speed.
    // Need to minimise the number of allocations.
    // It's worth using copy-on-write even for CTFE.

    for(int i = 0; i < instr.length; ++i)
    {
        if (instr[i] == '"' || instr[i] == '\\')
        {
            string str = instr[0..i] ~ escape;
            int m = i;
            foreach(int k, char c; instr[i+1..$])
            {
                if (c=='"' || c=='\\')
                {
                    str ~= instr[m..i+1+k] ~ escape;
                    m = i+k+1;
                }
            }
            return str ~ instr[m..$];
        }
    }
    return instr;
}

unittest {
    assert(enquote(`"a\"`)==`\"a\\\"`);
    assert(enquote(`abc`)==`abc`);
}

Reply via email to