Skip to content

Instantly share code, notes, and snippets.

@run-dlang
Created October 22, 2023 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save run-dlang/b608aee44aaa56a432895abd43a5f456 to your computer and use it in GitHub Desktop.
Save run-dlang/b608aee44aaa56a432895abd43a5f456 to your computer and use it in GitHub Desktop.
Code shared from run.dlang.io.
import std.typecons;
import std.stdio;
import std.format;
import std.meta;
import std.algorithm;
import std.meta;
import std.array;
import std.conv;
import std.functional;
import std.range;
struct Expression {
size_t start;
size_t end;
}
Expression[] expressions(string s) {
Expression[] exprs;
size_t idx = 0;
while(s[idx..$].length >= 2) {
if(s[idx..$].startsWith("${")) {
auto end = s[idx..$].countUntil('}');
if(end != -1) {
exprs ~= Expression(idx,idx+end+1);
idx = idx+end;
}
idx += 1;
}
else {
idx += 1;
}
}
return exprs;
}
string replacewith(string s, Expression[] es, string r) {
foreach(e; es.retro) {
s = s[0..e.start]~"%s"~s[e.end..$];
}
return s;
}
string i(string istring)() {
enum exprs = istring.expressions;
enum exprs_strs= exprs.map!(expr => istring[expr.start+2.. expr.end-1]).map!(e=>'"'~e~'"').array;
enum fmtstr = replacewith(istring, exprs, "%s");
return `(){
import std.typecons, std.stdio, std.format, std.meta, std.algorithm, std.meta, std.array, std.conv, std.functional;
enum EXPR_STRS = [`~exprs_strs.join(", ")~`];
static foreach(I,E; EXPR_STRS) {
mixin("auto fn_"~I.to!string~"(){ return "~E~" ;}");
}
struct RESULT {
alias fn0 = fn_0;
alias fn1 = fn_1;
alias SEQ = AliasSeq!(fn_0, fn_1);
}
return RESULT();
}()
`;
}
int main() {
import std.stdio;
float foo = 44;
float bar = 22;
enum teststr = "${foo}${bar}";
//writeln(i!teststr);
writeln(mixin(i!teststr).fn0());
writeln(mixin(i!teststr).fn1());
writeln(mixin(i!teststr).SEQ[0]());
writeln(mixin(i!teststr).SEQ[1]());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment