diff --git a/ccgen/generation.py b/ccgen/generation.py index 315bca1..c830846 100644 --- a/ccgen/generation.py +++ b/ccgen/generation.py @@ -27,6 +27,14 @@ def generate_enum(self, enum: Enum): for name, value in enum.items.items(): arr += f' "{name}",\n' arr += "};\n" + + maximum = max(enum.items.values()) + minimum = min(enum.items.values()) + self.header.append(f"{decl};") self.source.append(arr) - self.source.append(f"{decl}\n{{\n return {array_name}[e];\n}}") + self.source.append(f"{decl}\n{{") + self.source.append(f" int index = e - {minimum};") + self.source.append(f" assert(e >= {minimum} && e <= {maximum});") + self.source.append(f" return {array_name}[index];") + self.source.append(f"}}") diff --git a/ccgen/parser.py b/ccgen/parser.py index 16aaa80..2082ef6 100644 --- a/ccgen/parser.py +++ b/ccgen/parser.py @@ -1,4 +1,6 @@ from dataclasses import dataclass, field +import enum +from sys import stderr from typing import Iterable, List from strictyaml import YAML @@ -18,12 +20,20 @@ def visit_enums(self, node: YAML): e = Enum(str(enum_name), {}) self.enums.append(e) - attributes = self.visit_attributes(enum_def["attributes"]) - for attr in attributes: - f = getattr(self, f"process_enum_attribute_{attr}") - f(e) + if 'attributes' in enum_def: + attributes = self.visit_attributes(enum_def["attributes"]) + for attr in attributes: + f = getattr(self, f"process_enum_attribute_{attr}") + f(e) - items = self.visit_items(enum_def["items"], e) + if enum_def.is_sequence(): + yaml_items = enum_def + elif 'items' in enum_def: + yaml_items = enum_def["items"] + else: + print("Enums without items/values are not permitted.") + + items = self.visit_items(yaml_items, e) e.items = items def process_enum_attribute_bits(self, enum: Enum): diff --git a/ccgen/types.py b/ccgen/types.py index 88b90c5..3c69f39 100644 --- a/ccgen/types.py +++ b/ccgen/types.py @@ -8,7 +8,7 @@ @dataclass class Enum: name: str - items: Dict[str, Optional[int]] = field(default_factory=dict) + items: Dict[str, int] = field(default_factory=dict) is_bits: bool = False is_stringable: bool = False diff --git a/pyproject.toml b/pyproject.toml index 2dd50c2..5b0600d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "ccgen" description = "Simple C code generator for enums." -version = "0.1.2" +version = "0.1.3" classifiers = [ "License :: OSI Approved :: MIT License", ] diff --git a/test/test_01.yml b/test/test_01.yml index f7e1f99..60a3462 100644 --- a/test/test_01.yml +++ b/test/test_01.yml @@ -1,4 +1,11 @@ enums: + Test0: + - Head + + Test1: + items: + - Head + ItemType: attributes: - bits