Variadic Generics determined by static arguments

In interesting Idea I had was to use static variables to determine Variadic Generics.

This is what I mean by using C's printf as an example:

func printf(format: static String, _ args: Vargs) {
    var string = ""
    var iterator = format.makeIterator()

    while let char = iterator.next() {
        switch char {
        case "%":
            switch iterator.next() {
                case "i"?:
                    string.append("\(args.pop() staticCastTo Int)")
                case "s"?:
                    string.append(args.pop() staticCastTo String)
                default:
                fatalError()
            }
        default:
            string.append(char)
        }
    }
    print(string)
}

In this example, if format is known at the call site, then the argument types of Vargs could be determined at the call site by evaluating the branches of the printf function based on the information known at compile time. For this to work, format must be resolved at compile time. This is why format is marked with static.

Some minor points:

  • There is already a StaticString type. I could have used this, but I also want to apply the concept to other types such as a static Int, which is an Int that is resolved at compile time.
  • The fatalError would be better as a compile time error, as this could be determined at compile time with the static string.
  • staticCastTo is a compile time version of as! (the name of staticCastTo should probably be changed)
  • Though not necessary in this example, a switch statement that would have staticCastTo cases could be useful. This way of resolving types would not need static variable.

I think it's expected that compile-time evaluation might cover some of these kind of use cases, rather than designing a new feature for every situation.

1 Like

I think there is already some discussion around compile-time code execution. The keyword to look for should be constexpr.

2 Likes

Or compilerEvaluable.

FYI, I think Apple's OSLog team is doing something like this. Although, strangely, the compiler seems to require specific knowledge about those APIs. I hope that's just a stopgap until the constant-evaluator is more fully developed. Perhaps @ravikandhadai can shed some light on it.

1 Like