Skip to content

Commit 7149384

Browse files
committed
add support for char constants
1 parent 14f0e93 commit 7149384

File tree

4 files changed

+23
-0
lines changed

4 files changed

+23
-0
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ Different enum styles are supported in struct/union definitions.
129129
enum Type_A a; // externally defined using CEnum
130130
enum Type_B {A, B, C} b;
131131
enum {A, B, C} c;
132+
enum Type_D : short {A, B, C} d; // specify the underlying type
133+
enum Direction { left = 'l', right = 'r' };
132134
```
133135
134136
### Nested structs/unions
@@ -334,3 +336,6 @@ Output example:
334336
000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 aa |..............U.|
335337
```
336338

339+
Links
340+
-----
341+
* [C/C++ reference](https://en.cppreference.com/)

cstruct/c_expr.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ def c_eval(expr: str) -> Union[int, float]:
5858
try:
5959
expr = expr.replace("!", " not ").replace("&&", " and ").replace("||", " or ")
6060
return eval_node(ast.parse(expr.strip()).body[0])
61+
except EvalError:
62+
raise
6163
except Exception:
6264
raise EvalError
6365

@@ -67,6 +69,11 @@ def eval_node(node: ast.stmt) -> Union[int, float]:
6769
result = handler(node)
6870
if isinstance(result, bool): # convert bool to int
6971
return 1 if result else 0
72+
elif isinstance(result, str): # convert char to int
73+
if len(result) != 1:
74+
raise EvalError("Multi-character constant")
75+
else:
76+
return ord(result)
7077
return result
7178

7279

tests/test_c_expr.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,8 @@ def test_c_expr_compare():
7878
assert c_eval("3 <= 30") == 1
7979
define("A10", 10)
8080
assert c_eval("((A10 < 6) || (A10>10))") == 0
81+
82+
83+
def test_c_expr_char():
84+
assert c_eval("'A'") == 65
85+
assert c_eval("'B'") == 66

tests/test_cenum.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,9 @@ def test_type():
104104
color = cstruct.parse("enum Color : unsigned short { red, green, blue };")
105105
assert color.__size__ == 2
106106
assert cstruct.sizeof("enum Color") == 2
107+
108+
109+
def test_char():
110+
direction = cstruct.parse("enum Direction { left = 'l', right = 'r' };")
111+
assert direction.__size__ == 4
112+
assert cstruct.sizeof("enum Direction") == 4

0 commit comments

Comments
 (0)