Skip to content

Commit 5bcc02a

Browse files
committed
add parser_struct_fields
1 parent fe91a17 commit 5bcc02a

1 file changed

Lines changed: 38 additions & 6 deletions

File tree

pythonbpf/structs_pass.py

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
11
import ast
2+
import logging
23
from llvmlite import ir
34
from .type_deducer import ctypes_to_ir
45

5-
6-
def is_bpf_struct(cls_node):
7-
return any(
8-
isinstance(decorator, ast.Name) and decorator.id == "struct"
9-
for decorator in cls_node.decorator_list
10-
)
6+
logger = logging.getLogger(__name__)
117

128

139
def structs_proc(tree, module, chunks):
@@ -21,6 +17,13 @@ def structs_proc(tree, module, chunks):
2117
return structs_sym_tab
2218

2319

20+
def is_bpf_struct(cls_node):
21+
return any(
22+
isinstance(decorator, ast.Name) and decorator.id == "struct"
23+
for decorator in cls_node.decorator_list
24+
)
25+
26+
2427
def process_bpf_struct(cls_node, module):
2528
""" Process a single BPF struct definition """
2629

@@ -80,3 +83,32 @@ def process_bpf_struct(cls_node, module):
8083
"field_types": field_types,
8184
}
8285
print(f"Created struct {cls_node.name} with fields {field_names}")
86+
87+
88+
def parse_struct_fields(cls_node):
89+
""" Parse fields of a struct class node """
90+
field_names = []
91+
field_types = []
92+
93+
for item in cls_node.body:
94+
if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name):
95+
field_names.append(item.target.id)
96+
field_types.append(get_type_from_ann(item.annotation))
97+
else:
98+
logger.error(f"Unsupported struct field: {ast.dump(item)}")
99+
raise TypeError(f"Unsupported field in {ast.dump(cls_node)}")
100+
return field_names, field_types
101+
102+
103+
def get_type_from_ann(annotation):
104+
""" Convert an AST annotation node to an LLVM IR type for struct fields"""
105+
if isinstance(annotation, ast.Call) and \
106+
isinstance(annotation.func, ast.Name):
107+
if annotation.func.id == "str":
108+
# Assumes constant integer argument
109+
length = annotation.args[0].value
110+
return ir.ArrayType(ir.IntType(8), length)
111+
elif isinstance(annotation, ast.Name):
112+
return ctypes_to_ir(annotation.id)
113+
114+
raise TypeError(f"Unsupported annotation type: {ast.dump(annotation)}")

0 commit comments

Comments
 (0)