Search code examples
programming-languages

Iterating over a type's members at compile time


Is there any statically-typed, strongly-type compiled language that provides a functionality to iterate over a type's members at compile time and generate templated code for each one? For example, it could be something like:

// in pseudo-C#

public static void AddParameter(string parameterName, object value) { /* ... */ }

public static void AddParameters<T>(T parameters) {
    // Of course, the memberof(T), membersof(T), membername(<member>)
    // and membervalue(<member>, object) operators would be valid
    // inside a "compile for" block only
    compile for (memberof(T) member in membersof(T))
        AddParameter(membername(member), membervalue(member, parameters));

    /* If this were actual C#, the "compile for" block could even have a where clause */
}

So, if the following call was made:

StaticClass.AddParameters(new { UserID = "eleon", Password = "Gu3$$17" });

Then that particular instantiation of AddParameters would be unrolled to

public static void AddParameters(InternalNameOfTheAnonymousType parameters) {
    AddParameters("UserID",   parameters.UserID);
    AddParameters("Password", parameters.Password);
}

At compile-time (if it were actual C# at IL-to-native compile time)


Solution

  • You can do it with Nemerle.