Search code examples
crubystringcompiler-construction

Translating String Interpolation to C


I'm well on my way on a programming language I've written in Java that compiles directly into C99 code. I want to add string interpolation functionality and am not sure what the resulting C code would be. In Ruby, you can interpolate strings: puts "Hello #{name}!" What would be the equivalent in C?


Solution

  • So called interpolated strings are really just expressions in disguise, consisting of string concatenation of the various parts of the string content, alternating string literal fragments with interpolated subexpressions converted to string values.

    The interpolated string

           "Hello #{name}!"
    

    is equivalent to

           concatenate(concatenate("Hello",toString(name)),"!")
    

    The generalization to more complicated interpolated strings should be obvious.

    You can compile it to the equivalent of this in C. You will need a big library of type-specific toString operations to match the types in your language. User defined types will be fun.

    You may be able to implement special cases of this using "sprintf", which is the string-building version of C's "printf" library function, in cases where the types of the interpolated expressions match the limited set of types that printf format strings can handle (e.g., native ints and floats).