The new anonymous enum literals are great, but they don't to seem work with arrays. I assume that this is a bug.
Let's take this enum as an example:
const MyEnum = enum {Ok, Error};
Declaring a single variable works just fine:
var enum_instance: MyEnum = .Ok;
But an array of MyEnum does not:
var enum_instances: []MyEnum = {.Error};
Which leads to the following compiler output:
error: expected token '=', found '}'
I'd expect that to work too. Enum literals seem to be missing from the grammar - are they supposed to be included? That might make this easier to address.
Enum literals aren't finished because they are missing from the grammar and documentation: #683
This is invalid syntax:
var enum_instances: []MyEnum = {.Error};
Correct syntax would be:
test "aoeu" {
var enum_instances = [1]@typeOf(.x){.Error};
}
Which would give a compile error of error: variable of type '(enum literal)' must be const or comptime, which you could fix with using const instead of var.
However there is a grammar issue here, which is that {.Error is getting parsed as the beginning of a struct literal rather than an array literal with an enum literal in it.
Related: #208
cc @Hejsil I think you might have an opinion on how to resolve this.
my proposal:
T{ is always the start of a struct initializer.@thejoshwolfe I'm assuming by "anonymous array literals" you mean array initializers without the type prefix, right? Like this:
const arr: []u8 = {4, 2};
That would be really nice to have when the type can be inferred by the compiler, since you wouldn't have to specify it manually then. This actually sounds like a great solution to me.
Off topic: Is there an existing issue about anonymous array literals? I couldn't find any.
@thejoshwolfe might be a good idea, but i haven't thought much about this. I'm out travelling and will have time to look more into this in a weeks time.
I'm accepting https://github.com/ziglang/zig/issues/2235#issuecomment-481941256
@andrewrk well, if we are gonna have inferred struct initializes as well, then this is not gonna work. Related #208.
@andrewrk well, if we are gonna have inferred struct initializes as well, then this is not gonna work. Related #208.
A better link might be https://github.com/ziglang/zig/issues/685#issuecomment-481806770
If we add enum literals with this patch:
--- a/grammar/grammar.y
+++ b/grammar/grammar.y
@@ -121,6 +121,7 @@ PrimaryTypeExpr
<- BUILTINIDENTIFIER FnCallArguments
/ CHAR_LITERAL
/ ContainerDecl
+ / DOT IDENTIFIER
/ ErrorSetDecl
/ FLOAT
/ FnProto
then the peg parser parses []Enum {.Tag} succesfully as an array literal. So this is not a grammar problem, and just an implementation problem with the stage 1 parser. This is therefor a bug.
No ambiguity. This was just a bug in the implementation of the parser. You probably want to implement this in your stage 2 parser PR @hryx :)
'Tis now done
Most helpful comment
my proposal:
T{is always the start of a struct initializer.