__FUNC__ in D
Regan Heath
regan at netmail.co.nz
Wed Aug 15 12:56:02 PDT 2007
argl wrote:
> BCS Wrote:
>> It's a hypothetical function that doesn't exist (yet). However, it's
>> shouldn't be two hard to wright one that would work for most case.
>
> I see. Thank you.
Quick and dirty!
import std.stdio, std.string, std.ctype;
alias std.string.tolower tolower;
void main()
{
foo();
bar();
baz();
}
void foo()
{
string fn = FnName(import(__FILE__), __LINE__);
writefln(fn);
}
void bar ()
{
string fn = FnName(import(__FILE__), __LINE__);
writefln(fn);
}
const(char)baz ()
{
string fn = FnName(import(__FILE__), __LINE__);
writefln(fn);
return cast(const(char))'c';
}
string FnName(string file, uint line)
{
string name;
string last;
int level;
int start;
int end;
foreach(nLine, s; splitlines(file))
{
foreach(ref p; s.split())
{
if (p.contains(cast(const(char))'{')) level++;
if (p.contains(cast(const(char))'}')) level--;
if (level > 0) continue;
if (p.contains(cast(const(char))'#')) continue;
if (isKeyword(p)) continue;
if (p.contains(cast(const(char))'('))
{
end = p.find('(');
if (end == 0)
{
p = last;
end = p.length;
}
for(start = end-1; start > 0; start--)
{
if (!isalnum(p[start]))
{
start++;
break;
}
}
name = p[start..end].dup;
}
last = p;
}
if (nLine > line) break;
}
return name;
}
bool isKeyword(string word)
{
return keywords.contains(tolower(word));
}
bool contains(T)(T[] arr, T val)
{
foreach(i; arr) if (i == val) return true;
return false;
}
string[] keywords = [
"abstract",
"alias",
"align",
"asm",
"assert",
"auto",
"body",
"bool",
"break",
"byte",
"case",
"cast",
"catch",
"cdouble",
"cent",
"cfloat",
"char",
"class",
"const",
"continue",
"creal",
"dchar",
"debug",
"default",
"delegate",
"delete",
"deprecated",
"do",
"double",
"else",
"enum",
"export",
"extern",
"false",
"final",
"finally",
"float",
"for",
"foreach",
"foreach_reverse",
"function",
"goto",
"idouble",
"if",
"ifloat",
"import",
"in",
"inout",
"int",
"interface",
"invariant",
"ireal",
"is",
"lazy",
"long",
"macro",
"mixin",
"module",
"new",
"null",
"out",
"override",
"package",
"pragma",
"private",
"protected",
"public",
"real",
"ref",
"return",
"scope",
"short",
"static",
"struct",
"super",
"switch",
"synchronized",
"template",
"this",
"throw",
"__traits",
"true",
"try",
"typedef",
"typeid",
"typeof",
"ubyte",
"ucent",
"uint",
"ulong",
"union",
"unittest",
"ushort",
"version",
"void",
"volatile",
"wchar",
"while",
"with",
"__FILE__",
"__LINE__",
"__DATE__",
"__TIME__",
"__TIMESTAMP__",
"__VENDOR__",
"__VERSION__"
];
More information about the Digitalmars-d-learn
mailing list