Skip to content

Commit

Permalink
feat: Improve code-gen safety.
Browse files Browse the repository at this point in the history
Add asserts to the *_GetName function.
  • Loading branch information
BraynStorm committed Apr 25, 2022
1 parent 0d438fe commit 90b1107
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 8 deletions.
10 changes: 9 additions & 1 deletion ccgen/generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}}")
20 changes: 15 additions & 5 deletions ccgen/parser.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from dataclasses import dataclass, field
import enum
from sys import stderr
from typing import Iterable, List

from strictyaml import YAML
Expand All @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion ccgen/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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",
]
Expand Down
7 changes: 7 additions & 0 deletions test/test_01.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
enums:
Test0:
- Head

Test1:
items:
- Head

ItemType:
attributes:
- bits
Expand Down

0 comments on commit 90b1107

Please sign in to comment.