From 844a906d6276441bcc9cad9e50c4b60e30b81462 Mon Sep 17 00:00:00 2001 From: Slendi Date: Mon, 29 Apr 2024 17:01:53 +0300 Subject: [PATCH] Resolve enum values This patch makes it so that the compiler can automatically increment/decrement values in order for enums while parsing. Signed-off-by: Slendi --- src/parser.odin | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/parser.odin b/src/parser.odin index 8f7f059..e46b271 100644 --- a/src/parser.odin +++ b/src/parser.odin @@ -159,6 +159,41 @@ parser_parse_struct_definition :: proc(parser: ^Parser) -> ^Node { return n } +@(private = "file") +enum_resolve_value_items :: proc(values: ^[dynamic]EnumValueItem) { + // IMPORTANT: Although this should be obvious, THIS DOES NOT DO ANY TYPE + // CHECKING! The `type_check` procedure is for that! + + // What this algorithm basically does is find the first resolved item, then + // it resolved backwards, afterwards, it goes and resolves stuff forwards. + // This resolves everything as signed integers which may be an issue but i + // frankly don't care, if you have an enum which has more 2^63 negative + // values that's on you. + + // 1. Find the first element that is resolved, default to the beginning if + // none is found + idx_first_resolved := 0 + for &value, idx in values { + if value.resolved { + idx_first_resolved = idx + } + } + + // 2. Resolve backwards from first resolved element + for i := idx_first_resolved; i >= 1; i -= 1 { + values[i - 1].value = values[i].value - 1 + values[i].resolved = true + values[i - 1].resolved = true + } + + // 3. Resolve forwards until the end of the values vector + for i in idx_first_resolved ..< len(values) - 1 { + values[i + 1].value = values[i].value + 1 + values[i].resolved = true + values[i + 1].resolved = true + } +} + @(private = "file") parser_parse_enum_definition :: proc(parser: ^Parser) -> ^Node { range := parser.tok.range @@ -238,7 +273,7 @@ parser_parse_enum_definition :: proc(parser: ^Parser) -> ^Node { range.range.end = parser.tok.range.range.end parser_next(parser) - // FIXME: Resolve items + enum_resolve_value_items(&enum_value.values) enum_value.type = type_node