Zig NEWS

Discussion on: Crafting an Interpreter in Zig - part 4

Collapse
 
storyfeet profile image
storyfeet

Thanks to this series, I was inspired to follow in your footsteps and try this myself.

I've just come to the part where we make the table of rules in the compiler :

ParseRule rules[] = {
  [TOKEN_LEFT_PAREN]    = {grouping, NULL,   PREC_NONE},
  [TOKEN_RIGHT_PAREN]   = {NULL,     NULL,   PREC_NONE},
  // ...
}
Enter fullscreen mode Exit fullscreen mode

When I realized the enums were the location in the array, my head just went ouch, as I while I can see this is fast it's so precarious if you get your array locations wrong somehow.

I couldn't work out how to do this in zig, I considered a comptime hashmap, or just a function. Took a sneak peek at your solution, I think it's a good choice, "just follow the switch"

Collapse
 
andres profile image
Andres

One of the things I've enjoyed the most about Zig is the switch expression/statement. it has a very modern syntax as well as compose really good with other constructs on the language like try, return, etc

Collapse
 
apatriarca profile image
Antonio Patriarca

I got the impression the book author is sometimes trying to show some C feature instead of taking the easier route. Even in C a switch would have been easier to write and understand IMHO. Each row has in fact only a few entries that are different from the default.

It is possible to obtain something similar in Zig as well anyway. You create an array big enough to contain all the tokens and you then initialize it at compile time with those values.