1#!/usr/bin/env python 2 3from __future__ import unicode_literals 4 5'''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.''' 6nanopb_version = "nanopb-0.3.9.1" 7 8import sys 9import re 10import codecs 11from functools import reduce 12 13try: 14 # Add some dummy imports to keep packaging tools happy. 15 import google, distutils.util # bbfreeze seems to need these 16 import pkg_resources # pyinstaller / protobuf 2.5 seem to need these 17except: 18 # Don't care, we will error out later if it is actually important. 19 pass 20 21try: 22 import google.protobuf.text_format as text_format 23 import google.protobuf.descriptor_pb2 as descriptor 24except: 25 sys.stderr.write(''' 26 ************************************************************* 27 *** Could not import the Google protobuf Python libraries *** 28 *** Try installing package 'python-protobuf' or similar. *** 29 ************************************************************* 30 ''' + '\n') 31 raise 32 33try: 34 import proto.nanopb_pb2 as nanopb_pb2 35 import proto.plugin_pb2 as plugin_pb2 36except TypeError: 37 sys.stderr.write(''' 38 **************************************************************************** 39 *** Got TypeError when importing the protocol definitions for generator. *** 40 *** This usually means that the protoc in your path doesn't match the *** 41 *** Python protobuf library version. *** 42 *** *** 43 *** Please check the output of the following commands: *** 44 *** which protoc *** 45 *** protoc --version *** 46 *** python -c 'import google.protobuf; print(google.protobuf.__file__)' *** 47 **************************************************************************** 48 ''' + '\n') 49 raise 50except: 51 sys.stderr.write(''' 52 ******************************************************************** 53 *** Failed to import the protocol definitions for generator. *** 54 *** You have to run 'make' in the nanopb/generator/proto folder. *** 55 ******************************************************************** 56 ''' + '\n') 57 raise 58 59# --------------------------------------------------------------------------- 60# Generation of single fields 61# --------------------------------------------------------------------------- 62 63import time 64import os.path 65 66# Values are tuple (c type, pb type, encoded size, int_size_allowed) 67FieldD = descriptor.FieldDescriptorProto 68datatypes = { 69 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1, False), 70 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8, False), 71 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4, False), 72 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8, False), 73 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4, False), 74 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10, True), 75 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10, True), 76 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4, False), 77 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8, False), 78 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5, True), 79 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10, True), 80 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5, True), 81 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10, True) 82} 83 84# Integer size overrides (from .proto settings) 85intsizes = { 86 nanopb_pb2.IS_8: 'int8_t', 87 nanopb_pb2.IS_16: 'int16_t', 88 nanopb_pb2.IS_32: 'int32_t', 89 nanopb_pb2.IS_64: 'int64_t', 90} 91 92# String types (for python 2 / python 3 compatibility) 93try: 94 strtypes = (unicode, str) 95except NameError: 96 strtypes = (str, ) 97 98class Names: 99 '''Keeps a set of nested names and formats them to C identifier.''' 100 def __init__(self, parts = ()): 101 if isinstance(parts, Names): 102 parts = parts.parts 103 self.parts = tuple(parts) 104 105 def __str__(self): 106 return '_'.join(self.parts) 107 108 def __add__(self, other): 109 if isinstance(other, strtypes): 110 return Names(self.parts + (other,)) 111 elif isinstance(other, tuple): 112 return Names(self.parts + other) 113 else: 114 raise ValueError("Name parts should be of type str") 115 116 def __eq__(self, other): 117 return isinstance(other, Names) and self.parts == other.parts 118 119def names_from_type_name(type_name): 120 '''Parse Names() from FieldDescriptorProto type_name''' 121 if type_name[0] != '.': 122 raise NotImplementedError("Lookup of non-absolute type names is not supported") 123 return Names(type_name[1:].split('.')) 124 125def varint_max_size(max_value): 126 '''Returns the maximum number of bytes a varint can take when encoded.''' 127 if max_value < 0: 128 max_value = 2**64 - max_value 129 for i in range(1, 11): 130 if (max_value >> (i * 7)) == 0: 131 return i 132 raise ValueError("Value too large for varint: " + str(max_value)) 133 134assert varint_max_size(-1) == 10 135assert varint_max_size(0) == 1 136assert varint_max_size(127) == 1 137assert varint_max_size(128) == 2 138 139class EncodedSize: 140 '''Class used to represent the encoded size of a field or a message. 141 Consists of a combination of symbolic sizes and integer sizes.''' 142 def __init__(self, value = 0, symbols = []): 143 if isinstance(value, EncodedSize): 144 self.value = value.value 145 self.symbols = value.symbols 146 elif isinstance(value, strtypes + (Names,)): 147 self.symbols = [str(value)] 148 self.value = 0 149 else: 150 self.value = value 151 self.symbols = symbols 152 153 def __add__(self, other): 154 if isinstance(other, int): 155 return EncodedSize(self.value + other, self.symbols) 156 elif isinstance(other, strtypes + (Names,)): 157 return EncodedSize(self.value, self.symbols + [str(other)]) 158 elif isinstance(other, EncodedSize): 159 return EncodedSize(self.value + other.value, self.symbols + other.symbols) 160 else: 161 raise ValueError("Cannot add size: " + repr(other)) 162 163 def __mul__(self, other): 164 if isinstance(other, int): 165 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols]) 166 else: 167 raise ValueError("Cannot multiply size: " + repr(other)) 168 169 def __str__(self): 170 if not self.symbols: 171 return str(self.value) 172 else: 173 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')' 174 175 def upperlimit(self): 176 if not self.symbols: 177 return self.value 178 else: 179 return 2**32 - 1 180 181class Enum: 182 def __init__(self, names, desc, enum_options): 183 '''desc is EnumDescriptorProto''' 184 185 self.options = enum_options 186 self.names = names + desc.name 187 188 if enum_options.long_names: 189 self.values = [(self.names + x.name, x.number) for x in desc.value] 190 else: 191 self.values = [(names + x.name, x.number) for x in desc.value] 192 193 self.value_longnames = [self.names + x.name for x in desc.value] 194 self.packed = enum_options.packed_enum 195 196 def has_negative(self): 197 for n, v in self.values: 198 if v < 0: 199 return True 200 return False 201 202 def encoded_size(self): 203 return max([varint_max_size(v) for n,v in self.values]) 204 205 def __str__(self): 206 result = 'typedef enum _%s {\n' % self.names 207 result += ',\n'.join([" %s = %d" % x for x in self.values]) 208 result += '\n}' 209 210 if self.packed: 211 result += ' pb_packed' 212 213 result += ' %s;' % self.names 214 215 result += '\n#define _%s_MIN %s' % (self.names, self.values[0][0]) 216 result += '\n#define _%s_MAX %s' % (self.names, self.values[-1][0]) 217 result += '\n#define _%s_ARRAYSIZE ((%s)(%s+1))' % (self.names, self.names, self.values[-1][0]) 218 219 if not self.options.long_names: 220 # Define the long names always so that enum value references 221 # from other files work properly. 222 for i, x in enumerate(self.values): 223 result += '\n#define %s %s' % (self.value_longnames[i], x[0]) 224 225 if self.options.enum_to_string: 226 result += '\nconst char *%s_name(%s v);\n' % (self.names, self.names) 227 228 return result 229 230 def enum_to_string_definition(self): 231 if not self.options.enum_to_string: 232 return "" 233 234 result = 'const char *%s_name(%s v) {\n' % (self.names, self.names) 235 result += ' switch (v) {\n' 236 237 for ((enumname, _), strname) in zip(self.values, self.value_longnames): 238 # Strip off the leading type name from the string value. 239 strval = str(strname)[len(str(self.names)) + 1:] 240 result += ' case %s: return "%s";\n' % (enumname, strval) 241 242 result += ' }\n' 243 result += ' return "unknown";\n' 244 result += '}\n' 245 246 return result 247 248class FieldMaxSize: 249 def __init__(self, worst = 0, checks = [], field_name = 'undefined'): 250 if isinstance(worst, list): 251 self.worst = max(i for i in worst if i is not None) 252 else: 253 self.worst = worst 254 255 self.worst_field = field_name 256 self.checks = list(checks) 257 258 def extend(self, extend, field_name = None): 259 self.worst = max(self.worst, extend.worst) 260 261 if self.worst == extend.worst: 262 self.worst_field = extend.worst_field 263 264 self.checks.extend(extend.checks) 265 266class Field: 267 def __init__(self, struct_name, desc, field_options): 268 '''desc is FieldDescriptorProto''' 269 self.tag = desc.number 270 self.struct_name = struct_name 271 self.union_name = None 272 self.name = desc.name 273 self.default = None 274 self.max_size = None 275 self.max_count = None 276 self.array_decl = "" 277 self.enc_size = None 278 self.ctype = None 279 self.fixed_count = False 280 281 if field_options.type == nanopb_pb2.FT_INLINE: 282 # Before nanopb-0.3.8, fixed length bytes arrays were specified 283 # by setting type to FT_INLINE. But to handle pointer typed fields, 284 # it makes sense to have it as a separate option. 285 field_options.type = nanopb_pb2.FT_STATIC 286 field_options.fixed_length = True 287 288 # Parse field options 289 if field_options.HasField("max_size"): 290 self.max_size = field_options.max_size 291 292 if desc.type == FieldD.TYPE_STRING and field_options.HasField("max_length"): 293 # max_length overrides max_size for strings 294 self.max_size = field_options.max_length + 1 295 296 if field_options.HasField("max_count"): 297 self.max_count = field_options.max_count 298 299 if desc.HasField('default_value'): 300 self.default = desc.default_value 301 302 # Check field rules, i.e. required/optional/repeated. 303 can_be_static = True 304 if desc.label == FieldD.LABEL_REPEATED: 305 self.rules = 'REPEATED' 306 if self.max_count is None: 307 can_be_static = False 308 else: 309 self.array_decl = '[%d]' % self.max_count 310 self.fixed_count = field_options.fixed_count 311 312 elif field_options.proto3: 313 self.rules = 'SINGULAR' 314 elif desc.label == FieldD.LABEL_REQUIRED: 315 self.rules = 'REQUIRED' 316 elif desc.label == FieldD.LABEL_OPTIONAL: 317 self.rules = 'OPTIONAL' 318 else: 319 raise NotImplementedError(desc.label) 320 321 # Check if the field can be implemented with static allocation 322 # i.e. whether the data size is known. 323 if desc.type == FieldD.TYPE_STRING and self.max_size is None: 324 can_be_static = False 325 326 if desc.type == FieldD.TYPE_BYTES and self.max_size is None: 327 can_be_static = False 328 329 # Decide how the field data will be allocated 330 if field_options.type == nanopb_pb2.FT_DEFAULT: 331 if can_be_static: 332 field_options.type = nanopb_pb2.FT_STATIC 333 else: 334 field_options.type = nanopb_pb2.FT_CALLBACK 335 336 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static: 337 raise Exception("Field '%s' is defined as static, but max_size or " 338 "max_count is not given." % self.name) 339 340 if field_options.fixed_count and self.max_count is None: 341 raise Exception("Field '%s' is defined as fixed count, " 342 "but max_count is not given." % self.name) 343 344 if field_options.type == nanopb_pb2.FT_STATIC: 345 self.allocation = 'STATIC' 346 elif field_options.type == nanopb_pb2.FT_POINTER: 347 self.allocation = 'POINTER' 348 elif field_options.type == nanopb_pb2.FT_CALLBACK: 349 self.allocation = 'CALLBACK' 350 else: 351 raise NotImplementedError(field_options.type) 352 353 # Decide the C data type to use in the struct. 354 if desc.type in datatypes: 355 self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type] 356 357 # Override the field size if user wants to use smaller integers 358 if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT: 359 self.ctype = intsizes[field_options.int_size] 360 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64: 361 self.ctype = 'u' + self.ctype; 362 elif desc.type == FieldD.TYPE_ENUM: 363 self.pbtype = 'ENUM' 364 self.ctype = names_from_type_name(desc.type_name) 365 if self.default is not None: 366 self.default = self.ctype + self.default 367 self.enc_size = None # Needs to be filled in when enum values are known 368 elif desc.type == FieldD.TYPE_STRING: 369 self.pbtype = 'STRING' 370 self.ctype = 'char' 371 if self.allocation == 'STATIC': 372 self.ctype = 'char' 373 self.array_decl += '[%d]' % self.max_size 374 self.enc_size = varint_max_size(self.max_size) + self.max_size 375 elif desc.type == FieldD.TYPE_BYTES: 376 if field_options.fixed_length: 377 self.pbtype = 'FIXED_LENGTH_BYTES' 378 379 if self.max_size is None: 380 raise Exception("Field '%s' is defined as fixed length, " 381 "but max_size is not given." % self.name) 382 383 self.enc_size = varint_max_size(self.max_size) + self.max_size 384 self.ctype = 'pb_byte_t' 385 self.array_decl += '[%d]' % self.max_size 386 else: 387 self.pbtype = 'BYTES' 388 self.ctype = 'pb_bytes_array_t' 389 if self.allocation == 'STATIC': 390 self.ctype = self.struct_name + self.name + 't' 391 self.enc_size = varint_max_size(self.max_size) + self.max_size 392 elif desc.type == FieldD.TYPE_MESSAGE: 393 self.pbtype = 'MESSAGE' 394 self.ctype = self.submsgname = names_from_type_name(desc.type_name) 395 self.enc_size = None # Needs to be filled in after the message type is available 396 else: 397 raise NotImplementedError(desc.type) 398 399 def __lt__(self, other): 400 return self.tag < other.tag 401 402 def __str__(self): 403 result = '' 404 if self.allocation == 'POINTER': 405 if self.rules == 'REPEATED': 406 result += ' pb_size_t ' + self.name + '_count;\n' 407 408 if self.pbtype == 'MESSAGE': 409 # Use struct definition, so recursive submessages are possible 410 result += ' struct _%s *%s;' % (self.ctype, self.name) 411 elif self.pbtype == 'FIXED_LENGTH_BYTES': 412 # Pointer to fixed size array 413 result += ' %s (*%s)%s;' % (self.ctype, self.name, self.array_decl) 414 elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']: 415 # String/bytes arrays need to be defined as pointers to pointers 416 result += ' %s **%s;' % (self.ctype, self.name) 417 else: 418 result += ' %s *%s;' % (self.ctype, self.name) 419 elif self.allocation == 'CALLBACK': 420 result += ' pb_callback_t %s;' % self.name 421 else: 422 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC': 423 result += ' bool has_' + self.name + ';\n' 424 elif (self.rules == 'REPEATED' and 425 self.allocation == 'STATIC' and 426 not self.fixed_count): 427 result += ' pb_size_t ' + self.name + '_count;\n' 428 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl) 429 return result 430 431 def types(self): 432 '''Return definitions for any special types this field might need.''' 433 if self.pbtype == 'BYTES' and self.allocation == 'STATIC': 434 result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype) 435 else: 436 result = '' 437 return result 438 439 def get_dependencies(self): 440 '''Get list of type names used by this field.''' 441 if self.allocation == 'STATIC': 442 return [str(self.ctype)] 443 else: 444 return [] 445 446 def get_initializer(self, null_init, inner_init_only = False): 447 '''Return literal expression for this field's default value. 448 null_init: If True, initialize to a 0 value instead of default from .proto 449 inner_init_only: If True, exclude initialization for any count/has fields 450 ''' 451 452 inner_init = None 453 if self.pbtype == 'MESSAGE': 454 if null_init: 455 inner_init = '%s_init_zero' % self.ctype 456 else: 457 inner_init = '%s_init_default' % self.ctype 458 elif self.default is None or null_init: 459 if self.pbtype == 'STRING': 460 inner_init = '""' 461 elif self.pbtype == 'BYTES': 462 inner_init = '{0, {0}}' 463 elif self.pbtype == 'FIXED_LENGTH_BYTES': 464 inner_init = '{0}' 465 elif self.pbtype in ('ENUM', 'UENUM'): 466 inner_init = '_%s_MIN' % self.ctype 467 else: 468 inner_init = '0' 469 else: 470 if self.pbtype == 'STRING': 471 data = codecs.escape_encode(self.default.encode('utf-8'))[0] 472 inner_init = '"' + data.decode('ascii') + '"' 473 elif self.pbtype == 'BYTES': 474 data = codecs.escape_decode(self.default)[0] 475 data = ["0x%02x" % c for c in bytearray(data)] 476 if len(data) == 0: 477 inner_init = '{0, {0}}' 478 else: 479 inner_init = '{%d, {%s}}' % (len(data), ','.join(data)) 480 elif self.pbtype == 'FIXED_LENGTH_BYTES': 481 data = codecs.escape_decode(self.default)[0] 482 data = ["0x%02x" % c for c in bytearray(data)] 483 if len(data) == 0: 484 inner_init = '{0}' 485 else: 486 inner_init = '{%s}' % ','.join(data) 487 elif self.pbtype in ['FIXED32', 'UINT32']: 488 inner_init = str(self.default) + 'u' 489 elif self.pbtype in ['FIXED64', 'UINT64']: 490 inner_init = str(self.default) + 'ull' 491 elif self.pbtype in ['SFIXED64', 'INT64']: 492 inner_init = str(self.default) + 'll' 493 else: 494 inner_init = str(self.default) 495 496 if inner_init_only: 497 return inner_init 498 499 outer_init = None 500 if self.allocation == 'STATIC': 501 if self.rules == 'REPEATED': 502 outer_init = '' 503 if not self.fixed_count: 504 outer_init += '0, ' 505 outer_init += '{' 506 outer_init += ', '.join([inner_init] * self.max_count) 507 outer_init += '}' 508 elif self.rules == 'OPTIONAL': 509 outer_init = 'false, ' + inner_init 510 else: 511 outer_init = inner_init 512 elif self.allocation == 'POINTER': 513 if self.rules == 'REPEATED': 514 outer_init = '0, NULL' 515 else: 516 outer_init = 'NULL' 517 elif self.allocation == 'CALLBACK': 518 if self.pbtype == 'EXTENSION': 519 outer_init = 'NULL' 520 else: 521 outer_init = '{{NULL}, NULL}' 522 523 return outer_init 524 525 def default_decl(self, declaration_only = False): 526 '''Return definition for this field's default value.''' 527 if self.default is None: 528 return None 529 530 ctype = self.ctype 531 default = self.get_initializer(False, True) 532 array_decl = '' 533 534 if self.pbtype == 'STRING': 535 if self.allocation != 'STATIC': 536 return None # Not implemented 537 array_decl = '[%d]' % self.max_size 538 elif self.pbtype == 'BYTES': 539 if self.allocation != 'STATIC': 540 return None # Not implemented 541 elif self.pbtype == 'FIXED_LENGTH_BYTES': 542 if self.allocation != 'STATIC': 543 return None # Not implemented 544 array_decl = '[%d]' % self.max_size 545 546 if declaration_only: 547 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl) 548 else: 549 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default) 550 551 def tags(self): 552 '''Return the #define for the tag number of this field.''' 553 identifier = '%s_%s_tag' % (self.struct_name, self.name) 554 return '#define %-40s %d\n' % (identifier, self.tag) 555 556 def pb_field_t(self, prev_field_name, union_index = None): 557 '''Return the pb_field_t initializer to use in the constant array. 558 prev_field_name is the name of the previous field or None. For OneOf 559 unions, union_index is the index of this field inside the OneOf. 560 ''' 561 562 if self.rules == 'ONEOF': 563 if self.anonymous: 564 result = ' PB_ANONYMOUS_ONEOF_FIELD(%s, ' % self.union_name 565 else: 566 result = ' PB_ONEOF_FIELD(%s, ' % self.union_name 567 elif self.fixed_count: 568 result = ' PB_REPEATED_FIXED_COUNT(' 569 else: 570 result = ' PB_FIELD(' 571 572 result += '%3d, ' % self.tag 573 result += '%-8s, ' % self.pbtype 574 if not self.fixed_count: 575 result += '%s, ' % self.rules 576 result += '%-8s, ' % self.allocation 577 578 if union_index is not None and union_index > 0: 579 result += 'UNION, ' 580 elif prev_field_name is None: 581 result += 'FIRST, ' 582 else: 583 result += 'OTHER, ' 584 585 result += '%s, ' % self.struct_name 586 result += '%s, ' % self.name 587 result += '%s, ' % (prev_field_name or self.name) 588 589 if self.pbtype == 'MESSAGE': 590 result += '&%s_fields)' % self.submsgname 591 elif self.default is None: 592 result += '0)' 593 elif self.pbtype in ['BYTES', 'STRING', 'FIXED_LENGTH_BYTES'] and self.allocation != 'STATIC': 594 result += '0)' # Arbitrary size default values not implemented 595 elif self.rules == 'OPTEXT': 596 result += '0)' # Default value for extensions is not implemented 597 else: 598 result += '&%s_default)' % (self.struct_name + self.name) 599 600 return result 601 602 def get_last_field_name(self): 603 return self.name 604 605 def largest_field_value(self): 606 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly. 607 Returns numeric value or a C-expression for assert.''' 608 check = [] 609 if self.pbtype == 'MESSAGE' and self.allocation == 'STATIC': 610 if self.rules == 'REPEATED': 611 check.append('pb_membersize(%s, %s[0])' % (self.struct_name, self.name)) 612 elif self.rules == 'ONEOF': 613 if self.anonymous: 614 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name)) 615 else: 616 check.append('pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name)) 617 else: 618 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name)) 619 elif self.pbtype == 'BYTES' and self.allocation == 'STATIC': 620 if self.max_size > 251: 621 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name)) 622 623 return FieldMaxSize([self.tag, self.max_size, self.max_count], 624 check, 625 ('%s.%s' % (self.struct_name, self.name))) 626 627 def encoded_size(self, dependencies): 628 '''Return the maximum size that this field can take when encoded, 629 including the field tag. If the size cannot be determined, returns 630 None.''' 631 632 if self.allocation != 'STATIC': 633 return None 634 635 if self.pbtype == 'MESSAGE': 636 encsize = None 637 if str(self.submsgname) in dependencies: 638 submsg = dependencies[str(self.submsgname)] 639 encsize = submsg.encoded_size(dependencies) 640 if encsize is not None: 641 # Include submessage length prefix 642 encsize += varint_max_size(encsize.upperlimit()) 643 644 if encsize is None: 645 # Submessage or its size cannot be found. 646 # This can occur if submessage is defined in different 647 # file, and it or its .options could not be found. 648 # Instead of direct numeric value, reference the size that 649 # has been #defined in the other file. 650 encsize = EncodedSize(self.submsgname + 'size') 651 652 # We will have to make a conservative assumption on the length 653 # prefix size, though. 654 encsize += 5 655 656 elif self.pbtype in ['ENUM', 'UENUM']: 657 if str(self.ctype) in dependencies: 658 enumtype = dependencies[str(self.ctype)] 659 encsize = enumtype.encoded_size() 660 else: 661 # Conservative assumption 662 encsize = 10 663 664 elif self.enc_size is None: 665 raise RuntimeError("Could not determine encoded size for %s.%s" 666 % (self.struct_name, self.name)) 667 else: 668 encsize = EncodedSize(self.enc_size) 669 670 encsize += varint_max_size(self.tag << 3) # Tag + wire type 671 672 if self.rules == 'REPEATED': 673 # Decoders must be always able to handle unpacked arrays. 674 # Therefore we have to reserve space for it, even though 675 # we emit packed arrays ourselves. For length of 1, packed 676 # arrays are larger however so we need to add allowance 677 # for the length byte. 678 encsize *= self.max_count 679 680 if self.max_count == 1: 681 encsize += 1 682 683 return encsize 684 685 686class ExtensionRange(Field): 687 def __init__(self, struct_name, range_start, field_options): 688 '''Implements a special pb_extension_t* field in an extensible message 689 structure. The range_start signifies the index at which the extensions 690 start. Not necessarily all tags above this are extensions, it is merely 691 a speed optimization. 692 ''' 693 self.tag = range_start 694 self.struct_name = struct_name 695 self.name = 'extensions' 696 self.pbtype = 'EXTENSION' 697 self.rules = 'OPTIONAL' 698 self.allocation = 'CALLBACK' 699 self.ctype = 'pb_extension_t' 700 self.array_decl = '' 701 self.default = None 702 self.max_size = 0 703 self.max_count = 0 704 self.fixed_count = False 705 706 def __str__(self): 707 return ' pb_extension_t *extensions;' 708 709 def types(self): 710 return '' 711 712 def tags(self): 713 return '' 714 715 def encoded_size(self, dependencies): 716 # We exclude extensions from the count, because they cannot be known 717 # until runtime. Other option would be to return None here, but this 718 # way the value remains useful if extensions are not used. 719 return EncodedSize(0) 720 721class ExtensionField(Field): 722 def __init__(self, struct_name, desc, field_options): 723 self.fullname = struct_name + desc.name 724 self.extendee_name = names_from_type_name(desc.extendee) 725 Field.__init__(self, self.fullname + 'struct', desc, field_options) 726 727 if self.rules != 'OPTIONAL': 728 self.skip = True 729 else: 730 self.skip = False 731 self.rules = 'OPTEXT' 732 733 def tags(self): 734 '''Return the #define for the tag number of this field.''' 735 identifier = '%s_tag' % self.fullname 736 return '#define %-40s %d\n' % (identifier, self.tag) 737 738 def extension_decl(self): 739 '''Declaration of the extension type in the .pb.h file''' 740 if self.skip: 741 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname 742 msg +=' type of extension fields is currently supported. */\n' 743 return msg 744 745 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' % 746 (self.fullname, str(self).strip())) 747 748 def extension_def(self): 749 '''Definition of the extension type in the .pb.c file''' 750 751 if self.skip: 752 return '' 753 754 result = 'typedef struct {\n' 755 result += str(self) 756 result += '\n} %s;\n\n' % self.struct_name 757 result += ('static const pb_field_t %s_field = \n %s;\n\n' % 758 (self.fullname, self.pb_field_t(None))) 759 result += 'const pb_extension_type_t %s = {\n' % self.fullname 760 result += ' NULL,\n' 761 result += ' NULL,\n' 762 result += ' &%s_field\n' % self.fullname 763 result += '};\n' 764 return result 765 766 767# --------------------------------------------------------------------------- 768# Generation of oneofs (unions) 769# --------------------------------------------------------------------------- 770 771class OneOf(Field): 772 def __init__(self, struct_name, oneof_desc): 773 self.struct_name = struct_name 774 self.name = oneof_desc.name 775 self.ctype = 'union' 776 self.pbtype = 'oneof' 777 self.fields = [] 778 self.allocation = 'ONEOF' 779 self.default = None 780 self.rules = 'ONEOF' 781 self.anonymous = False 782 783 def add_field(self, field): 784 if field.allocation == 'CALLBACK': 785 raise Exception("Callback fields inside of oneof are not supported" 786 + " (field %s)" % field.name) 787 788 field.union_name = self.name 789 field.rules = 'ONEOF' 790 field.anonymous = self.anonymous 791 self.fields.append(field) 792 self.fields.sort(key = lambda f: f.tag) 793 794 # Sort by the lowest tag number inside union 795 self.tag = min([f.tag for f in self.fields]) 796 797 def __str__(self): 798 result = '' 799 if self.fields: 800 result += ' pb_size_t which_' + self.name + ";\n" 801 result += ' union {\n' 802 for f in self.fields: 803 result += ' ' + str(f).replace('\n', '\n ') + '\n' 804 if self.anonymous: 805 result += ' };' 806 else: 807 result += ' } ' + self.name + ';' 808 return result 809 810 def types(self): 811 return ''.join([f.types() for f in self.fields]) 812 813 def get_dependencies(self): 814 deps = [] 815 for f in self.fields: 816 deps += f.get_dependencies() 817 return deps 818 819 def get_initializer(self, null_init): 820 return '0, {' + self.fields[0].get_initializer(null_init) + '}' 821 822 def default_decl(self, declaration_only = False): 823 return None 824 825 def tags(self): 826 return ''.join([f.tags() for f in self.fields]) 827 828 def pb_field_t(self, prev_field_name): 829 parts = [] 830 for union_index, field in enumerate(self.fields): 831 parts.append(field.pb_field_t(prev_field_name, union_index)) 832 return ',\n'.join(parts) 833 834 def get_last_field_name(self): 835 if self.anonymous: 836 return self.fields[-1].name 837 else: 838 return self.name + '.' + self.fields[-1].name 839 840 def largest_field_value(self): 841 largest = FieldMaxSize() 842 for f in self.fields: 843 largest.extend(f.largest_field_value()) 844 return largest 845 846 def encoded_size(self, dependencies): 847 '''Returns the size of the largest oneof field.''' 848 largest = EncodedSize(0) 849 symbols = set() 850 for f in self.fields: 851 size = EncodedSize(f.encoded_size(dependencies)) 852 if size.value is None: 853 return None 854 elif size.symbols: 855 symbols.add(EncodedSize(f.submsgname + 'size').symbols[0]) 856 elif size.value > largest.value: 857 largest = size 858 859 if not symbols: 860 return largest 861 862 symbols = list(symbols) 863 symbols.append(str(largest)) 864 max_size = lambda x, y: '({0} > {1} ? {0} : {1})'.format(x, y) 865 return reduce(max_size, symbols) 866 867# --------------------------------------------------------------------------- 868# Generation of messages (structures) 869# --------------------------------------------------------------------------- 870 871 872class Message: 873 def __init__(self, names, desc, message_options): 874 self.name = names 875 self.fields = [] 876 self.oneofs = {} 877 no_unions = [] 878 879 if message_options.msgid: 880 self.msgid = message_options.msgid 881 882 if hasattr(desc, 'oneof_decl'): 883 for i, f in enumerate(desc.oneof_decl): 884 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name) 885 if oneof_options.no_unions: 886 no_unions.append(i) # No union, but add fields normally 887 elif oneof_options.type == nanopb_pb2.FT_IGNORE: 888 pass # No union and skip fields also 889 else: 890 oneof = OneOf(self.name, f) 891 if oneof_options.anonymous_oneof: 892 oneof.anonymous = True 893 self.oneofs[i] = oneof 894 self.fields.append(oneof) 895 else: 896 sys.stderr.write('Note: This Python protobuf library has no OneOf support\n') 897 898 for f in desc.field: 899 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name) 900 if field_options.type == nanopb_pb2.FT_IGNORE: 901 continue 902 903 field = Field(self.name, f, field_options) 904 if (hasattr(f, 'oneof_index') and 905 f.HasField('oneof_index') and 906 f.oneof_index not in no_unions): 907 if f.oneof_index in self.oneofs: 908 self.oneofs[f.oneof_index].add_field(field) 909 else: 910 self.fields.append(field) 911 912 if len(desc.extension_range) > 0: 913 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions') 914 range_start = min([r.start for r in desc.extension_range]) 915 if field_options.type != nanopb_pb2.FT_IGNORE: 916 self.fields.append(ExtensionRange(self.name, range_start, field_options)) 917 918 self.packed = message_options.packed_struct 919 self.ordered_fields = self.fields[:] 920 self.ordered_fields.sort() 921 922 def get_dependencies(self): 923 '''Get list of type names that this structure refers to.''' 924 deps = [] 925 for f in self.fields: 926 deps += f.get_dependencies() 927 return deps 928 929 def __str__(self): 930 result = 'typedef struct _%s {\n' % self.name 931 932 if not self.ordered_fields: 933 # Empty structs are not allowed in C standard. 934 # Therefore add a dummy field if an empty message occurs. 935 result += ' char dummy_field;' 936 937 result += '\n'.join([str(f) for f in self.ordered_fields]) 938 result += '\n/* @@protoc_insertion_point(struct:%s) */' % self.name 939 result += '\n}' 940 941 if self.packed: 942 result += ' pb_packed' 943 944 result += ' %s;' % self.name 945 946 if self.packed: 947 result = 'PB_PACKED_STRUCT_START\n' + result 948 result += '\nPB_PACKED_STRUCT_END' 949 950 return result 951 952 def types(self): 953 return ''.join([f.types() for f in self.fields]) 954 955 def get_initializer(self, null_init): 956 if not self.ordered_fields: 957 return '{0}' 958 959 parts = [] 960 for field in self.ordered_fields: 961 parts.append(field.get_initializer(null_init)) 962 return '{' + ', '.join(parts) + '}' 963 964 def default_decl(self, declaration_only = False): 965 result = "" 966 for field in self.fields: 967 default = field.default_decl(declaration_only) 968 if default is not None: 969 result += default + '\n' 970 return result 971 972 def count_required_fields(self): 973 '''Returns number of required fields inside this message''' 974 count = 0 975 for f in self.fields: 976 if not isinstance(f, OneOf): 977 if f.rules == 'REQUIRED': 978 count += 1 979 return count 980 981 def count_all_fields(self): 982 count = 0 983 for f in self.fields: 984 if isinstance(f, OneOf): 985 count += len(f.fields) 986 else: 987 count += 1 988 return count 989 990 def fields_declaration(self): 991 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1) 992 return result 993 994 def fields_definition(self): 995 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1) 996 997 prev = None 998 for field in self.ordered_fields: 999 result += field.pb_field_t(prev) 1000 result += ',\n' 1001 prev = field.get_last_field_name() 1002 1003 result += ' PB_LAST_FIELD\n};' 1004 return result 1005 1006 def encoded_size(self, dependencies): 1007 '''Return the maximum size that this message can take when encoded. 1008 If the size cannot be determined, returns None. 1009 ''' 1010 size = EncodedSize(0) 1011 for field in self.fields: 1012 fsize = field.encoded_size(dependencies) 1013 if fsize is None: 1014 return None 1015 size += fsize 1016 1017 return size 1018 1019 1020# --------------------------------------------------------------------------- 1021# Processing of entire .proto files 1022# --------------------------------------------------------------------------- 1023 1024def iterate_messages(desc, names = Names()): 1025 '''Recursively find all messages. For each, yield name, DescriptorProto.''' 1026 if hasattr(desc, 'message_type'): 1027 submsgs = desc.message_type 1028 else: 1029 submsgs = desc.nested_type 1030 1031 for submsg in submsgs: 1032 sub_names = names + submsg.name 1033 yield sub_names, submsg 1034 1035 for x in iterate_messages(submsg, sub_names): 1036 yield x 1037 1038def iterate_extensions(desc, names = Names()): 1039 '''Recursively find all extensions. 1040 For each, yield name, FieldDescriptorProto. 1041 ''' 1042 for extension in desc.extension: 1043 yield names, extension 1044 1045 for subname, subdesc in iterate_messages(desc, names): 1046 for extension in subdesc.extension: 1047 yield subname, extension 1048 1049def toposort2(data): 1050 '''Topological sort. 1051 From http://code.activestate.com/recipes/577413-topological-sort/ 1052 This function is under the MIT license. 1053 ''' 1054 for k, v in list(data.items()): 1055 v.discard(k) # Ignore self dependencies 1056 extra_items_in_deps = reduce(set.union, list(data.values()), set()) - set(data.keys()) 1057 data.update(dict([(item, set()) for item in extra_items_in_deps])) 1058 while True: 1059 ordered = set(item for item,dep in list(data.items()) if not dep) 1060 if not ordered: 1061 break 1062 for item in sorted(ordered): 1063 yield item 1064 data = dict([(item, (dep - ordered)) for item,dep in list(data.items()) 1065 if item not in ordered]) 1066 assert not data, "A cyclic dependency exists amongst %r" % data 1067 1068def sort_dependencies(messages): 1069 '''Sort a list of Messages based on dependencies.''' 1070 dependencies = {} 1071 message_by_name = {} 1072 for message in messages: 1073 dependencies[str(message.name)] = set(message.get_dependencies()) 1074 message_by_name[str(message.name)] = message 1075 1076 for msgname in toposort2(dependencies): 1077 if msgname in message_by_name: 1078 yield message_by_name[msgname] 1079 1080def make_identifier(headername): 1081 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9''' 1082 result = "" 1083 for c in headername.upper(): 1084 if c.isalnum(): 1085 result += c 1086 else: 1087 result += '_' 1088 return result 1089 1090class ProtoFile: 1091 def __init__(self, fdesc, file_options): 1092 '''Takes a FileDescriptorProto and parses it.''' 1093 self.fdesc = fdesc 1094 self.file_options = file_options 1095 self.dependencies = {} 1096 self.parse() 1097 1098 # Some of types used in this file probably come from the file itself. 1099 # Thus it has implicit dependency on itself. 1100 self.add_dependency(self) 1101 1102 def parse(self): 1103 self.enums = [] 1104 self.messages = [] 1105 self.extensions = [] 1106 1107 if self.fdesc.package: 1108 base_name = Names(self.fdesc.package.split('.')) 1109 else: 1110 base_name = Names() 1111 1112 for enum in self.fdesc.enum_type: 1113 enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name) 1114 self.enums.append(Enum(base_name, enum, enum_options)) 1115 1116 for names, message in iterate_messages(self.fdesc, base_name): 1117 message_options = get_nanopb_suboptions(message, self.file_options, names) 1118 1119 if message_options.skip_message: 1120 continue 1121 1122 self.messages.append(Message(names, message, message_options)) 1123 for enum in message.enum_type: 1124 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name) 1125 self.enums.append(Enum(names, enum, enum_options)) 1126 1127 for names, extension in iterate_extensions(self.fdesc, base_name): 1128 field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name) 1129 if field_options.type != nanopb_pb2.FT_IGNORE: 1130 self.extensions.append(ExtensionField(names, extension, field_options)) 1131 1132 def add_dependency(self, other): 1133 for enum in other.enums: 1134 self.dependencies[str(enum.names)] = enum 1135 1136 for msg in other.messages: 1137 self.dependencies[str(msg.name)] = msg 1138 1139 # Fix field default values where enum short names are used. 1140 for enum in other.enums: 1141 if not enum.options.long_names: 1142 for message in self.messages: 1143 for field in message.fields: 1144 if field.default in enum.value_longnames: 1145 idx = enum.value_longnames.index(field.default) 1146 field.default = enum.values[idx][0] 1147 1148 # Fix field data types where enums have negative values. 1149 for enum in other.enums: 1150 if not enum.has_negative(): 1151 for message in self.messages: 1152 for field in message.fields: 1153 if field.pbtype == 'ENUM' and field.ctype == enum.names: 1154 field.pbtype = 'UENUM' 1155 1156 def generate_header(self, includes, headername, options): 1157 '''Generate content for a header file. 1158 Generates strings, which should be concatenated and stored to file. 1159 ''' 1160 1161 yield '/* Automatically generated nanopb header */\n' 1162 if options.notimestamp: 1163 yield '/* Generated by %s */\n\n' % (nanopb_version) 1164 else: 1165 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime()) 1166 1167 if self.fdesc.package: 1168 symbol = make_identifier(self.fdesc.package + '_' + headername) 1169 else: 1170 symbol = make_identifier(headername) 1171 yield '#ifndef PB_%s_INCLUDED\n' % symbol 1172 yield '#define PB_%s_INCLUDED\n' % symbol 1173 try: 1174 yield options.libformat % ('pb.h') 1175 except TypeError: 1176 # no %s specified - use whatever was passed in as options.libformat 1177 yield options.libformat 1178 yield '\n' 1179 1180 for incfile in includes: 1181 noext = os.path.splitext(incfile)[0] 1182 yield options.genformat % (noext + options.extension + options.header_extension) 1183 yield '\n' 1184 1185 yield '/* @@protoc_insertion_point(includes) */\n' 1186 1187 yield '#if PB_PROTO_HEADER_VERSION != 30\n' 1188 yield '#error Regenerate this file with the current version of nanopb generator.\n' 1189 yield '#endif\n' 1190 yield '\n' 1191 1192 yield '#ifdef __cplusplus\n' 1193 yield 'extern "C" {\n' 1194 yield '#endif\n\n' 1195 1196 if self.enums: 1197 yield '/* Enum definitions */\n' 1198 for enum in self.enums: 1199 yield str(enum) + '\n\n' 1200 1201 if self.messages: 1202 yield '/* Struct definitions */\n' 1203 for msg in sort_dependencies(self.messages): 1204 yield msg.types() 1205 yield str(msg) + '\n\n' 1206 1207 if self.extensions: 1208 yield '/* Extensions */\n' 1209 for extension in self.extensions: 1210 yield extension.extension_decl() 1211 yield '\n' 1212 1213 if self.messages: 1214 yield '/* Default values for struct fields */\n' 1215 for msg in self.messages: 1216 yield msg.default_decl(True) 1217 yield '\n' 1218 1219 yield '/* Initializer values for message structs */\n' 1220 for msg in self.messages: 1221 identifier = '%s_init_default' % msg.name 1222 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False)) 1223 for msg in self.messages: 1224 identifier = '%s_init_zero' % msg.name 1225 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True)) 1226 yield '\n' 1227 1228 yield '/* Field tags (for use in manual encoding/decoding) */\n' 1229 for msg in sort_dependencies(self.messages): 1230 for field in msg.fields: 1231 yield field.tags() 1232 for extension in self.extensions: 1233 yield extension.tags() 1234 yield '\n' 1235 1236 yield '/* Struct field encoding specification for nanopb */\n' 1237 for msg in self.messages: 1238 yield msg.fields_declaration() + '\n' 1239 yield '\n' 1240 1241 yield '/* Maximum encoded size of messages (where known) */\n' 1242 for msg in self.messages: 1243 msize = msg.encoded_size(self.dependencies) 1244 identifier = '%s_size' % msg.name 1245 if msize is not None: 1246 yield '#define %-40s %s\n' % (identifier, msize) 1247 else: 1248 yield '/* %s depends on runtime parameters */\n' % identifier 1249 yield '\n' 1250 1251 yield '/* Message IDs (where set with "msgid" option) */\n' 1252 1253 yield '#ifdef PB_MSGID\n' 1254 for msg in self.messages: 1255 if hasattr(msg,'msgid'): 1256 yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name) 1257 yield '\n' 1258 1259 symbol = make_identifier(headername.split('.')[0]) 1260 yield '#define %s_MESSAGES \\\n' % symbol 1261 1262 for msg in self.messages: 1263 m = "-1" 1264 msize = msg.encoded_size(self.dependencies) 1265 if msize is not None: 1266 m = msize 1267 if hasattr(msg,'msgid'): 1268 yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name) 1269 yield '\n' 1270 1271 for msg in self.messages: 1272 if hasattr(msg,'msgid'): 1273 yield '#define %s_msgid %d\n' % (msg.name, msg.msgid) 1274 yield '\n' 1275 1276 yield '#endif\n\n' 1277 1278 yield '#ifdef __cplusplus\n' 1279 yield '} /* extern "C" */\n' 1280 yield '#endif\n' 1281 1282 # End of header 1283 yield '/* @@protoc_insertion_point(eof) */\n' 1284 yield '\n#endif\n' 1285 1286 def generate_source(self, headername, options): 1287 '''Generate content for a source file.''' 1288 1289 yield '/* Automatically generated nanopb constant definitions */\n' 1290 if options.notimestamp: 1291 yield '/* Generated by %s */\n\n' % (nanopb_version) 1292 else: 1293 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime()) 1294 yield options.genformat % (headername) 1295 yield '\n' 1296 yield '/* @@protoc_insertion_point(includes) */\n' 1297 1298 yield '#if PB_PROTO_HEADER_VERSION != 30\n' 1299 yield '#error Regenerate this file with the current version of nanopb generator.\n' 1300 yield '#endif\n' 1301 yield '\n' 1302 1303 for msg in self.messages: 1304 yield msg.default_decl(False) 1305 1306 yield '\n\n' 1307 1308 for msg in self.messages: 1309 yield msg.fields_definition() + '\n\n' 1310 1311 for ext in self.extensions: 1312 yield ext.extension_def() + '\n' 1313 1314 for enum in self.enums: 1315 yield enum.enum_to_string_definition() + '\n' 1316 1317 # Add checks for numeric limits 1318 if self.messages: 1319 largest_msg = max(self.messages, key = lambda m: m.count_required_fields()) 1320 largest_count = largest_msg.count_required_fields() 1321 if largest_count > 64: 1322 yield '\n/* Check that missing required fields will be properly detected */\n' 1323 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count 1324 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name 1325 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count 1326 yield '#endif\n' 1327 1328 max_field = FieldMaxSize() 1329 checks_msgnames = [] 1330 for msg in self.messages: 1331 checks_msgnames.append(msg.name) 1332 for field in msg.fields: 1333 max_field.extend(field.largest_field_value()) 1334 for field in self.extensions: 1335 max_field.extend(field.largest_field_value()) 1336 1337 worst = max_field.worst 1338 worst_field = max_field.worst_field 1339 checks = max_field.checks 1340 1341 if worst > 255 or checks: 1342 yield '\n/* Check that field information fits in pb_field_t */\n' 1343 1344 if worst > 65535 or checks: 1345 yield '#if !defined(PB_FIELD_32BIT)\n' 1346 if worst > 65535: 1347 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field 1348 else: 1349 assertion = ' && '.join(str(c) + ' < 65536' for c in checks) 1350 msgs = '_'.join(str(n) for n in checks_msgnames) 1351 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n' 1352 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n' 1353 yield ' * \n' 1354 yield ' * The reason you need to do this is that some of your messages contain tag\n' 1355 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n' 1356 yield ' * field descriptors.\n' 1357 yield ' */\n' 1358 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs) 1359 yield '#endif\n\n' 1360 1361 if worst < 65536: 1362 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n' 1363 if worst > 255: 1364 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field 1365 else: 1366 assertion = ' && '.join(str(c) + ' < 256' for c in checks) 1367 msgs = '_'.join(str(n) for n in checks_msgnames) 1368 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n' 1369 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n' 1370 yield ' * \n' 1371 yield ' * The reason you need to do this is that some of your messages contain tag\n' 1372 yield ' * numbers or field sizes that are larger than what can fit in the default\n' 1373 yield ' * 8 bit descriptors.\n' 1374 yield ' */\n' 1375 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs) 1376 yield '#endif\n\n' 1377 1378 # Add check for sizeof(double) 1379 has_double = False 1380 for msg in self.messages: 1381 for field in msg.fields: 1382 if field.ctype == 'double': 1383 has_double = True 1384 1385 if has_double: 1386 yield '\n' 1387 yield '/* On some platforms (such as AVR), double is really float.\n' 1388 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n' 1389 yield ' * To get rid of this error, remove any double fields from your .proto.\n' 1390 yield ' */\n' 1391 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n' 1392 1393 yield '\n' 1394 yield '/* @@protoc_insertion_point(eof) */\n' 1395 1396# --------------------------------------------------------------------------- 1397# Options parsing for the .proto files 1398# --------------------------------------------------------------------------- 1399 1400from fnmatch import fnmatch 1401 1402def read_options_file(infile): 1403 '''Parse a separate options file to list: 1404 [(namemask, options), ...] 1405 ''' 1406 results = [] 1407 data = infile.read() 1408 data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE) 1409 data = re.sub('//.*?$', '', data, flags = re.MULTILINE) 1410 data = re.sub('#.*?$', '', data, flags = re.MULTILINE) 1411 for i, line in enumerate(data.split('\n')): 1412 line = line.strip() 1413 if not line: 1414 continue 1415 1416 parts = line.split(None, 1) 1417 1418 if len(parts) < 2: 1419 sys.stderr.write("%s:%d: " % (infile.name, i + 1) + 1420 "Option lines should have space between field name and options. " + 1421 "Skipping line: '%s'\n" % line) 1422 continue 1423 1424 opts = nanopb_pb2.NanoPBOptions() 1425 1426 try: 1427 text_format.Merge(parts[1], opts) 1428 except Exception as e: 1429 sys.stderr.write("%s:%d: " % (infile.name, i + 1) + 1430 "Unparseable option line: '%s'. " % line + 1431 "Error: %s\n" % str(e)) 1432 continue 1433 results.append((parts[0], opts)) 1434 1435 return results 1436 1437class Globals: 1438 '''Ugly global variables, should find a good way to pass these.''' 1439 verbose_options = False 1440 separate_options = [] 1441 matched_namemasks = set() 1442 1443def get_nanopb_suboptions(subdesc, options, name): 1444 '''Get copy of options, and merge information from subdesc.''' 1445 new_options = nanopb_pb2.NanoPBOptions() 1446 new_options.CopyFrom(options) 1447 1448 if hasattr(subdesc, 'syntax') and subdesc.syntax == "proto3": 1449 new_options.proto3 = True 1450 1451 # Handle options defined in a separate file 1452 dotname = '.'.join(name.parts) 1453 for namemask, options in Globals.separate_options: 1454 if fnmatch(dotname, namemask): 1455 Globals.matched_namemasks.add(namemask) 1456 new_options.MergeFrom(options) 1457 1458 # Handle options defined in .proto 1459 if isinstance(subdesc.options, descriptor.FieldOptions): 1460 ext_type = nanopb_pb2.nanopb 1461 elif isinstance(subdesc.options, descriptor.FileOptions): 1462 ext_type = nanopb_pb2.nanopb_fileopt 1463 elif isinstance(subdesc.options, descriptor.MessageOptions): 1464 ext_type = nanopb_pb2.nanopb_msgopt 1465 elif isinstance(subdesc.options, descriptor.EnumOptions): 1466 ext_type = nanopb_pb2.nanopb_enumopt 1467 else: 1468 raise Exception("Unknown options type") 1469 1470 if subdesc.options.HasExtension(ext_type): 1471 ext = subdesc.options.Extensions[ext_type] 1472 new_options.MergeFrom(ext) 1473 1474 if Globals.verbose_options: 1475 sys.stderr.write("Options for " + dotname + ": ") 1476 sys.stderr.write(text_format.MessageToString(new_options) + "\n") 1477 1478 return new_options 1479 1480 1481# --------------------------------------------------------------------------- 1482# Command line interface 1483# --------------------------------------------------------------------------- 1484 1485import sys 1486import os.path 1487from optparse import OptionParser 1488 1489optparser = OptionParser( 1490 usage = "Usage: nanopb_generator.py [options] file.pb ...", 1491 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " + 1492 "Output will be written to file.pb.h and file.pb.c.") 1493optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[], 1494 help="Exclude file from generated #include list.") 1495optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb", 1496 help="Set extension to use instead of '.pb' for generated files. [default: %default]") 1497optparser.add_option("-H", "--header-extension", dest="header_extension", metavar="EXTENSION", default=".h", 1498 help="Set extension to use for generated header files. [default: %default]") 1499optparser.add_option("-S", "--source-extension", dest="source_extension", metavar="EXTENSION", default=".c", 1500 help="Set extension to use for generated source files. [default: %default]") 1501optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options", 1502 help="Set name of a separate generator options file.") 1503optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR", 1504 action="append", default = [], 1505 help="Search for .options files additionally in this path") 1506optparser.add_option("-D", "--output-dir", dest="output_dir", 1507 metavar="OUTPUTDIR", default=None, 1508 help="Output directory of .pb.h and .pb.c files") 1509optparser.add_option("-Q", "--generated-include-format", dest="genformat", 1510 metavar="FORMAT", default='#include "%s"\n', 1511 help="Set format string to use for including other .pb.h files. [default: %default]") 1512optparser.add_option("-L", "--library-include-format", dest="libformat", 1513 metavar="FORMAT", default='#include <%s>\n', 1514 help="Set format string to use for including the nanopb pb.h header. [default: %default]") 1515optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False, 1516 help="Don't add timestamp to .pb.h and .pb.c preambles") 1517optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False, 1518 help="Don't print anything except errors.") 1519optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, 1520 help="Print more information.") 1521optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[], 1522 help="Set generator option (max_size, max_count etc.).") 1523 1524def parse_file(filename, fdesc, options): 1525 '''Parse a single file. Returns a ProtoFile instance.''' 1526 toplevel_options = nanopb_pb2.NanoPBOptions() 1527 for s in options.settings: 1528 text_format.Merge(s, toplevel_options) 1529 1530 if not fdesc: 1531 data = open(filename, 'rb').read() 1532 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0] 1533 1534 # Check if there is a separate .options file 1535 had_abspath = False 1536 try: 1537 optfilename = options.options_file % os.path.splitext(filename)[0] 1538 except TypeError: 1539 # No %s specified, use the filename as-is 1540 optfilename = options.options_file 1541 had_abspath = True 1542 1543 paths = ['.'] + options.options_path 1544 for p in paths: 1545 if os.path.isfile(os.path.join(p, optfilename)): 1546 optfilename = os.path.join(p, optfilename) 1547 if options.verbose: 1548 sys.stderr.write('Reading options from ' + optfilename + '\n') 1549 Globals.separate_options = read_options_file(open(optfilename, "rU")) 1550 break 1551 else: 1552 # If we are given a full filename and it does not exist, give an error. 1553 # However, don't give error when we automatically look for .options file 1554 # with the same name as .proto. 1555 if options.verbose or had_abspath: 1556 sys.stderr.write('Options file not found: ' + optfilename + '\n') 1557 Globals.separate_options = [] 1558 1559 Globals.matched_namemasks = set() 1560 1561 # Parse the file 1562 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename])) 1563 f = ProtoFile(fdesc, file_options) 1564 f.optfilename = optfilename 1565 1566 return f 1567 1568def process_file(filename, fdesc, options, other_files = {}): 1569 '''Process a single file. 1570 filename: The full path to the .proto or .pb source file, as string. 1571 fdesc: The loaded FileDescriptorSet, or None to read from the input file. 1572 options: Command line options as they come from OptionsParser. 1573 1574 Returns a dict: 1575 {'headername': Name of header file, 1576 'headerdata': Data for the .h header file, 1577 'sourcename': Name of the source code file, 1578 'sourcedata': Data for the .c source code file 1579 } 1580 ''' 1581 f = parse_file(filename, fdesc, options) 1582 1583 # Provide dependencies if available 1584 for dep in f.fdesc.dependency: 1585 if dep in other_files: 1586 f.add_dependency(other_files[dep]) 1587 1588 # Decide the file names 1589 noext = os.path.splitext(filename)[0] 1590 headername = noext + options.extension + options.header_extension 1591 sourcename = noext + options.extension + options.source_extension 1592 headerbasename = os.path.basename(headername) 1593 1594 # List of .proto files that should not be included in the C header file 1595 # even if they are mentioned in the source .proto. 1596 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude 1597 includes = [d for d in f.fdesc.dependency if d not in excludes] 1598 1599 headerdata = ''.join(f.generate_header(includes, headerbasename, options)) 1600 sourcedata = ''.join(f.generate_source(headerbasename, options)) 1601 1602 # Check if there were any lines in .options that did not match a member 1603 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks] 1604 if unmatched and not options.quiet: 1605 sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: " 1606 + ', '.join(unmatched) + "\n") 1607 if not Globals.verbose_options: 1608 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n") 1609 1610 return {'headername': headername, 'headerdata': headerdata, 1611 'sourcename': sourcename, 'sourcedata': sourcedata} 1612 1613def main_cli(): 1614 '''Main function when invoked directly from the command line.''' 1615 1616 options, filenames = optparser.parse_args() 1617 1618 if not filenames: 1619 optparser.print_help() 1620 sys.exit(1) 1621 1622 if options.quiet: 1623 options.verbose = False 1624 1625 if options.output_dir and not os.path.exists(options.output_dir): 1626 optparser.print_help() 1627 sys.stderr.write("\noutput_dir does not exist: %s\n" % options.output_dir) 1628 sys.exit(1) 1629 1630 if options.verbose: 1631 sys.stderr.write('Google Python protobuf library imported from %s, version %s\n' 1632 % (google.protobuf.__file__, google.protobuf.__version__)) 1633 1634 Globals.verbose_options = options.verbose 1635 for filename in filenames: 1636 results = process_file(filename, None, options) 1637 1638 base_dir = options.output_dir or '' 1639 to_write = [ 1640 (os.path.join(base_dir, results['headername']), results['headerdata']), 1641 (os.path.join(base_dir, results['sourcename']), results['sourcedata']), 1642 ] 1643 1644 if not options.quiet: 1645 paths = " and ".join([x[0] for x in to_write]) 1646 sys.stderr.write("Writing to %s\n" % paths) 1647 1648 for path, data in to_write: 1649 with open(path, 'w') as f: 1650 f.write(data) 1651 1652def main_plugin(): 1653 '''Main function when invoked as a protoc plugin.''' 1654 1655 import io, sys 1656 if sys.platform == "win32": 1657 import os, msvcrt 1658 # Set stdin and stdout to binary mode 1659 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) 1660 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) 1661 1662 data = io.open(sys.stdin.fileno(), "rb").read() 1663 1664 request = plugin_pb2.CodeGeneratorRequest.FromString(data) 1665 1666 try: 1667 # Versions of Python prior to 2.7.3 do not support unicode 1668 # input to shlex.split(). Try to convert to str if possible. 1669 params = str(request.parameter) 1670 except UnicodeEncodeError: 1671 params = request.parameter 1672 1673 import shlex 1674 args = shlex.split(params) 1675 options, dummy = optparser.parse_args(args) 1676 1677 Globals.verbose_options = options.verbose 1678 1679 if options.verbose: 1680 sys.stderr.write('Google Python protobuf library imported from %s, version %s\n' 1681 % (google.protobuf.__file__, google.protobuf.__version__)) 1682 1683 response = plugin_pb2.CodeGeneratorResponse() 1684 1685 # Google's protoc does not currently indicate the full path of proto files. 1686 # Instead always add the main file path to the search dirs, that works for 1687 # the common case. 1688 import os.path 1689 options.options_path.append(os.path.dirname(request.file_to_generate[0])) 1690 1691 # Process any include files first, in order to have them 1692 # available as dependencies 1693 other_files = {} 1694 for fdesc in request.proto_file: 1695 other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options) 1696 1697 for filename in request.file_to_generate: 1698 for fdesc in request.proto_file: 1699 if fdesc.name == filename: 1700 results = process_file(filename, fdesc, options, other_files) 1701 1702 f = response.file.add() 1703 f.name = results['headername'] 1704 f.content = results['headerdata'] 1705 1706 f = response.file.add() 1707 f.name = results['sourcename'] 1708 f.content = results['sourcedata'] 1709 1710 io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString()) 1711 1712if __name__ == '__main__': 1713 # Check if we are running as a plugin under protoc 1714 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: 1715 main_plugin() 1716 else: 1717 main_cli() 1718