3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.3.4"
10 # Add some dummy imports to keep packaging tools happy.
11 import google, distutils.util # bbfreeze seems to need these
12 import pkg_resources # pyinstaller / protobuf 2.5 seem to need these
14 # Don't care, we will error out later if it is actually important.
18 import google.protobuf.text_format as text_format
19 import google.protobuf.descriptor_pb2 as descriptor
22 *************************************************************
23 *** Could not import the Google protobuf Python libraries ***
24 *** Try installing package 'python-protobuf' or similar. ***
25 *************************************************************
30 import proto.nanopb_pb2 as nanopb_pb2
31 import proto.plugin_pb2 as plugin_pb2
34 ********************************************************************
35 *** Failed to import the protocol definitions for generator. ***
36 *** You have to run 'make' in the nanopb/generator/proto folder. ***
37 ********************************************************************
41 # ---------------------------------------------------------------------------
42 # Generation of single fields
43 # ---------------------------------------------------------------------------
48 # Values are tuple (c type, pb type, encoded size, int_size_allowed)
49 FieldD = descriptor.FieldDescriptorProto
51 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1, False),
52 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8, False),
53 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4, False),
54 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8, False),
55 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4, False),
56 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10, True),
57 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10, True),
58 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4, False),
59 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8, False),
60 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5, True),
61 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10, True),
62 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5, True),
63 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10, True)
66 # Integer size overrides (from .proto settings)
68 nanopb_pb2.IS_8: 'int8_t',
69 nanopb_pb2.IS_16: 'int16_t',
70 nanopb_pb2.IS_32: 'int32_t',
71 nanopb_pb2.IS_64: 'int64_t',
75 '''Keeps a set of nested names and formats them to C identifier.'''
76 def __init__(self, parts = ()):
77 if isinstance(parts, Names):
79 self.parts = tuple(parts)
82 return '_'.join(self.parts)
84 def __add__(self, other):
85 if isinstance(other, (str, unicode)):
86 return Names(self.parts + (other,))
87 elif isinstance(other, tuple):
88 return Names(self.parts + other)
90 raise ValueError("Name parts should be of type str")
92 def __eq__(self, other):
93 return isinstance(other, Names) and self.parts == other.parts
95 def names_from_type_name(type_name):
96 '''Parse Names() from FieldDescriptorProto type_name'''
97 if type_name[0] != '.':
98 raise NotImplementedError("Lookup of non-absolute type names is not supported")
99 return Names(type_name[1:].split('.'))
101 def varint_max_size(max_value):
102 '''Returns the maximum number of bytes a varint can take when encoded.'''
104 max_value = 2**64 - max_value
105 for i in range(1, 11):
106 if (max_value >> (i * 7)) == 0:
108 raise ValueError("Value too large for varint: " + str(max_value))
110 assert varint_max_size(-1) == 10
111 assert varint_max_size(0) == 1
112 assert varint_max_size(127) == 1
113 assert varint_max_size(128) == 2
116 '''Class used to represent the encoded size of a field or a message.
117 Consists of a combination of symbolic sizes and integer sizes.'''
118 def __init__(self, value = 0, symbols = []):
119 if isinstance(value, (str, Names)):
120 symbols = [str(value)]
123 self.symbols = symbols
125 def __add__(self, other):
126 if isinstance(other, (int, long)):
127 return EncodedSize(self.value + other, self.symbols)
128 elif isinstance(other, (str, Names)):
129 return EncodedSize(self.value, self.symbols + [str(other)])
130 elif isinstance(other, EncodedSize):
131 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
133 raise ValueError("Cannot add size: " + repr(other))
135 def __mul__(self, other):
136 if isinstance(other, (int, long)):
137 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
139 raise ValueError("Cannot multiply size: " + repr(other))
143 return str(self.value)
145 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
147 def upperlimit(self):
154 def __init__(self, names, desc, enum_options):
155 '''desc is EnumDescriptorProto'''
157 self.options = enum_options
158 self.names = names + desc.name
160 if enum_options.long_names:
161 self.values = [(self.names + x.name, x.number) for x in desc.value]
163 self.values = [(names + x.name, x.number) for x in desc.value]
165 self.value_longnames = [self.names + x.name for x in desc.value]
166 self.packed = enum_options.packed_enum
168 def has_negative(self):
169 for n, v in self.values:
174 def encoded_size(self):
175 return max([varint_max_size(v) for n,v in self.values])
178 result = 'typedef enum _%s {\n' % self.names
179 result += ',\n'.join([" %s = %d" % x for x in self.values])
183 result += ' pb_packed'
185 result += ' %s;' % self.names
187 if not self.options.long_names:
188 # Define the long names always so that enum value references
189 # from other files work properly.
190 for i, x in enumerate(self.values):
191 result += '\n#define %s %s' % (self.value_longnames[i], x[0])
196 def __init__(self, struct_name, desc, field_options):
197 '''desc is FieldDescriptorProto'''
198 self.tag = desc.number
199 self.struct_name = struct_name
200 self.union_name = None
201 self.name = desc.name
204 self.max_count = None
209 # Parse field options
210 if field_options.HasField("max_size"):
211 self.max_size = field_options.max_size
213 if field_options.HasField("max_count"):
214 self.max_count = field_options.max_count
216 if desc.HasField('default_value'):
217 self.default = desc.default_value
219 # Check field rules, i.e. required/optional/repeated.
221 if desc.label == FieldD.LABEL_REQUIRED:
222 self.rules = 'REQUIRED'
223 elif desc.label == FieldD.LABEL_OPTIONAL:
224 self.rules = 'OPTIONAL'
225 elif desc.label == FieldD.LABEL_REPEATED:
226 self.rules = 'REPEATED'
227 if self.max_count is None:
228 can_be_static = False
230 self.array_decl = '[%d]' % self.max_count
232 raise NotImplementedError(desc.label)
234 # Check if the field can be implemented with static allocation
235 # i.e. whether the data size is known.
236 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
237 can_be_static = False
239 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
240 can_be_static = False
242 # Decide how the field data will be allocated
243 if field_options.type == nanopb_pb2.FT_DEFAULT:
245 field_options.type = nanopb_pb2.FT_STATIC
247 field_options.type = nanopb_pb2.FT_CALLBACK
249 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
250 raise Exception("Field %s is defined as static, but max_size or "
251 "max_count is not given." % self.name)
253 if field_options.type == nanopb_pb2.FT_STATIC:
254 self.allocation = 'STATIC'
255 elif field_options.type == nanopb_pb2.FT_POINTER:
256 self.allocation = 'POINTER'
257 elif field_options.type == nanopb_pb2.FT_CALLBACK:
258 self.allocation = 'CALLBACK'
260 raise NotImplementedError(field_options.type)
262 # Decide the C data type to use in the struct.
263 if datatypes.has_key(desc.type):
264 self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
266 # Override the field size if user wants to use smaller integers
267 if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
268 self.ctype = intsizes[field_options.int_size]
269 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
270 self.ctype = 'u' + self.ctype;
271 elif desc.type == FieldD.TYPE_ENUM:
273 self.ctype = names_from_type_name(desc.type_name)
274 if self.default is not None:
275 self.default = self.ctype + self.default
276 self.enc_size = None # Needs to be filled in when enum values are known
277 elif desc.type == FieldD.TYPE_STRING:
278 self.pbtype = 'STRING'
280 if self.allocation == 'STATIC':
282 self.array_decl += '[%d]' % self.max_size
283 self.enc_size = varint_max_size(self.max_size) + self.max_size
284 elif desc.type == FieldD.TYPE_BYTES:
285 self.pbtype = 'BYTES'
286 if self.allocation == 'STATIC':
287 self.ctype = self.struct_name + self.name + 't'
288 self.enc_size = varint_max_size(self.max_size) + self.max_size
289 elif self.allocation == 'POINTER':
290 self.ctype = 'pb_bytes_array_t'
291 elif desc.type == FieldD.TYPE_MESSAGE:
292 self.pbtype = 'MESSAGE'
293 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
294 self.enc_size = None # Needs to be filled in after the message type is available
296 raise NotImplementedError(desc.type)
298 def __cmp__(self, other):
299 return cmp(self.tag, other.tag)
303 if self.allocation == 'POINTER':
304 if self.rules == 'REPEATED':
305 result += ' pb_size_t ' + self.name + '_count;\n'
307 if self.pbtype == 'MESSAGE':
308 # Use struct definition, so recursive submessages are possible
309 result += ' struct _%s *%s;' % (self.ctype, self.name)
310 elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
311 # String/bytes arrays need to be defined as pointers to pointers
312 result += ' %s **%s;' % (self.ctype, self.name)
314 result += ' %s *%s;' % (self.ctype, self.name)
315 elif self.allocation == 'CALLBACK':
316 result += ' pb_callback_t %s;' % self.name
318 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
319 result += ' bool has_' + self.name + ';\n'
320 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
321 result += ' pb_size_t ' + self.name + '_count;\n'
322 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
326 '''Return definitions for any special types this field might need.'''
327 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
328 result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
333 def get_dependencies(self):
334 '''Get list of type names used by this field.'''
335 if self.allocation == 'STATIC':
336 return [str(self.ctype)]
340 def get_initializer(self, null_init, inner_init_only = False):
341 '''Return literal expression for this field's default value.
342 null_init: If True, initialize to a 0 value instead of default from .proto
343 inner_init_only: If True, exclude initialization for any count/has fields
347 if self.pbtype == 'MESSAGE':
349 inner_init = '%s_init_zero' % self.ctype
351 inner_init = '%s_init_default' % self.ctype
352 elif self.default is None or null_init:
353 if self.pbtype == 'STRING':
355 elif self.pbtype == 'BYTES':
356 inner_init = '{0, {0}}'
357 elif self.pbtype in ('ENUM', 'UENUM'):
358 inner_init = '(%s)0' % self.ctype
362 if self.pbtype == 'STRING':
363 inner_init = self.default.encode('utf-8').encode('string_escape')
364 inner_init = inner_init.replace('"', '\\"')
365 inner_init = '"' + inner_init + '"'
366 elif self.pbtype == 'BYTES':
367 data = str(self.default).decode('string_escape')
368 data = ['0x%02x' % ord(c) for c in data]
370 inner_init = '{0, {0}}'
372 inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
373 elif self.pbtype in ['FIXED32', 'UINT32']:
374 inner_init = str(self.default) + 'u'
375 elif self.pbtype in ['FIXED64', 'UINT64']:
376 inner_init = str(self.default) + 'ull'
377 elif self.pbtype in ['SFIXED64', 'INT64']:
378 inner_init = str(self.default) + 'll'
380 inner_init = str(self.default)
386 if self.allocation == 'STATIC':
387 if self.rules == 'REPEATED':
389 outer_init += ', '.join([inner_init] * self.max_count)
391 elif self.rules == 'OPTIONAL':
392 outer_init = 'false, ' + inner_init
394 outer_init = inner_init
395 elif self.allocation == 'POINTER':
396 if self.rules == 'REPEATED':
397 outer_init = '0, NULL'
400 elif self.allocation == 'CALLBACK':
401 if self.pbtype == 'EXTENSION':
404 outer_init = '{{NULL}, NULL}'
408 def default_decl(self, declaration_only = False):
409 '''Return definition for this field's default value.'''
410 if self.default is None:
414 default = self.get_initializer(False, True)
417 if self.pbtype == 'STRING':
418 if self.allocation != 'STATIC':
419 return None # Not implemented
420 array_decl = '[%d]' % self.max_size
421 elif self.pbtype == 'BYTES':
422 if self.allocation != 'STATIC':
423 return None # Not implemented
426 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
428 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
431 '''Return the #define for the tag number of this field.'''
432 identifier = '%s_%s_tag' % (self.struct_name, self.name)
433 return '#define %-40s %d\n' % (identifier, self.tag)
435 def pb_field_t(self, prev_field_name):
436 '''Return the pb_field_t initializer to use in the constant array.
437 prev_field_name is the name of the previous field or None.
440 if self.rules == 'ONEOF':
441 result = ' PB_ONEOF_FIELD(%s, ' % self.union_name
443 result = ' PB_FIELD('
445 result += '%3d, ' % self.tag
446 result += '%-8s, ' % self.pbtype
447 result += '%s, ' % self.rules
448 result += '%-8s, ' % self.allocation
449 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
450 result += '%s, ' % self.struct_name
451 result += '%s, ' % self.name
452 result += '%s, ' % (prev_field_name or self.name)
454 if self.pbtype == 'MESSAGE':
455 result += '&%s_fields)' % self.submsgname
456 elif self.default is None:
458 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
459 result += '0)' # Arbitrary size default values not implemented
460 elif self.rules == 'OPTEXT':
461 result += '0)' # Default value for extensions is not implemented
463 result += '&%s_default)' % (self.struct_name + self.name)
467 def largest_field_value(self):
468 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
469 Returns numeric value or a C-expression for assert.'''
470 if self.pbtype == 'MESSAGE':
471 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
472 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
473 elif self.rules == 'ONEOF':
474 return 'pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name)
476 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
478 return max(self.tag, self.max_size, self.max_count)
480 def encoded_size(self, dependencies):
481 '''Return the maximum size that this field can take when encoded,
482 including the field tag. If the size cannot be determined, returns
485 if self.allocation != 'STATIC':
488 if self.pbtype == 'MESSAGE':
489 if str(self.submsgname) in dependencies:
490 submsg = dependencies[str(self.submsgname)]
491 encsize = submsg.encoded_size(dependencies)
493 return None # Submessage size is indeterminate
495 # Include submessage length prefix
496 encsize += varint_max_size(encsize.upperlimit())
498 # Submessage cannot be found, this currently occurs when
499 # the submessage type is defined in a different file and
500 # not using the protoc plugin.
501 # Instead of direct numeric value, reference the size that
502 # has been #defined in the other file.
503 encsize = EncodedSize(self.submsgname + 'size')
505 # We will have to make a conservative assumption on the length
506 # prefix size, though.
509 elif self.pbtype in ['ENUM', 'UENUM']:
510 if str(self.ctype) in dependencies:
511 enumtype = dependencies[str(self.ctype)]
512 encsize = enumtype.encoded_size()
514 # Conservative assumption
517 elif self.enc_size is None:
518 raise RuntimeError("Could not determine encoded size for %s.%s"
519 % (self.struct_name, self.name))
521 encsize = EncodedSize(self.enc_size)
523 encsize += varint_max_size(self.tag << 3) # Tag + wire type
525 if self.rules == 'REPEATED':
526 # Decoders must be always able to handle unpacked arrays.
527 # Therefore we have to reserve space for it, even though
528 # we emit packed arrays ourselves.
529 encsize *= self.max_count
534 class ExtensionRange(Field):
535 def __init__(self, struct_name, range_start, field_options):
536 '''Implements a special pb_extension_t* field in an extensible message
537 structure. The range_start signifies the index at which the extensions
538 start. Not necessarily all tags above this are extensions, it is merely
539 a speed optimization.
541 self.tag = range_start
542 self.struct_name = struct_name
543 self.name = 'extensions'
544 self.pbtype = 'EXTENSION'
545 self.rules = 'OPTIONAL'
546 self.allocation = 'CALLBACK'
547 self.ctype = 'pb_extension_t'
554 return ' pb_extension_t *extensions;'
562 def encoded_size(self, dependencies):
563 # We exclude extensions from the count, because they cannot be known
564 # until runtime. Other option would be to return None here, but this
565 # way the value remains useful if extensions are not used.
566 return EncodedSize(0)
568 class ExtensionField(Field):
569 def __init__(self, struct_name, desc, field_options):
570 self.fullname = struct_name + desc.name
571 self.extendee_name = names_from_type_name(desc.extendee)
572 Field.__init__(self, self.fullname + 'struct', desc, field_options)
574 if self.rules != 'OPTIONAL':
578 self.rules = 'OPTEXT'
581 '''Return the #define for the tag number of this field.'''
582 identifier = '%s_tag' % self.fullname
583 return '#define %-40s %d\n' % (identifier, self.tag)
585 def extension_decl(self):
586 '''Declaration of the extension type in the .pb.h file'''
588 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
589 msg +=' type of extension fields is currently supported. */\n'
592 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
593 (self.fullname, str(self).strip()))
595 def extension_def(self):
596 '''Definition of the extension type in the .pb.c file'''
601 result = 'typedef struct {\n'
603 result += '\n} %s;\n\n' % self.struct_name
604 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
605 (self.fullname, self.pb_field_t(None)))
606 result += 'const pb_extension_type_t %s = {\n' % self.fullname
609 result += ' &%s_field\n' % self.fullname
614 # ---------------------------------------------------------------------------
615 # Generation of oneofs (unions)
616 # ---------------------------------------------------------------------------
619 def __init__(self, struct_name, oneof_desc):
620 self.struct_name = struct_name
621 self.name = oneof_desc.name
623 self.pbtype = 'oneof'
625 self.allocation = 'ONEOF'
629 def add_field(self, field):
630 if field.allocation == 'CALLBACK':
631 raise Exception("Callback fields inside of oneof are not supported"
632 + " (field %s)" % field.name)
634 field.union_name = self.name
635 field.rules = 'ONEOF'
636 self.fields.append(field)
637 self.fields.sort(key = lambda f: f.tag)
639 # Sort by the lowest tag number inside union
640 self.tag = min([f.tag for f in self.fields])
642 def __cmp__(self, other):
643 return cmp(self.tag, other.tag)
648 result += ' pb_size_t which_' + self.name + ";\n"
649 result += ' union {\n'
650 for f in self.fields:
651 result += ' ' + str(f).replace('\n', '\n ') + '\n'
652 result += ' } ' + self.name + ';'
656 return ''.join([f.types() for f in self.fields])
658 def get_dependencies(self):
660 for f in self.fields:
661 deps += f.get_dependencies()
664 def get_initializer(self, null_init):
665 return '0, {' + self.fields[0].get_initializer(null_init) + '}'
667 def default_decl(self, declaration_only = False):
671 return '\n'.join([f.tags() for f in self.fields])
673 def pb_field_t(self, prev_field_name):
674 result = ',\n'.join([f.pb_field_t(prev_field_name) for f in self.fields])
677 def largest_field_value(self):
678 return max([f.largest_field_value() for f in self.fields])
680 def encoded_size(self, dependencies):
681 largest = EncodedSize(0)
682 for f in self.fields:
683 size = f.encoded_size(dependencies)
687 return None # Cannot resolve maximum of symbols
688 elif size.value > largest.value:
693 # ---------------------------------------------------------------------------
694 # Generation of messages (structures)
695 # ---------------------------------------------------------------------------
699 def __init__(self, names, desc, message_options):
705 if message_options.msgid:
706 self.msgid = message_options.msgid
708 if hasattr(desc, 'oneof_decl'):
709 for i, f in enumerate(desc.oneof_decl):
710 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
711 if oneof_options.no_unions:
712 no_unions.append(i) # No union, but add fields normally
713 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
714 pass # No union and skip fields also
716 oneof = OneOf(self.name, f)
717 self.oneofs[i] = oneof
718 self.fields.append(oneof)
721 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
722 if field_options.type == nanopb_pb2.FT_IGNORE:
725 field = Field(self.name, f, field_options)
726 if (hasattr(f, 'oneof_index') and
727 f.HasField('oneof_index') and
728 f.oneof_index not in no_unions):
729 if f.oneof_index in self.oneofs:
730 self.oneofs[f.oneof_index].add_field(field)
732 self.fields.append(field)
734 if len(desc.extension_range) > 0:
735 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
736 range_start = min([r.start for r in desc.extension_range])
737 if field_options.type != nanopb_pb2.FT_IGNORE:
738 self.fields.append(ExtensionRange(self.name, range_start, field_options))
740 self.packed = message_options.packed_struct
741 self.ordered_fields = self.fields[:]
742 self.ordered_fields.sort()
744 def get_dependencies(self):
745 '''Get list of type names that this structure refers to.'''
747 for f in self.fields:
748 deps += f.get_dependencies()
752 result = 'typedef struct _%s {\n' % self.name
754 if not self.ordered_fields:
755 # Empty structs are not allowed in C standard.
756 # Therefore add a dummy field if an empty message occurs.
757 result += ' uint8_t dummy_field;'
759 result += '\n'.join([str(f) for f in self.ordered_fields])
763 result += ' pb_packed'
765 result += ' %s;' % self.name
768 result = 'PB_PACKED_STRUCT_START\n' + result
769 result += '\nPB_PACKED_STRUCT_END'
774 return ''.join([f.types() for f in self.fields])
776 def get_initializer(self, null_init):
777 if not self.ordered_fields:
781 for field in self.ordered_fields:
782 parts.append(field.get_initializer(null_init))
783 return '{' + ', '.join(parts) + '}'
785 def default_decl(self, declaration_only = False):
787 for field in self.fields:
788 default = field.default_decl(declaration_only)
789 if default is not None:
790 result += default + '\n'
793 def count_required_fields(self):
794 '''Returns number of required fields inside this message'''
796 for f in self.fields:
797 if not isinstance(f, OneOf):
798 if f.rules == 'REQUIRED':
802 def count_all_fields(self):
804 for f in self.fields:
805 if isinstance(f, OneOf):
806 count += len(f.fields)
811 def fields_declaration(self):
812 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
815 def fields_definition(self):
816 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
819 for field in self.ordered_fields:
820 result += field.pb_field_t(prev)
822 if isinstance(field, OneOf):
823 prev = field.name + '.' + field.fields[-1].name
827 result += ' PB_LAST_FIELD\n};'
830 def encoded_size(self, dependencies):
831 '''Return the maximum size that this message can take when encoded.
832 If the size cannot be determined, returns None.
834 size = EncodedSize(0)
835 for field in self.fields:
836 fsize = field.encoded_size(dependencies)
844 # ---------------------------------------------------------------------------
845 # Processing of entire .proto files
846 # ---------------------------------------------------------------------------
848 def iterate_messages(desc, names = Names()):
849 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
850 if hasattr(desc, 'message_type'):
851 submsgs = desc.message_type
853 submsgs = desc.nested_type
855 for submsg in submsgs:
856 sub_names = names + submsg.name
857 yield sub_names, submsg
859 for x in iterate_messages(submsg, sub_names):
862 def iterate_extensions(desc, names = Names()):
863 '''Recursively find all extensions.
864 For each, yield name, FieldDescriptorProto.
866 for extension in desc.extension:
867 yield names, extension
869 for subname, subdesc in iterate_messages(desc, names):
870 for extension in subdesc.extension:
871 yield subname, extension
875 From http://code.activestate.com/recipes/577413-topological-sort/
876 This function is under the MIT license.
878 for k, v in data.items():
879 v.discard(k) # Ignore self dependencies
880 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
881 data.update(dict([(item, set()) for item in extra_items_in_deps]))
883 ordered = set(item for item,dep in data.items() if not dep)
886 for item in sorted(ordered):
888 data = dict([(item, (dep - ordered)) for item,dep in data.items()
889 if item not in ordered])
890 assert not data, "A cyclic dependency exists amongst %r" % data
892 def sort_dependencies(messages):
893 '''Sort a list of Messages based on dependencies.'''
896 for message in messages:
897 dependencies[str(message.name)] = set(message.get_dependencies())
898 message_by_name[str(message.name)] = message
900 for msgname in toposort2(dependencies):
901 if msgname in message_by_name:
902 yield message_by_name[msgname]
904 def make_identifier(headername):
905 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
907 for c in headername.upper():
915 def __init__(self, fdesc, file_options):
916 '''Takes a FileDescriptorProto and parses it.'''
918 self.file_options = file_options
919 self.dependencies = {}
922 # Some of types used in this file probably come from the file itself.
923 # Thus it has implicit dependency on itself.
924 self.add_dependency(self)
931 if self.fdesc.package:
932 base_name = Names(self.fdesc.package.split('.'))
936 for enum in self.fdesc.enum_type:
937 enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
938 self.enums.append(Enum(base_name, enum, enum_options))
940 for names, message in iterate_messages(self.fdesc, base_name):
941 message_options = get_nanopb_suboptions(message, self.file_options, names)
943 if message_options.skip_message:
946 self.messages.append(Message(names, message, message_options))
947 for enum in message.enum_type:
948 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
949 self.enums.append(Enum(names, enum, enum_options))
951 for names, extension in iterate_extensions(self.fdesc, base_name):
952 field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
953 if field_options.type != nanopb_pb2.FT_IGNORE:
954 self.extensions.append(ExtensionField(names, extension, field_options))
956 def add_dependency(self, other):
957 for enum in other.enums:
958 self.dependencies[str(enum.names)] = enum
960 for msg in other.messages:
961 self.dependencies[str(msg.name)] = msg
963 # Fix field default values where enum short names are used.
964 for enum in other.enums:
965 if not enum.options.long_names:
966 for message in self.messages:
967 for field in message.fields:
968 if field.default in enum.value_longnames:
969 idx = enum.value_longnames.index(field.default)
970 field.default = enum.values[idx][0]
972 # Fix field data types where enums have negative values.
973 for enum in other.enums:
974 if not enum.has_negative():
975 for message in self.messages:
976 for field in message.fields:
977 if field.pbtype == 'ENUM' and field.ctype == enum.names:
978 field.pbtype = 'UENUM'
980 def generate_header(self, includes, headername, options):
981 '''Generate content for a header file.
982 Generates strings, which should be concatenated and stored to file.
985 yield '/* Automatically generated nanopb header */\n'
986 if options.notimestamp:
987 yield '/* Generated by %s */\n\n' % (nanopb_version)
989 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
991 symbol = make_identifier(headername)
992 yield '#ifndef PB_%s_INCLUDED\n' % symbol
993 yield '#define PB_%s_INCLUDED\n' % symbol
995 yield options.libformat % ('pb.h')
997 # no %s specified - use whatever was passed in as options.libformat
998 yield options.libformat
1001 for incfile in includes:
1002 noext = os.path.splitext(incfile)[0]
1003 yield options.genformat % (noext + options.extension + '.h')
1006 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1007 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1011 yield '#ifdef __cplusplus\n'
1012 yield 'extern "C" {\n'
1016 yield '/* Enum definitions */\n'
1017 for enum in self.enums:
1018 yield str(enum) + '\n\n'
1021 yield '/* Struct definitions */\n'
1022 for msg in sort_dependencies(self.messages):
1024 yield str(msg) + '\n\n'
1027 yield '/* Extensions */\n'
1028 for extension in self.extensions:
1029 yield extension.extension_decl()
1033 yield '/* Default values for struct fields */\n'
1034 for msg in self.messages:
1035 yield msg.default_decl(True)
1038 yield '/* Initializer values for message structs */\n'
1039 for msg in self.messages:
1040 identifier = '%s_init_default' % msg.name
1041 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1042 for msg in self.messages:
1043 identifier = '%s_init_zero' % msg.name
1044 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1047 yield '/* Field tags (for use in manual encoding/decoding) */\n'
1048 for msg in sort_dependencies(self.messages):
1049 for field in msg.fields:
1051 for extension in self.extensions:
1052 yield extension.tags()
1055 yield '/* Struct field encoding specification for nanopb */\n'
1056 for msg in self.messages:
1057 yield msg.fields_declaration() + '\n'
1060 yield '/* Maximum encoded size of messages (where known) */\n'
1061 for msg in self.messages:
1062 msize = msg.encoded_size(self.dependencies)
1063 if msize is not None:
1064 identifier = '%s_size' % msg.name
1065 yield '#define %-40s %s\n' % (identifier, msize)
1068 yield '/* Message IDs (where set with "msgid" option) */\n'
1070 yield '#ifdef PB_MSGID\n'
1071 for msg in self.messages:
1072 if hasattr(msg,'msgid'):
1073 yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1076 symbol = make_identifier(headername.split('.')[0])
1077 yield '#define %s_MESSAGES \\\n' % symbol
1079 for msg in self.messages:
1081 msize = msg.encoded_size(self.dependencies)
1082 if msize is not None:
1084 if hasattr(msg,'msgid'):
1085 yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1088 for msg in self.messages:
1089 if hasattr(msg,'msgid'):
1090 yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1095 yield '#ifdef __cplusplus\n'
1096 yield '} /* extern "C" */\n'
1102 def generate_source(self, headername, options):
1103 '''Generate content for a source file.'''
1105 yield '/* Automatically generated nanopb constant definitions */\n'
1106 if options.notimestamp:
1107 yield '/* Generated by %s */\n\n' % (nanopb_version)
1109 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1110 yield options.genformat % (headername)
1113 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1114 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1118 for msg in self.messages:
1119 yield msg.default_decl(False)
1123 for msg in self.messages:
1124 yield msg.fields_definition() + '\n\n'
1126 for ext in self.extensions:
1127 yield ext.extension_def() + '\n'
1129 # Add checks for numeric limits
1131 largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1132 largest_count = largest_msg.count_required_fields()
1133 if largest_count > 64:
1134 yield '\n/* Check that missing required fields will be properly detected */\n'
1135 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1136 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1137 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1143 checks_msgnames = []
1144 for msg in self.messages:
1145 checks_msgnames.append(msg.name)
1146 for field in msg.fields:
1147 status = field.largest_field_value()
1148 if isinstance(status, (str, unicode)):
1149 checks.append(status)
1150 elif status > worst:
1152 worst_field = str(field.struct_name) + '.' + str(field.name)
1154 if worst > 255 or checks:
1155 yield '\n/* Check that field information fits in pb_field_t */\n'
1157 if worst > 65535 or checks:
1158 yield '#if !defined(PB_FIELD_32BIT)\n'
1160 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1162 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1163 msgs = '_'.join(str(n) for n in checks_msgnames)
1164 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1165 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1167 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1168 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1169 yield ' * field descriptors.\n'
1171 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1175 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1177 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1179 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1180 msgs = '_'.join(str(n) for n in checks_msgnames)
1181 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1182 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1184 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1185 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1186 yield ' * 8 bit descriptors.\n'
1188 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1191 # Add check for sizeof(double)
1193 for msg in self.messages:
1194 for field in msg.fields:
1195 if field.ctype == 'double':
1200 yield '/* On some platforms (such as AVR), double is really float.\n'
1201 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1202 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1204 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1208 # ---------------------------------------------------------------------------
1209 # Options parsing for the .proto files
1210 # ---------------------------------------------------------------------------
1212 from fnmatch import fnmatch
1214 def read_options_file(infile):
1215 '''Parse a separate options file to list:
1216 [(namemask, options), ...]
1219 data = infile.read()
1220 data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1221 data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1222 data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1223 for i, line in enumerate(data.split('\n')):
1228 parts = line.split(None, 1)
1231 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1232 "Option lines should have space between field name and options. " +
1233 "Skipping line: '%s'\n" % line)
1236 opts = nanopb_pb2.NanoPBOptions()
1239 text_format.Merge(parts[1], opts)
1240 except Exception, e:
1241 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1242 "Unparseable option line: '%s'. " % line +
1243 "Error: %s\n" % str(e))
1245 results.append((parts[0], opts))
1250 '''Ugly global variables, should find a good way to pass these.'''
1251 verbose_options = False
1252 separate_options = []
1253 matched_namemasks = set()
1255 def get_nanopb_suboptions(subdesc, options, name):
1256 '''Get copy of options, and merge information from subdesc.'''
1257 new_options = nanopb_pb2.NanoPBOptions()
1258 new_options.CopyFrom(options)
1260 # Handle options defined in a separate file
1261 dotname = '.'.join(name.parts)
1262 for namemask, options in Globals.separate_options:
1263 if fnmatch(dotname, namemask):
1264 Globals.matched_namemasks.add(namemask)
1265 new_options.MergeFrom(options)
1267 # Handle options defined in .proto
1268 if isinstance(subdesc.options, descriptor.FieldOptions):
1269 ext_type = nanopb_pb2.nanopb
1270 elif isinstance(subdesc.options, descriptor.FileOptions):
1271 ext_type = nanopb_pb2.nanopb_fileopt
1272 elif isinstance(subdesc.options, descriptor.MessageOptions):
1273 ext_type = nanopb_pb2.nanopb_msgopt
1274 elif isinstance(subdesc.options, descriptor.EnumOptions):
1275 ext_type = nanopb_pb2.nanopb_enumopt
1277 raise Exception("Unknown options type")
1279 if subdesc.options.HasExtension(ext_type):
1280 ext = subdesc.options.Extensions[ext_type]
1281 new_options.MergeFrom(ext)
1283 if Globals.verbose_options:
1284 sys.stderr.write("Options for " + dotname + ": ")
1285 sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1290 # ---------------------------------------------------------------------------
1291 # Command line interface
1292 # ---------------------------------------------------------------------------
1296 from optparse import OptionParser
1298 optparser = OptionParser(
1299 usage = "Usage: nanopb_generator.py [options] file.pb ...",
1300 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1301 "Output will be written to file.pb.h and file.pb.c.")
1302 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1303 help="Exclude file from generated #include list.")
1304 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1305 help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1306 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1307 help="Set name of a separate generator options file.")
1308 optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR",
1309 action="append", default = [],
1310 help="Search for .options files additionally in this path")
1311 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1312 metavar="FORMAT", default='#include "%s"\n',
1313 help="Set format string to use for including other .pb.h files. [default: %default]")
1314 optparser.add_option("-L", "--library-include-format", dest="libformat",
1315 metavar="FORMAT", default='#include <%s>\n',
1316 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1317 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1318 help="Don't add timestamp to .pb.h and .pb.c preambles")
1319 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1320 help="Don't print anything except errors.")
1321 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1322 help="Print more information.")
1323 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1324 help="Set generator option (max_size, max_count etc.).")
1326 def parse_file(filename, fdesc, options):
1327 '''Parse a single file. Returns a ProtoFile instance.'''
1328 toplevel_options = nanopb_pb2.NanoPBOptions()
1329 for s in options.settings:
1330 text_format.Merge(s, toplevel_options)
1333 data = open(filename, 'rb').read()
1334 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1336 # Check if there is a separate .options file
1339 optfilename = options.options_file % os.path.splitext(filename)[0]
1341 # No %s specified, use the filename as-is
1342 optfilename = options.options_file
1345 paths = ['.'] + options.options_path
1347 if os.path.isfile(os.path.join(p, optfilename)):
1348 optfilename = os.path.join(p, optfilename)
1350 sys.stderr.write('Reading options from ' + optfilename + '\n')
1351 Globals.separate_options = read_options_file(open(optfilename, "rU"))
1354 # If we are given a full filename and it does not exist, give an error.
1355 # However, don't give error when we automatically look for .options file
1356 # with the same name as .proto.
1357 if options.verbose or had_abspath:
1358 sys.stderr.write('Options file not found: ' + optfilename + '\n')
1359 Globals.separate_options = []
1361 Globals.matched_namemasks = set()
1364 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1365 f = ProtoFile(fdesc, file_options)
1366 f.optfilename = optfilename
1370 def process_file(filename, fdesc, options, other_files = {}):
1371 '''Process a single file.
1372 filename: The full path to the .proto or .pb source file, as string.
1373 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1374 options: Command line options as they come from OptionsParser.
1377 {'headername': Name of header file,
1378 'headerdata': Data for the .h header file,
1379 'sourcename': Name of the source code file,
1380 'sourcedata': Data for the .c source code file
1383 f = parse_file(filename, fdesc, options)
1385 # Provide dependencies if available
1386 for dep in f.fdesc.dependency:
1387 if dep in other_files:
1388 f.add_dependency(other_files[dep])
1390 # Decide the file names
1391 noext = os.path.splitext(filename)[0]
1392 headername = noext + options.extension + '.h'
1393 sourcename = noext + options.extension + '.c'
1394 headerbasename = os.path.basename(headername)
1396 # List of .proto files that should not be included in the C header file
1397 # even if they are mentioned in the source .proto.
1398 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1399 includes = [d for d in f.fdesc.dependency if d not in excludes]
1401 headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1402 sourcedata = ''.join(f.generate_source(headerbasename, options))
1404 # Check if there were any lines in .options that did not match a member
1405 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1406 if unmatched and not options.quiet:
1407 sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: "
1408 + ', '.join(unmatched) + "\n")
1409 if not Globals.verbose_options:
1410 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n")
1412 return {'headername': headername, 'headerdata': headerdata,
1413 'sourcename': sourcename, 'sourcedata': sourcedata}
1416 '''Main function when invoked directly from the command line.'''
1418 options, filenames = optparser.parse_args()
1421 optparser.print_help()
1425 options.verbose = False
1427 Globals.verbose_options = options.verbose
1429 for filename in filenames:
1430 results = process_file(filename, None, options)
1432 if not options.quiet:
1433 sys.stderr.write("Writing to " + results['headername'] + " and "
1434 + results['sourcename'] + "\n")
1436 open(results['headername'], 'w').write(results['headerdata'])
1437 open(results['sourcename'], 'w').write(results['sourcedata'])
1440 '''Main function when invoked as a protoc plugin.'''
1443 if sys.platform == "win32":
1445 # Set stdin and stdout to binary mode
1446 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1447 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1449 data = sys.stdin.read()
1450 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1453 # Versions of Python prior to 2.7.3 do not support unicode
1454 # input to shlex.split(). Try to convert to str if possible.
1455 params = str(request.parameter)
1456 except UnicodeEncodeError:
1457 params = request.parameter
1460 args = shlex.split(params)
1461 options, dummy = optparser.parse_args(args)
1463 Globals.verbose_options = options.verbose
1465 response = plugin_pb2.CodeGeneratorResponse()
1467 # Google's protoc does not currently indicate the full path of proto files.
1468 # Instead always add the main file path to the search dirs, that works for
1471 options.options_path.append(os.path.dirname(request.file_to_generate[0]))
1473 # Process any include files first, in order to have them
1474 # available as dependencies
1476 for fdesc in request.proto_file:
1477 other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)
1479 for filename in request.file_to_generate:
1480 for fdesc in request.proto_file:
1481 if fdesc.name == filename:
1482 results = process_file(filename, fdesc, options, other_files)
1484 f = response.file.add()
1485 f.name = results['headername']
1486 f.content = results['headerdata']
1488 f = response.file.add()
1489 f.name = results['sourcename']
1490 f.content = results['sourcedata']
1492 sys.stdout.write(response.SerializeToString())
1494 if __name__ == '__main__':
1495 # Check if we are running as a plugin under protoc
1496 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: