| 1 |
import argparse |
| 2 |
import itertools |
| 3 |
import json |
| 4 |
import os |
| 5 |
import re |
| 6 |
import sys |
| 7 |
|
| 8 |
from typing import Any, Dict, List, Set, Tuple, Union |
| 9 |
|
| 10 |
|
| 11 |
class ParseError(Exception): |
| 12 |
def __init__(self, error): |
| 13 |
super().__init__(error) |
| 14 |
|
| 15 |
|
| 16 |
indent_size = 4 |
| 17 |
|
| 18 |
|
| 19 |
class ASTNode: |
| 20 |
def __init__(self, function_suffix: str, types: List[str], consume_types: Union[List[str], None] = None): |
| 21 |
self.function_suffix = function_suffix |
| 22 |
self.types = types |
| 23 |
self.consume_types = consume_types |
| 24 |
self.count_args = len(self.types) |
| 25 |
self.count_consume_args = len(self.consume_types) if self.consume_types else len(self.types) |
| 26 |
|
| 27 |
@staticmethod |
| 28 |
def mk_indent(indent: int): |
| 29 |
return " "*indent*indent_size |
| 30 |
|
| 31 |
@staticmethod |
| 32 |
def mk_funcall(name: str, args: List[str]): |
| 33 |
return f'{name}({", ".join(args)})' |
| 34 |
|
| 35 |
def gen_emit_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 36 |
return [f'{self.mk_indent(indent)}{self.mk_funcall("emit_"+self.function_suffix, prefix + self.gen_args(first_arg))};'] |
| 37 |
|
| 38 |
def gen_params(self, first_arg: int) -> List[Tuple[str, str]]: |
| 39 |
return [(f'arg{i+first_arg}', self.types[i]) for i in range(len(self.types))] |
| 40 |
|
| 41 |
def gen_args(self, first_arg: int) -> List[str]: |
| 42 |
return [f'arg{i+first_arg}' for i in range(len(self.types))] |
| 43 |
|
| 44 |
def gen_consume_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 45 |
return [f'{self.mk_indent(indent)}{self.mk_funcall("consume_"+self.function_suffix, prefix + self.gen_consume_args(first_arg))};'] |
| 46 |
|
| 47 |
@staticmethod |
| 48 |
def add_pointer(type: str) -> str: |
| 49 |
return f'{type}*' |
| 50 |
|
| 51 |
def gen_consume_params(self, first_arg: int) -> List[Tuple[str, str]]: |
| 52 |
if self.consume_types: |
| 53 |
return [(f'arg{i + first_arg}', self.consume_types[i]) for i in range(len(self.consume_types))] |
| 54 |
else: |
| 55 |
return [(f'arg{i + first_arg}', self.add_pointer(self.types[i])) for i in range(len(self.types))] |
| 56 |
|
| 57 |
def gen_consume_args(self, first_arg: int) -> List[str]: |
| 58 |
if self.consume_types: |
| 59 |
return [f'arg{i+first_arg}' for i in range(len(self.consume_types))] |
| 60 |
else: |
| 61 |
return [f'arg{i+first_arg}' for i in range(len(self.types))] |
| 62 |
|
| 63 |
def __repr__(self) -> str: |
| 64 |
return f'<{self.function_suffix}: {self.types}>' |
| 65 |
|
| 66 |
|
| 67 |
class NullNode(ASTNode): |
| 68 |
def __init__(self, function_suffix: str): |
| 69 |
super().__init__(function_suffix, []) |
| 70 |
|
| 71 |
def gen_emit_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 72 |
return [f'{self.mk_indent(indent)}{self.mk_funcall("emit_"+self.function_suffix, prefix)};'] |
| 73 |
|
| 74 |
def gen_params(self, first_arg: int) -> List[Tuple[str, str]]: |
| 75 |
return [] |
| 76 |
|
| 77 |
|
| 78 |
class ListNode(ASTNode): |
| 79 |
def __init__(self, name: str, l: List[ASTNode], types: List[str]): |
| 80 |
self.list: List[ASTNode] = l |
| 81 |
super().__init__(name, types) |
| 82 |
self.count_args += sum([i.count_args for i in l]) |
| 83 |
self.count_consume_args += sum([i.count_consume_args for i in l]) |
| 84 |
|
| 85 |
def gen_params_list(self, first_arg: int) -> List[Tuple[str, str]]: |
| 86 |
params = [] |
| 87 |
arg = first_arg |
| 88 |
for n in self.list: |
| 89 |
r = n.gen_params(arg) |
| 90 |
arg += len(r) |
| 91 |
params.append(r) |
| 92 |
return [i for i in itertools.chain(*params)] |
| 93 |
|
| 94 |
def gen_params(self, first_arg: int) -> List[Tuple[str, str]]: |
| 95 |
args = super().gen_params(first_arg) |
| 96 |
return [ |
| 97 |
*args, |
| 98 |
*self.gen_params_list(first_arg + len(args)) |
| 99 |
] |
| 100 |
|
| 101 |
def gen_consume_params_list(self, first_arg: int) -> List[Tuple[str, str]]: |
| 102 |
params = [] |
| 103 |
arg = first_arg |
| 104 |
for n in self.list: |
| 105 |
r = n.gen_consume_params(arg) |
| 106 |
arg += len(r) |
| 107 |
params.append(r) |
| 108 |
return [i for i in itertools.chain(*params)] |
| 109 |
|
| 110 |
def gen_consume_params(self, first_arg: int) -> List[Tuple[str, str]]: |
| 111 |
args = super().gen_consume_params(first_arg) |
| 112 |
return [ |
| 113 |
*args, |
| 114 |
*self.gen_consume_params_list(first_arg + len(args)) |
| 115 |
] |
| 116 |
|
| 117 |
def gen_emit_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 118 |
lines = [] |
| 119 |
arg = first_arg |
| 120 |
for n in self.list: |
| 121 |
lines.append(n.gen_emit_code(prefix, arg, indent)) |
| 122 |
arg += n.count_args |
| 123 |
return [i for i in itertools.chain(*lines)] |
| 124 |
|
| 125 |
def gen_consume_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 126 |
lines = [] |
| 127 |
arg = first_arg |
| 128 |
for n in self.list: |
| 129 |
lines.append(n.gen_consume_code(prefix, arg, indent+1)) |
| 130 |
arg += n.count_consume_args |
| 131 |
return [ |
| 132 |
f'{self.mk_indent(indent)}{{', |
| 133 |
f'{self.mk_indent(indent+1)}pni_consumer_t subconsumer;', |
| 134 |
f'{self.mk_indent(indent+1)}uint32_t count;', |
| 135 |
f'{self.mk_indent(indent+1)}{self.mk_funcall("consume_list", prefix+["&subconsumer", "&count"])};', |
| 136 |
f'{self.mk_indent(indent+1)}pni_consumer_t consumer = subconsumer;', |
| 137 |
*[i for i in itertools.chain(*lines)], |
| 138 |
f'{self.mk_indent(indent+1)}{self.mk_funcall("consume_end_list", prefix)};', |
| 139 |
f'{self.mk_indent(indent)}}}' |
| 140 |
] |
| 141 |
|
| 142 |
def __repr__(self) -> str: |
| 143 |
nl = "\n " |
| 144 |
return f'''<{self.function_suffix}: {self.types} |
| 145 |
{nl.join([repr(x) for x in self.list])} |
| 146 |
>''' |
| 147 |
|
| 148 |
|
| 149 |
class DescListNode(ListNode): |
| 150 |
def __init__(self, l: List[ASTNode]): |
| 151 |
super().__init__('described_list', l, ['uint64_t']) |
| 152 |
|
| 153 |
def gen_emit_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 154 |
args = self.gen_args(first_arg) |
| 155 |
return [ |
| 156 |
f'{self.mk_indent(indent)}emit_descriptor({", ".join(prefix+args)});', |
| 157 |
f'{self.mk_indent(indent)}for (bool small_encoding = true; ; small_encoding = false) {{', |
| 158 |
f'{self.mk_indent(indent+1)}pni_compound_context c = ' |
| 159 |
f'{self.mk_funcall("emit_list", prefix+["small_encoding", "true"])};', |
| 160 |
f'{self.mk_indent(indent+1)}pni_compound_context compound = c;', |
| 161 |
*super().gen_emit_code(prefix, first_arg+len(args), indent + 1), |
| 162 |
f'{self.mk_indent(indent+1)}{self.mk_funcall("emit_end_list", prefix+["small_encoding"])};', |
| 163 |
f'{self.mk_indent(indent+1)}if (encode_succeeded({", ".join(prefix)})) break;', |
| 164 |
f'{self.mk_indent(indent)}}}', |
| 165 |
] |
| 166 |
|
| 167 |
|
| 168 |
class DescListIgnoreTypeNode(ListNode): |
| 169 |
def __init__(self, l: List[ASTNode]): |
| 170 |
super().__init__('described_unknown_list', l, []) |
| 171 |
|
| 172 |
def gen_consume_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 173 |
return [ |
| 174 |
f'{self.mk_indent(indent)}{{', |
| 175 |
f'{self.mk_indent(indent+1)}pni_consumer_t subconsumer;', |
| 176 |
f'{self.mk_indent(indent+1)}{self.mk_funcall("consume_described", prefix+["&subconsumer"])};', |
| 177 |
f'{self.mk_indent(indent+1)}pni_consumer_t consumer = subconsumer;', |
| 178 |
*super().gen_consume_code(prefix, first_arg, indent + 1), |
| 179 |
f'{self.mk_indent(indent)}}}', |
| 180 |
] |
| 181 |
|
| 182 |
|
| 183 |
class ArrayNode(ListNode): |
| 184 |
def __init__(self, l: List[ASTNode]): |
| 185 |
self.list: List[ASTNode] = l |
| 186 |
super().__init__('array', l, ['pn_type_t']) |
| 187 |
|
| 188 |
def gen_emit_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 189 |
args = self.gen_args(first_arg) |
| 190 |
return [ |
| 191 |
f'{self.mk_indent(indent)}for (bool small_encoding = true; ; small_encoding = false) {{', |
| 192 |
f'{self.mk_indent(indent+1)}pni_compound_context c = ' |
| 193 |
f'{self.mk_funcall("emit_array", prefix+["small_encoding"]+args)};', |
| 194 |
f'{self.mk_indent(indent+1)}pni_compound_context compound = c;', |
| 195 |
*super().gen_emit_code(prefix, first_arg+len(args), indent + 1), |
| 196 |
f'{self.mk_indent(indent+1)}{self.mk_funcall("emit_end_array", prefix+["small_encoding"])};', |
| 197 |
f'{self.mk_indent(indent+1)}if (encode_succeeded({", ".join(prefix)})) break;', |
| 198 |
f'{self.mk_indent(indent)}}}', |
| 199 |
] |
| 200 |
|
| 201 |
|
| 202 |
class OptionNode(ASTNode): |
| 203 |
def __init__(self, i: ASTNode): |
| 204 |
self.option: ASTNode = i |
| 205 |
super().__init__('option', ['bool']) |
| 206 |
self.count_args += i.count_args |
| 207 |
self.count_consume_args += i.count_consume_args |
| 208 |
|
| 209 |
def gen_emit_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 210 |
arg = f'arg{first_arg}' |
| 211 |
return [ |
| 212 |
f'{self.mk_indent(indent)}if ({arg}) {{', |
| 213 |
*self.option.gen_emit_code(prefix, first_arg+1, indent + 1), |
| 214 |
f'{self.mk_indent(indent)}}} else {{', |
| 215 |
*NullNode("null").gen_emit_code(prefix, 0, indent + 1), |
| 216 |
f'{self.mk_indent(indent)}}}' |
| 217 |
] |
| 218 |
|
| 219 |
def gen_params(self, first_arg: int) -> List[Tuple[str, str]]: |
| 220 |
args = super().gen_params(first_arg) |
| 221 |
return [ |
| 222 |
*args, |
| 223 |
*self.option.gen_params(first_arg + len(args)) |
| 224 |
] |
| 225 |
|
| 226 |
def gen_consume_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 227 |
arg = f'arg{first_arg}' |
| 228 |
return [ |
| 229 |
f'{self.mk_indent(indent)}*{arg} = {self.option.gen_consume_code(prefix, first_arg+1, 0)[0]};' |
| 230 |
] |
| 231 |
|
| 232 |
def gen_consume_params(self, first_arg: int) -> List[Tuple[str, str]]: |
| 233 |
args = super().gen_consume_params(first_arg) |
| 234 |
return [ |
| 235 |
*args, |
| 236 |
*self.option.gen_consume_params(first_arg + len(args)) |
| 237 |
] |
| 238 |
|
| 239 |
|
| 240 |
class EmptyNode(ASTNode): |
| 241 |
def __init__(self): |
| 242 |
super().__init__('empty_frame', []) |
| 243 |
|
| 244 |
def gen_emit_code(self, prefix: List[str], first_arg: int, indent: int) -> List[str]: |
| 245 |
return [] |
| 246 |
|
| 247 |
def gen_params(self, first_arg: int) -> List[Tuple[str, str]]: |
| 248 |
return [] |
| 249 |
|
| 250 |
|
| 251 |
def expect_char(format: str, char: str) -> Tuple[bool, str]: |
| 252 |
return format[0] == char, format[1:] |
| 253 |
|
| 254 |
|
| 255 |
def parse_list(format: str) -> Tuple[List[ASTNode], str]: |
| 256 |
rest = format |
| 257 |
list = [] |
| 258 |
while not rest[0] == ']': |
| 259 |
i, rest, = parse_item(rest) |
| 260 |
list.append(i) |
| 261 |
return list, rest |
| 262 |
|
| 263 |
|
| 264 |
def parse_item(format: str) -> Tuple[ASTNode, str]: |
| 265 |
if len(format) == 0: |
| 266 |
return EmptyNode(), '' |
| 267 |
if format.startswith('DL['): |
| 268 |
l, rest = parse_list(format[3:]) |
| 269 |
b, rest = expect_char(rest, ']') |
| 270 |
if not b: |
| 271 |
raise ParseError(format) |
| 272 |
return DescListNode(l), rest |
| 273 |
elif format.startswith('D.['): |
| 274 |
l, rest = parse_list(format[3:]) |
| 275 |
b, rest = expect_char(rest, ']') |
| 276 |
if not b: |
| 277 |
raise ParseError(format) |
| 278 |
return DescListIgnoreTypeNode(l), rest |
| 279 |
elif format.startswith('D?LR'): |
| 280 |
return ASTNode('described_maybe_type_raw', ['bool', 'uint64_t', 'pn_bytes_t'], consume_types=['bool*', 'uint64_t*', 'pn_bytes_t*']), format[4:] |
| 281 |
elif format.startswith('D?L?.'): |
| 282 |
return ASTNode('described_maybe_type_maybe_anything', ['bool', 'uint64_t', 'bool'], consume_types=['bool*', 'uint64_t*', 'bool*']), format[4:] |
| 283 |
elif format.startswith('DLC'): |
| 284 |
return ASTNode('described_type_copy', ['uint64_t', 'pn_data_t*'], consume_types=['uint64_t*', 'pn_data_t*']), format[3:] |
| 285 |
elif format.startswith('DL.'): |
| 286 |
return ASTNode('described_type_anything', ['uint64_t']), format[3:] |
| 287 |
elif format.startswith('D?L.'): |
| 288 |
return ASTNode('described_maybe_type_anything', ['bool', 'uint64_t']), format[3:] |
| 289 |
elif format.startswith('D..'): |
| 290 |
return NullNode('described_anything'), format[3:] |
| 291 |
elif format.startswith('D.C'): |
| 292 |
return ASTNode('described_copy', ['pn_data_t*'], consume_types=['pn_data_t*']), format[3:] |
| 293 |
elif format.startswith('@T['): |
| 294 |
l, rest = parse_list(format[3:]) |
| 295 |
b, rest = expect_char(rest, ']') |
| 296 |
if not b: |
| 297 |
raise ParseError(format) |
| 298 |
return ArrayNode(l), rest |
| 299 |
elif format.startswith('?'): |
| 300 |
i, rest = parse_item(format[1:]) |
| 301 |
return OptionNode(i), rest |
| 302 |
elif format.startswith('*s'): |
| 303 |
return ASTNode('counted_symbols', ['size_t', 'char**']), format[2:] |
| 304 |
elif format.startswith('.'): |
| 305 |
return NullNode('anything'), format[1:] |
| 306 |
elif format.startswith('s'): |
| 307 |
return ASTNode('symbol', ['const char*'], consume_types=['pn_bytes_t*']), format[1:] |
| 308 |
elif format.startswith('S'): |
| 309 |
return ASTNode('string', ['const char*'], consume_types=['pn_bytes_t*']), format[1:] |
| 310 |
elif format.startswith('C'): |
| 311 |
return ASTNode('copy', ['pn_data_t*'], consume_types=['pn_data_t*']), format[1:] |
| 312 |
elif format.startswith('I'): |
| 313 |
return ASTNode('uint', ['uint32_t']), format[1:] |
| 314 |
elif format.startswith('H'): |
| 315 |
return ASTNode('ushort', ['uint16_t']), format[1:] |
| 316 |
elif format.startswith('n'): |
| 317 |
return NullNode('null'), format[1:] |
| 318 |
elif format.startswith('R'): |
| 319 |
return ASTNode('raw', ['pn_bytes_t'], consume_types=['pn_bytes_t*']), format[1:] |
| 320 |
elif format.startswith('a'): |
| 321 |
return ASTNode('atom', ['pn_atom_t*'], consume_types=['pn_atom_t*']), format[1:] |
| 322 |
elif format.startswith('M'): |
| 323 |
return ASTNode('multiple', ['pn_data_t*']), format[1:] |
| 324 |
elif format.startswith('o'): |
| 325 |
return ASTNode('bool', ['bool']), format[1:] |
| 326 |
elif format.startswith('B'): |
| 327 |
return ASTNode('ubyte', ['uint8_t']), format[1:] |
| 328 |
elif format.startswith('L'): |
| 329 |
return ASTNode('ulong', ['uint64_t']), format[1:] |
| 330 |
elif format.startswith('t'): |
| 331 |
return ASTNode('timestamp', ['pn_timestamp_t']), format[1:] |
| 332 |
elif format.startswith('z'): |
| 333 |
return ASTNode('binaryornull', ['size_t', 'const char*'], consume_types=['pn_bytes_t*']), format[1:] |
| 334 |
elif format.startswith('Z'): |
| 335 |
return ASTNode('binarynonull', ['size_t', 'const char*'], consume_types=['pn_bytes_t*']), format[1:] |
| 336 |
else: |
| 337 |
raise ParseError(format) |
| 338 |
|
| 339 |
|
| 340 |
# Need to translate '@[]*?.' to legal identifier characters |
| 341 |
# These will be fairly arbitrary and just need to avoid already used codes |
| 342 |
def make_legal_identifier(s: str) -> str: |
| 343 |
subs = {'@': 'A', '[': 'E', ']': 'e', '{': 'F', '}': 'f', '*': 'j', '.': 'q', '?': 'Q'} |
| 344 |
r = '' |
| 345 |
for c in s: |
| 346 |
if c in subs: |
| 347 |
r += subs[c] |
| 348 |
else: |
| 349 |
r += c |
| 350 |
return r |
| 351 |
|
| 352 |
|
| 353 |
def consume_function(name_prefix: str, scan_spec: str, prefix_args: List[Tuple[str, str]]) -> Tuple[str, List[str]]: |
| 354 |
p, _ = parse_item(scan_spec) |
| 355 |
params = p.gen_consume_params(0) |
| 356 |
function_name = name_prefix + '_' + make_legal_identifier(scan_spec) |
| 357 |
param_list = ', '.join([t+' '+arg for arg, t in prefix_args+params]) |
| 358 |
function_spec = f'size_t {function_name}({param_list})' |
| 359 |
|
| 360 |
function_decl = f'{function_spec};' |
| 361 |
|
| 362 |
prefix_params = [a for (a, _) in prefix_args] |
| 363 |
function_defn = [ |
| 364 |
f'{function_spec}', |
| 365 |
'{', |
| 366 |
f'{p.mk_indent(1)}pni_consumer_t consumer = make_consumer_from_bytes({", ".join(prefix_params)});', |
| 367 |
*p.gen_consume_code(['&consumer'], 0, 1), |
| 368 |
f'{p.mk_indent(1)}return consumer.position;', |
| 369 |
'}', |
| 370 |
'' |
| 371 |
] |
| 372 |
return function_decl, function_defn |
| 373 |
|
| 374 |
|
| 375 |
def emit_function(name_prefix: str, fill_spec: str, prefix_args: List[Tuple[str, str]]) -> Tuple[str, List[str]]: |
| 376 |
p, _ = parse_item(fill_spec) |
| 377 |
params = p.gen_params(0) |
| 378 |
function_name = name_prefix + '_' + make_legal_identifier(fill_spec) |
| 379 |
param_list = ', '.join([t+' '+arg for arg, t in prefix_args+params]) |
| 380 |
function_spec = f'pn_bytes_t {function_name}({param_list})' |
| 381 |
|
| 382 |
bytes_args = [('bytes', 'char*'), ('size', 'size_t')] |
| 383 |
bytes_function_name = name_prefix + '_bytes_' + make_legal_identifier(fill_spec) |
| 384 |
bytes_param_list = ', '.join([t+' '+arg for arg, t in bytes_args+params]) |
| 385 |
bytes_function_spec = f'size_t {bytes_function_name}({bytes_param_list})' |
| 386 |
|
| 387 |
inner_function_name = name_prefix + '_inner_' + make_legal_identifier(fill_spec) |
| 388 |
inner_param_list = [('emitter', 'pni_emitter_t*')]+params |
| 389 |
inner_params = ', '.join([t+' '+arg for arg, t in inner_param_list]) |
| 390 |
inner_function_spec = f'bool {inner_function_name}({inner_params})' |
| 391 |
|
| 392 |
function_decl = f'{function_spec};\n{bytes_function_spec};' |
| 393 |
|
| 394 |
prefix_params = [a for (a, _) in prefix_args] |
| 395 |
args = [a for (a, _) in params] |
| 396 |
if type(p) is EmptyNode: |
| 397 |
function_defn = [ |
| 398 |
f'{function_spec}', |
| 399 |
'{', |
| 400 |
f'{p.mk_indent(1)}pni_emitter_t emitter = make_emitter({", ".join(prefix_params)});', |
| 401 |
f'{p.mk_indent(1)}return make_return(emitter);', |
| 402 |
'}', |
| 403 |
'' |
| 404 |
] |
| 405 |
else: |
| 406 |
function_defn = [ |
| 407 |
f'{inner_function_spec}', |
| 408 |
'{', |
| 409 |
f'{p.mk_indent(1)}pni_compound_context compound = make_compound();', |
| 410 |
*p.gen_emit_code(['emitter', '&compound'], 0, 1), |
| 411 |
f'{p.mk_indent(1)}return resize_required(emitter);', |
| 412 |
'}', |
| 413 |
'', |
| 414 |
f'{function_spec}', |
| 415 |
'{', |
| 416 |
f'{p.mk_indent(1)}do {{', |
| 417 |
f'{p.mk_indent(2)}pni_emitter_t emitter = make_emitter_from_buffer({", ".join(prefix_params)});', |
| 418 |
f'{p.mk_indent(2)}if ({p.mk_funcall(inner_function_name, ["&emitter", *args])}) {{', |
| 419 |
f'{p.mk_indent(3)}{p.mk_funcall("size_buffer_to_emitter", [*prefix_params, "&emitter"])};', |
| 420 |
f'{p.mk_indent(3)}continue;', |
| 421 |
f'{p.mk_indent(2)}}}', |
| 422 |
f'{p.mk_indent(2)}return make_bytes_from_emitter(emitter);', |
| 423 |
f'{p.mk_indent(1)}}} while (true);', |
| 424 |
f'{p.mk_indent(1)}/*Unreachable*/', |
| 425 |
'}', |
| 426 |
'' |
| 427 |
f'{bytes_function_spec}', |
| 428 |
'{', |
| 429 |
f'{p.mk_indent(1)}pni_emitter_t emitter = make_emitter_from_bytes((pn_rwbytes_t){{.size=size, .start=bytes}});', |
| 430 |
f'{p.mk_indent(1)}{p.mk_funcall(inner_function_name, ["&emitter", *args])};', |
| 431 |
f'{p.mk_indent(1)}return make_bytes_from_emitter(emitter).size;', |
| 432 |
'}', |
| 433 |
'' |
| 434 |
] |
| 435 |
return function_decl, function_defn |
| 436 |
|
| 437 |
|
| 438 |
prefix_emit_header = """ |
| 439 |
#include "proton/codec.h" |
| 440 |
#include "buffer.h" |
| 441 |
|
| 442 |
#include <stdbool.h> |
| 443 |
#include <stddef.h> |
| 444 |
#include <stdint.h> |
| 445 |
|
| 446 |
""" |
| 447 |
|
| 448 |
prefix_consume_header = """ |
| 449 |
#include "proton/codec.h" |
| 450 |
|
| 451 |
#include <stdbool.h> |
| 452 |
#include <stddef.h> |
| 453 |
#include <stdint.h> |
| 454 |
|
| 455 |
""" |
| 456 |
|
| 457 |
|
| 458 |
def output_header(decls: Dict[str, str], prefix: str, file=None): |
| 459 |
# Output declarations |
| 460 |
print(prefix, file=file) |
| 461 |
for fill_spec, decl in sorted(decls.items()): |
| 462 |
print( |
| 463 |
f'/* {fill_spec} */\n' |
| 464 |
f'{decl}', |
| 465 |
file=file |
| 466 |
) |
| 467 |
|
| 468 |
|
| 469 |
prefix_emit_implementation = """ |
| 470 |
#include "core/emitters.h" |
| 471 |
""" |
| 472 |
|
| 473 |
prefix_consume_implementation = """ |
| 474 |
#include "core/consumers.h" |
| 475 |
""" |
| 476 |
|
| 477 |
|
| 478 |
def output_implementation(defns: Dict[str, List[str]], prefix: str, header=None, file=None): |
| 479 |
# Output implementations |
| 480 |
if header: |
| 481 |
print(f'#include "{header}"', file=file) |
| 482 |
|
| 483 |
print(prefix, file=file) |
| 484 |
for fill_spec, defn in sorted(defns.items()): |
| 485 |
printable_defn = '\n'.join(defn) |
| 486 |
print( |
| 487 |
f'/* {fill_spec} */\n' |
| 488 |
f'{printable_defn}', |
| 489 |
file=file |
| 490 |
) |
| 491 |
|
| 492 |
|
| 493 |
def emit(fill_specs, decl_filename, impl_filename): |
| 494 |
decls: Dict[str, str] = {} |
| 495 |
defns: Dict[str, List[str]] = {} |
| 496 |
for fill_spec in fill_specs: |
| 497 |
decl, defn = emit_function('pn_amqp_encode', fill_spec, [('buffer', 'pn_buffer_t*')]) |
| 498 |
decls[fill_spec] = decl |
| 499 |
defns[fill_spec] = defn |
| 500 |
if decl_filename and impl_filename: |
| 501 |
with open(decl_filename, 'w') as dfile: |
| 502 |
output_header(decls, prefix_emit_header, file=dfile) |
| 503 |
with open(impl_filename, 'w') as ifile: |
| 504 |
output_implementation(defns, prefix_emit_implementation, header=os.path.basename(decl_filename), file=ifile) |
| 505 |
else: |
| 506 |
output_header(decls, prefix_emit_header) |
| 507 |
output_implementation(defns, prefix_emit_implementation) |
| 508 |
|
| 509 |
|
| 510 |
def consume(scan_specs, decl_filename, impl_filename): |
| 511 |
|
| 512 |
decls: Dict[str, str] = {} |
| 513 |
defns: Dict[str, List[str]] = {} |
| 514 |
for scan_spec in scan_specs: |
| 515 |
decl, defn = consume_function('pn_amqp_decode', scan_spec, [('bytes', 'pn_bytes_t')]) |
| 516 |
decls[scan_spec] = decl |
| 517 |
defns[scan_spec] = defn |
| 518 |
if decl_filename and impl_filename: |
| 519 |
with open(decl_filename, 'w') as dfile: |
| 520 |
output_header(decls, prefix_consume_header, file=dfile) |
| 521 |
with open(impl_filename, 'w') as ifile: |
| 522 |
output_implementation(defns, prefix_consume_implementation, header=os.path.basename(decl_filename), file=ifile) |
| 523 |
else: |
| 524 |
output_header(decls, prefix_consume_header) |
| 525 |
output_implementation(defns, prefix_consume_implementation) |
| 526 |
|
| 527 |
|
| 528 |
def main(): |
| 529 |
argparser = argparse.ArgumentParser(description='Generate AMQP codec in C for data scan/fill function calls') |
| 530 |
argparser.add_argument('-i', '--input_specs', help='json file with specs to generate codec output code', type=str, required=True) |
| 531 |
argparser.add_argument('-o', '--output-base', help='basename for output code', type=str) |
| 532 |
group = argparser.add_mutually_exclusive_group(required=True) |
| 533 |
group.add_argument('-e', '--emit', help='generate code to emit amqp', action='store_true') |
| 534 |
group.add_argument('-c', '--consume', help='generate code to consume amqp', action='store_true') |
| 535 |
|
| 536 |
args = argparser.parse_args() |
| 537 |
|
| 538 |
if args.output_base: |
| 539 |
decl_filename = args.output_base + '.h' |
| 540 |
impl_filename = args.output_base + '.c' |
| 541 |
else: |
| 542 |
decl_filename = None |
| 543 |
impl_filename = None |
| 544 |
|
| 545 |
with open(args.input_specs, 'r') as file: |
| 546 |
jsonfile = json.load(file) |
| 547 |
if args.emit: |
| 548 |
fill_specs = jsonfile['fill_specs'] |
| 549 |
emit(fill_specs, decl_filename, impl_filename) |
| 550 |
elif args.consume: |
| 551 |
scan_specs = jsonfile['scan_specs'] |
| 552 |
consume(scan_specs, decl_filename, impl_filename) |
| 553 |
|
| 554 |
|
| 555 |
if __name__ == '__main__': |
| 556 |
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) |
| 557 |
sys.exit(main()) |