c3lang / c3c

Compiler for the C3 language
GNU Lesser General Public License v3.0
1.34k stars 80 forks source link

Compile time string concatenation #1208

Open cbuttner opened 2 weeks ago

cbuttner commented 2 weeks ago

I often find myself needing some way to concatenate strings at compile time.

Maybe a builtin $concat with variable number of arguments could be introduced.

Some examples of what I image it to look like:

macro echo_code_loc() => $echo $concat($$FILE, ":", $$LINE);

// Console output with virtual terminal sequences
macro color_code($id) {
  $if env::WINDOWS:  
    return $concat("\x1b[1;", $id, "m")
  $else
    return $concat("\x1b[", $id, "m")
  $endif
}

const TERM_RESET = color_code("0");
const TERM_BOLD = color_code("1");

fn print_to_console(bool colored) {
  String fmt = colored ? $concat(TERM_BOLD, "%s", TERM_RESET, "%s") : $concat("%s", "%s");
  io::printfn(fmt, "Hello bold output", "1234");
}

// Some libraries such as ICU do this:
const VERSION_SUFFIX = "_74"
fn ZString getName(UScriptCode scriptCode) @extern($concat("uscript_getName", VERSION_SUFFIX));
lerno commented 2 weeks ago

This could probably be implemented as a compiler builtin $$concat which is then exposed as a stdlib macro @concat()

lerno commented 2 weeks ago

Other functions proposed are at #828

lerno commented 2 weeks ago

$append and $concat are now added. Please test them out from dev