View System over same data

View


Some years ago I started building a compiler, the AST was formed by a generic Node with a tag and fields with indexes pointing at the next nodes, this fields were used in different ways depending on the tag, so I had to remember which tag is expected, which fields are used and the expected type.
The other problem I had was that each function that needed a Node did not specify which tag and if i wanted to check the tags are the expected ones, it was with a horrible assert.
I tried fixing it in there with an as for each possible type and no generics with a manual assert check, with this I managed to get naming for each field and what type should each function expects, But this did not solve the whole problem each field just had an index so I didn’t know what the field expects and each new variant has a big manual overhead.

I had some other problem aside that so I decided to make a new version of the compiler, I designed with the help of AI for iteration the so called view system here (it was refactored via AI because it is not pretty how nested it is).
The usage is the build time function and a comform function that check at comptime the variants for tags and common decl, common indicate that the possible child should have the same offset for those fields and the tags indicate in what tags can the node exist. In the base Node there is commonFields and Decl for all the variants.
This allows you to with less manual overhead adding each variant of the Node with check that inidicates everything is okey you just need tags and common. This unlike an union enum which only allows leaf, here there could be Nodes in the middle example: Node → Expression → [Binop, Unaryop, Call, etc] (Having methods).
With the help of Link wrapping an index to the array it allows to indicate what type each field expects and with Fat which wraps a Node and the storage for easier navigation, each of this have an as function which checks if the tags of each type are a subset and assert it, this is not done in Link because it does not have the node, but when it is access by get does it there.
There are some useful function like exact which allows you to grab a Node Variant and it allows you to have a switch will only the tags it could be, and not the ones there should (wrapping it in a union enum).
This build time function which create a variant file which imports all of them and then does the unwrapping and it grabs all function which have anytype and add it to each variant for method access of it.

The USAGE example are in Parser and BackEnd

I have some questions:

  • am I abusing comptime for the conform function?
  • What is the cost at runtime of this?

Supported Zig versions

In the codeberge version, it should be master.
The github one I have no idea.

AI / LLM usage disclosure

The compiler is being done with AI, and the README is quiet old