Repository navigation
Description
Problem
Generic functions, as currently supported in Zig have the form
fn eql(x: anytype, y: @TypeOf(x)) bool {
return x == y;
}This works well enough in general, but also has some problems and limitations:
1. Aesthetics
Besides the controversial keyword (#5893), the @TypeOf pattern is a bit of a hack, even though everybody is used to it by now. It somewhat obscures the fact that eql takes two arguments of the same type. It also leads to unnecessary verbosity in some cases:
fn foo(x: anytype, y: @TypeOf(x)) Container(@TypeOf(x)) {
const T = @TypeOf(x);
...
}2. Type signatures
The type of a simple function like same(x: i32, y: i32) bool {...}, is fn(i32, i32) bool. For the generic function eql, the intended type is something like fn<T>(T,T) bool. But the actual type inferred by the compiler seems to be fn(anytype,anytype) anytype. In my limited testing, I found that the compiler essentially considers all generic and parametric functions to have the same type. Only the number of arguments is checked. E.g., the following code compiles:
const eq: fn(anytype, f32) i32 = eql; // should have failed
assert(eq(1, 1));It seems that the type check automatically simplifies to const eq: any_generic_function = eql;, which then succeeds. Maybe this is a limitation of the compiler that can be fixed independently, but then only in part. For example, the fact that both arguments of eql should have the same type is simply not expressible in the current system, since parameter names are not part of the type: fn(anytype, @TypeOf(?)) bool.
This state of affairs reduces the precision of type checks, and also discards valuable information that could be used by documentation generators, mataprogrammed interfaces and error messages.
3. Order dependence
Another minor nit is that generic functions constrain the order of function parameters in some cases. This, for example, is not possible:
fn find(haystack: ArrayList(@TypeOf(needle)), needle: anytype) usize {...} // errorThe arguments need to be the other way round, although logically they can be in any order. This is an arbitrary, albeit minor, limitation.
Proposed solution
Change the fn(x: anytype) syntax to fn(x: infer T), which infers the type of x and binds it to T. Example:
// before:
fn eql(x: anytype, y: @TypeOf(x)) bool {...}
// after:
fn eql(x: infer T, y: T) bool {...}
// before:
fn find(needle: anytype, haystack: ArrayList(@TypeOf(needle))) usize {...}
// after:
fn find(needle: infer T, haystack: ArrayList(T)) usize {...}This makes the intent much clearer, IMO. More importantly, the naming of inferred types allows us to talk about the types of generic functions with much greater precision:
// before:
eql: fn(anytype, anytype) anytype
// after:
eql: fn(infer T, T) bool
// before:
find: fn(anytype, anytype) anytype
// after:
find: fn(infer T, ArrayList(T)) usizeThis forms the bare bones of the proposal, but there are additional possibilities that could be easily layered on top of it:
// Make type name optional:
fn wrapper(x: infer _) void { other_generic_function(x, 0); }
// Unrestrict order of inferred parameters:
fn find(haystack: ArrayList(T), needle: infer T) usize {...}
// Note: T can still only be inferred once, and only at a particular location, but it
// can be referred to before that. The procedure would be to resolve all infers first,
// and then use them in a second pass to finalize the types of the remaining arguments.
// Structural pattern matching on simple types:
fn foo(bar: ?*infer T, baz: []const T) bool {...}
// However, note that structural inference across custom types is not possible
// and will probably never be possible, because type constructors in Zig can be
// arbitrarily complex.
fn convert(x: ArrayList(infer T)) HashSet(T) {...} // No can do. Use this instead:
fn convert(comptime T: type, x: ArrayList(T)) HashSet(T) {...}Peer type resolution
Another straight-forward possibility is to allow peer type resolution, as suggested by @mlugg in this comment. Peer type resolution is enabled by using an infer with the same label more than once:
fn max(x: infer T, y: infer T) T {
return if (x > y) x else y;
}This allows us to call max(@as(u8, 5), @as(u16, 3)) and get a u16 as a result. If the function were instead declared as fn max(x: infer T, y: T) T { ... }, then a call with different argument types would be an error.
Nearly the same thing could be achieved by declaring fn max(x: infer _, y: infer _) @TypeOf(x, y) { ... }, but this is less nice syntactically. It may also lead to over-instantiation in some cases: max(u8, u16), max(u16, u8) and max(u16, u16) would produce separate instances. This can be avoided if the peer type resolution happens at the argument level and is not deferred to the return type calculation.
Similar proposals
This proposal is an improved (I hope) version of something suggested by @YohananDiamond here: #5893 (comment). Towards the end of the comment, the following is proposed:
fn max(generic a: T, b: T) T {
return if (a > b) a else b;
}In the same comment it is pointed out that this makes it somewhat unclear that T is being declared here. The present proposal addresses this shortcoming and generally makes it clear what and where exactly is inferred. It also leads to a more natural representation of the type of a generic function, but is otherwise only a minor reshuffling of keywords.
Edit: There's also the proposal #6997, which provides a partial solution to the type signature imprecision problem.
Summary
Advantages over status quo:
- Preserve more type information for docgen, metaprogramming and error messages
- Reduce visual noise and unintuitive keyword naming
- Express intent more clearly
Optionally also:
- Remove constraints on order of arguments
- Allow structural pattern matching without
std.metain simple cases
It should also be mentioned that inference remains simple and fully deterministic and does not open the door to template metaprogamming or some such.
Activity
jedisct1 commentedon Jun 28, 2021
This is a nice proposal, and indeed, having to systematically use
@TypeOf()for this use case is a little bit cumbersome.There wouldn't be a clear difference between
anytypeandinfer, though. The only difference is that withinfer, the type has a name, while withanytype, it doesn't.So, I'm wondering if, instead of introducing a new keyword, we couldn't have
anytype(perhaps renamed toinferif this improves clarity) require a name, which could be_to discard it.zigazeljko commentedon Jun 28, 2021
There would be a difference. Since
infercould be used inside a more complex type, it would allow pattern matching and creating type constraints.marler8997 commentedon Jun 29, 2021
Oh it's definitely possible. All you need is a way to reverse the operation from a custom type to its input parameters. The compiler could maintain this mapping internally. Note this would only work for "custom types" though. This wouldn't work with non-custom types and would probably be mostly useless for them anyway:
It's impossible to do this in the general case, unless all your functions are bijective mappings. Whether it's desirable is another question which I would have to ponder on. Some things to think about.
SpexGuy commentedon Jun 29, 2021
This doesn't work for most actual cases though, because things like
std.ArrayListare just wrappers for more complex types likestd.ArrayListAligned. Determining whether a function likestd.ArrayListcould return a given type for some input is undecidable in the general case.marler8997 commentedon Jun 29, 2021
Yes the general case meaning all functions is undecidable, but it's very much possible for bijective functions. In the case of
std.ArrayList, it's a very simple bijective function, so this "actual case" is quite simple if you use the table I mentioned. Let's say we have anArrayList(u32). In this case, the compiler's "inverse table" would look like this:So when the compiler tries to pattern match
ArrayList(infer T), and receives an instance ofArrayListAligned(u32, null)(akaArrayList(u32)), all it needs to do is look in theArrayListtable for an output type that matchesArrayListAligned(u32, null), and assign theinfer Tto the corresponding input parameteru32.This only breaks down when we have non-bijective functions. For example:
In this case our inverse table looks like this:
So now when we try to pattern match
IgnoreTGiveMeU32(infer T)with an instance ofu32, we will find multiple entries that match the output typeu32, which means we cannot determine the input parameter and thus the problem becomes "undecidable" as you say.The concept of bijective functions is well-understood, and that is the exact criteria that would determine whether or not a function could support
infer T.ikskuh commentedon Jun 29, 2021
@ZZYXYZZ i don't think all of this is worth the benefit in the end, especially as
ArrayList(T)aliases withArrayListAligned(T, null)already and a lot of comptime functions just configure other types. Or you have functions like this:where
BitBuffer(1)andBitBuffer(8)are the same typemarler8997 commentedon Jun 29, 2021
@MasterQ32 yes your example
BitBufferis a non-bijective function so it's not reversible. We could create a bijective function that wraps it like this:This example doesn't really apply to this
infer Tproposal becauseBitBuffertakes ausizeinstead of a type, so there's no type to infer, but the same concept applies to functions that do accept types as input parameters. This mechanism of defining wrapper functions to make type functions bijective could be used to extract the input types from any type function.I thought alot about this stuff years ago when I was thinking about how D implemented pattern matching and what the challenges and potential solutions were with it. I determined it is feasible and actually not too difficult to implement and I'd be happy to help come up with a design if we want to go this route. And to re-iterate, I'm not advocating that we do implement it, just sharing exactly what a solution would look so we can make informed decisions.
windows-h8r commentedon Jun 29, 2021
On a comment on #5893, I suggested an alternative. If we add support for default parameters, and make default parameters go first, we can do something like this:
SpexGuy commentedon Jun 29, 2021
The reverse lookup table doesn't work, because the outer function may never have been called.
std.ArrayListhas never run in the above example, but the type being passed tofoois indeed a valid possible return value for it.marler8997 commentedon Jun 29, 2021
@SpexGuy Shoot you're right. I can't think of a way to get around this without having a way to generally reverse code evaluation.
zigazeljko commentedon Jun 29, 2021
There is a simpler and more powerful way that does not depend on memoization or other type constructor shenanigans.
Given a parameter declaration such as
haystack: ArrayList(infer T), the compiler expands the type constructor into the actual type, in this casehaystack: struct { items: []infer T, capacity: usize, allocator: *Allocator }. Treating that as an equation, we getconst T = @typeInfo(@TypeOf(haystack.items)).Pointer.child;.For example, the function
fn find(haystack: ArrayList(infer T), needle: T) usize {...}would behave like this:This method also allows
infer Tto be used more that once per function declaration.For example, the declaration
fn max(a: infer T, b: infer T) Twould mean this:Furthermore, this method allows using anonymous initializers for generic parameters:
53 remaining items
nektro commentedon Apr 11, 2023
I think the path to getting this potentially accepted is by reducing scope and making follow up proposals. getting only the syntax change in for
anytype->infer Twould greatly increase the ergonomics ofcomptimegeneric code and allow #5893 to be supersededekipan commentedon Apr 11, 2023
Speaking of scope, was it mentioned in this thread what was the scope of bindings introduced by
infer?nektro commentedon Apr 12, 2023
you would be able to use T in the body yes
Pyrolistical commentedon Apr 18, 2024
Instead of introducing a new keyword, can the parser gods bless us with "comptime T" instead of "infer T", or is this ambigious?
rohlem commentedon Apr 18, 2024
@Pyrolistical I feel like that would be overloading the meaning of the
comptimekeyword for no gain in readability.Everywhere else
comptimeas unary operator forces the argument expression to becomptime-evaluated.For uniformity it should do the same thing here, only that
name: typetype annotations already have to becomptime-evaluated from a language perspective, so the syntax disallows explicitly placing the operator there.I don't see an intuitive parallel from that primary usage to the semantics proposed here.
jayrod246 commentedon Aug 26, 2024
How ugly would this be? 😄
edit: Found this comment which seems to have had a similar idea.
ItsMeSamey commentedon Oct 15, 2024
Imho something like this would also be cool too
paperdev-code commentedon Oct 17, 2024
@ItsMeSamey
To expand on this and the previous comment, maybe the captured type can be used within a comptime expression which must evaluate. I think this is better than a boolean condition, because it plays well with
@compileError(...)Maybe
|Type|should implyanytypeas syntactic sugar;Because it's an expression, you could uhh
ItsMeSamey commentedon Oct 24, 2024
I actually was thinking something more like
currently you have to do something like
and the worst part is, like function coloring this problem is contagious.
Like if you had
now you'll need a
GetBartoo.leecannon commentedon Oct 24, 2024
@ItsMeSamey I don't think
anytypefields are on the table.Thinking about how that could actually be implemented, I can't think of many things less zig-like.