3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.3.4-dev"
8 from functools import reduce
11 # Add some dummy imports to keep packaging tools happy.
12 import google, distutils.util # bbfreeze seems to need these
13 import pkg_resources # pyinstaller / protobuf 2.5 seem to need these
15 # Don't care, we will error out later if it is actually important.
19 import google.protobuf.text_format as text_format
20 import google.protobuf.descriptor_pb2 as descriptor
23 *************************************************************
24 *** Could not import the Google protobuf Python libraries ***
25 *** Try installing package 'python-protobuf' or similar. ***
26 *************************************************************
31 import proto.nanopb_pb2 as nanopb_pb2
32 import proto.plugin_pb2 as plugin_pb2
35 ********************************************************************
36 *** Failed to import the protocol definitions for generator. ***
37 *** You have to run 'make' in the nanopb/generator/proto folder. ***
38 ********************************************************************
42 # ---------------------------------------------------------------------------
43 # Generation of single fields
44 # ---------------------------------------------------------------------------
49 # Values are tuple (c type, pb type, encoded size, int_size_allowed)
50 FieldD = descriptor.FieldDescriptorProto
52 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1, False),
53 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8, False),
54 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4, False),
55 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8, False),
56 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4, False),
57 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10, True),
58 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10, True),
59 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4, False),
60 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8, False),
61 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5, True),
62 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10, True),
63 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5, True),
64 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10, True)
67 # Integer size overrides (from .proto settings)
69 nanopb_pb2.IS_8: 'int8_t',
70 nanopb_pb2.IS_16: 'int16_t',
71 nanopb_pb2.IS_32: 'int32_t',
72 nanopb_pb2.IS_64: 'int64_t',
76 '''Keeps a set of nested names and formats them to C identifier.'''
77 def __init__(self, parts = ()):
78 if isinstance(parts, Names):
80 self.parts = tuple(parts)
83 return '_'.join(self.parts)
85 def __add__(self, other):
86 if isinstance(other, str):
87 return Names(self.parts + (other,))
88 elif isinstance(other, tuple):
89 return Names(self.parts + other)
91 raise ValueError("Name parts should be of type str")
93 def __eq__(self, other):
94 return isinstance(other, Names) and self.parts == other.parts
96 def names_from_type_name(type_name):
97 '''Parse Names() from FieldDescriptorProto type_name'''
98 if type_name[0] != '.':
99 raise NotImplementedError("Lookup of non-absolute type names is not supported")
100 return Names(type_name[1:].split('.'))
102 def varint_max_size(max_value):
103 '''Returns the maximum number of bytes a varint can take when encoded.'''
105 max_value = 2**64 - max_value
106 for i in range(1, 11):
107 if (max_value >> (i * 7)) == 0:
109 raise ValueError("Value too large for varint: " + str(max_value))
111 assert varint_max_size(-1) == 10
112 assert varint_max_size(0) == 1
113 assert varint_max_size(127) == 1
114 assert varint_max_size(128) == 2
117 '''Class used to represent the encoded size of a field or a message.
118 Consists of a combination of symbolic sizes and integer sizes.'''
119 def __init__(self, value = 0, symbols = []):
120 if isinstance(value, (str, Names)):
121 symbols = [str(value)]
124 self.symbols = symbols
126 def __add__(self, other):
127 if isinstance(other, int):
128 return EncodedSize(self.value + other, self.symbols)
129 elif isinstance(other, (str, Names)):
130 return EncodedSize(self.value, self.symbols + [str(other)])
131 elif isinstance(other, EncodedSize):
132 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
134 raise ValueError("Cannot add size: " + repr(other))
136 def __mul__(self, other):
137 if isinstance(other, int):
138 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
140 raise ValueError("Cannot multiply size: " + repr(other))
144 return str(self.value)
146 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
148 def upperlimit(self):
155 def __init__(self, names, desc, enum_options):
156 '''desc is EnumDescriptorProto'''
158 self.options = enum_options
159 self.names = names + desc.name
161 if enum_options.long_names:
162 self.values = [(self.names + x.name, x.number) for x in desc.value]
164 self.values = [(names + x.name, x.number) for x in desc.value]
166 self.value_longnames = [self.names + x.name for x in desc.value]
167 self.packed = enum_options.packed_enum
169 def has_negative(self):
170 for n, v in self.values:
175 def encoded_size(self):
176 return max([varint_max_size(v) for n,v in self.values])
179 result = 'typedef enum _%s {\n' % self.names
180 result += ',\n'.join([" %s = %d" % x for x in self.values])
184 result += ' pb_packed'
186 result += ' %s;' % self.names
188 if not self.options.long_names:
189 # Define the long names always so that enum value references
190 # from other files work properly.
191 for i, x in enumerate(self.values):
192 result += '\n#define %s %s' % (self.value_longnames[i], x[0])
197 def __init__(self, worst = 0, checks = [], field_name = 'undefined'):
198 if isinstance(worst, list):
199 self.worst = max(i for i in worst if i is not None)
203 self.worst_field = field_name
206 def extend(self, extend, field_name = None):
207 self.worst = max(self.worst, extend.worst)
209 if self.worst == extend.worst:
210 self.worst_field = extend.worst_field
212 self.checks.extend(extend.checks)
215 def __init__(self, struct_name, desc, field_options):
216 '''desc is FieldDescriptorProto'''
217 self.tag = desc.number
218 self.struct_name = struct_name
219 self.union_name = None
220 self.name = desc.name
223 self.max_count = None
228 # Parse field options
229 if field_options.HasField("max_size"):
230 self.max_size = field_options.max_size
232 if field_options.HasField("max_count"):
233 self.max_count = field_options.max_count
235 if desc.HasField('default_value'):
236 self.default = desc.default_value
238 # Check field rules, i.e. required/optional/repeated.
240 if desc.label == FieldD.LABEL_REQUIRED:
241 self.rules = 'REQUIRED'
242 elif desc.label == FieldD.LABEL_OPTIONAL:
243 self.rules = 'OPTIONAL'
244 elif desc.label == FieldD.LABEL_REPEATED:
245 self.rules = 'REPEATED'
246 if self.max_count is None:
247 can_be_static = False
249 self.array_decl = '[%d]' % self.max_count
251 raise NotImplementedError(desc.label)
253 # Check if the field can be implemented with static allocation
254 # i.e. whether the data size is known.
255 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
256 can_be_static = False
258 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
259 can_be_static = False
261 # Decide how the field data will be allocated
262 if field_options.type == nanopb_pb2.FT_DEFAULT:
264 field_options.type = nanopb_pb2.FT_STATIC
266 field_options.type = nanopb_pb2.FT_CALLBACK
268 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
269 raise Exception("Field %s is defined as static, but max_size or "
270 "max_count is not given." % self.name)
272 if field_options.type == nanopb_pb2.FT_STATIC:
273 self.allocation = 'STATIC'
274 elif field_options.type == nanopb_pb2.FT_POINTER:
275 self.allocation = 'POINTER'
276 elif field_options.type == nanopb_pb2.FT_CALLBACK:
277 self.allocation = 'CALLBACK'
279 raise NotImplementedError(field_options.type)
281 # Decide the C data type to use in the struct.
282 if desc.type in datatypes:
283 self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
285 # Override the field size if user wants to use smaller integers
286 if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
287 self.ctype = intsizes[field_options.int_size]
288 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
289 self.ctype = 'u' + self.ctype;
290 elif desc.type == FieldD.TYPE_ENUM:
292 self.ctype = names_from_type_name(desc.type_name)
293 if self.default is not None:
294 self.default = self.ctype + self.default
295 self.enc_size = None # Needs to be filled in when enum values are known
296 elif desc.type == FieldD.TYPE_STRING:
297 self.pbtype = 'STRING'
299 if self.allocation == 'STATIC':
301 self.array_decl += '[%d]' % self.max_size
302 self.enc_size = varint_max_size(self.max_size) + self.max_size
303 elif desc.type == FieldD.TYPE_BYTES:
304 self.pbtype = 'BYTES'
305 if self.allocation == 'STATIC':
306 self.ctype = self.struct_name + self.name + 't'
307 self.enc_size = varint_max_size(self.max_size) + self.max_size
308 elif self.allocation == 'POINTER':
309 self.ctype = 'pb_bytes_array_t'
310 elif desc.type == FieldD.TYPE_MESSAGE:
311 self.pbtype = 'MESSAGE'
312 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
313 self.enc_size = None # Needs to be filled in after the message type is available
315 raise NotImplementedError(desc.type)
317 def __lt__(self, other):
318 return self.tag < other.tag
322 if self.allocation == 'POINTER':
323 if self.rules == 'REPEATED':
324 result += ' pb_size_t ' + self.name + '_count;\n'
326 if self.pbtype == 'MESSAGE':
327 # Use struct definition, so recursive submessages are possible
328 result += ' struct _%s *%s;' % (self.ctype, self.name)
329 elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
330 # String/bytes arrays need to be defined as pointers to pointers
331 result += ' %s **%s;' % (self.ctype, self.name)
333 result += ' %s *%s;' % (self.ctype, self.name)
334 elif self.allocation == 'CALLBACK':
335 result += ' pb_callback_t %s;' % self.name
337 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
338 result += ' bool has_' + self.name + ';\n'
339 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
340 result += ' pb_size_t ' + self.name + '_count;\n'
341 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
345 '''Return definitions for any special types this field might need.'''
346 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
347 result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
352 def get_dependencies(self):
353 '''Get list of type names used by this field.'''
354 if self.allocation == 'STATIC':
355 return [str(self.ctype)]
359 def get_initializer(self, null_init, inner_init_only = False):
360 '''Return literal expression for this field's default value.
361 null_init: If True, initialize to a 0 value instead of default from .proto
362 inner_init_only: If True, exclude initialization for any count/has fields
366 if self.pbtype == 'MESSAGE':
368 inner_init = '%s_init_zero' % self.ctype
370 inner_init = '%s_init_default' % self.ctype
371 elif self.default is None or null_init:
372 if self.pbtype == 'STRING':
374 elif self.pbtype == 'BYTES':
375 inner_init = '{0, {0}}'
376 elif self.pbtype in ('ENUM', 'UENUM'):
377 inner_init = '(%s)0' % self.ctype
381 if self.pbtype == 'STRING':
382 inner_init = self.default.replace('"', '\\"')
383 inner_init = '"' + inner_init + '"'
384 elif self.pbtype == 'BYTES':
385 data = ['0x%02x' % ord(c) for c in self.default]
387 inner_init = '{0, {0}}'
389 inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
390 elif self.pbtype in ['FIXED32', 'UINT32']:
391 inner_init = str(self.default) + 'u'
392 elif self.pbtype in ['FIXED64', 'UINT64']:
393 inner_init = str(self.default) + 'ull'
394 elif self.pbtype in ['SFIXED64', 'INT64']:
395 inner_init = str(self.default) + 'll'
397 inner_init = str(self.default)
403 if self.allocation == 'STATIC':
404 if self.rules == 'REPEATED':
406 outer_init += ', '.join([inner_init] * self.max_count)
408 elif self.rules == 'OPTIONAL':
409 outer_init = 'false, ' + inner_init
411 outer_init = inner_init
412 elif self.allocation == 'POINTER':
413 if self.rules == 'REPEATED':
414 outer_init = '0, NULL'
417 elif self.allocation == 'CALLBACK':
418 if self.pbtype == 'EXTENSION':
421 outer_init = '{{NULL}, NULL}'
425 def default_decl(self, declaration_only = False):
426 '''Return definition for this field's default value.'''
427 if self.default is None:
431 default = self.get_initializer(False, True)
434 if self.pbtype == 'STRING':
435 if self.allocation != 'STATIC':
436 return None # Not implemented
437 array_decl = '[%d]' % self.max_size
438 elif self.pbtype == 'BYTES':
439 if self.allocation != 'STATIC':
440 return None # Not implemented
443 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
445 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
448 '''Return the #define for the tag number of this field.'''
449 identifier = '%s_%s_tag' % (self.struct_name, self.name)
450 return '#define %-40s %d\n' % (identifier, self.tag)
452 def pb_field_t(self, prev_field_name):
453 '''Return the pb_field_t initializer to use in the constant array.
454 prev_field_name is the name of the previous field or None.
457 if self.rules == 'ONEOF':
458 result = ' PB_ONEOF_FIELD(%s, ' % self.union_name
460 result = ' PB_FIELD('
462 result += '%3d, ' % self.tag
463 result += '%-8s, ' % self.pbtype
464 result += '%s, ' % self.rules
465 result += '%-8s, ' % self.allocation
466 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
467 result += '%s, ' % self.struct_name
468 result += '%s, ' % self.name
469 result += '%s, ' % (prev_field_name or self.name)
471 if self.pbtype == 'MESSAGE':
472 result += '&%s_fields)' % self.submsgname
473 elif self.default is None:
475 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
476 result += '0)' # Arbitrary size default values not implemented
477 elif self.rules == 'OPTEXT':
478 result += '0)' # Default value for extensions is not implemented
480 result += '&%s_default)' % (self.struct_name + self.name)
484 def largest_field_value(self):
485 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
486 Returns numeric value or a C-expression for assert.'''
488 if self.pbtype == 'MESSAGE':
489 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
490 check.append('pb_membersize(%s, %s[0])' % (self.struct_name, self.name))
491 elif self.rules == 'ONEOF':
492 check.append('pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name))
494 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
496 return FieldMaxSize([self.tag, self.max_size, self.max_count],
498 ('%s.%s' % (self.struct_name, self.name)))
500 def encoded_size(self, dependencies):
501 '''Return the maximum size that this field can take when encoded,
502 including the field tag. If the size cannot be determined, returns
505 if self.allocation != 'STATIC':
508 if self.pbtype == 'MESSAGE':
509 if str(self.submsgname) in dependencies:
510 submsg = dependencies[str(self.submsgname)]
511 encsize = submsg.encoded_size(dependencies)
513 return None # Submessage size is indeterminate
515 # Include submessage length prefix
516 encsize += varint_max_size(encsize.upperlimit())
518 # Submessage cannot be found, this currently occurs when
519 # the submessage type is defined in a different file and
520 # not using the protoc plugin.
521 # Instead of direct numeric value, reference the size that
522 # has been #defined in the other file.
523 encsize = EncodedSize(self.submsgname + 'size')
525 # We will have to make a conservative assumption on the length
526 # prefix size, though.
529 elif self.pbtype in ['ENUM', 'UENUM']:
530 if str(self.ctype) in dependencies:
531 enumtype = dependencies[str(self.ctype)]
532 encsize = enumtype.encoded_size()
534 # Conservative assumption
537 elif self.enc_size is None:
538 raise RuntimeError("Could not determine encoded size for %s.%s"
539 % (self.struct_name, self.name))
541 encsize = EncodedSize(self.enc_size)
543 encsize += varint_max_size(self.tag << 3) # Tag + wire type
545 if self.rules == 'REPEATED':
546 # Decoders must be always able to handle unpacked arrays.
547 # Therefore we have to reserve space for it, even though
548 # we emit packed arrays ourselves.
549 encsize *= self.max_count
554 class ExtensionRange(Field):
555 def __init__(self, struct_name, range_start, field_options):
556 '''Implements a special pb_extension_t* field in an extensible message
557 structure. The range_start signifies the index at which the extensions
558 start. Not necessarily all tags above this are extensions, it is merely
559 a speed optimization.
561 self.tag = range_start
562 self.struct_name = struct_name
563 self.name = 'extensions'
564 self.pbtype = 'EXTENSION'
565 self.rules = 'OPTIONAL'
566 self.allocation = 'CALLBACK'
567 self.ctype = 'pb_extension_t'
574 return ' pb_extension_t *extensions;'
582 def encoded_size(self, dependencies):
583 # We exclude extensions from the count, because they cannot be known
584 # until runtime. Other option would be to return None here, but this
585 # way the value remains useful if extensions are not used.
586 return EncodedSize(0)
588 class ExtensionField(Field):
589 def __init__(self, struct_name, desc, field_options):
590 self.fullname = struct_name + desc.name
591 self.extendee_name = names_from_type_name(desc.extendee)
592 Field.__init__(self, self.fullname + 'struct', desc, field_options)
594 if self.rules != 'OPTIONAL':
598 self.rules = 'OPTEXT'
601 '''Return the #define for the tag number of this field.'''
602 identifier = '%s_tag' % self.fullname
603 return '#define %-40s %d\n' % (identifier, self.tag)
605 def extension_decl(self):
606 '''Declaration of the extension type in the .pb.h file'''
608 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
609 msg +=' type of extension fields is currently supported. */\n'
612 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
613 (self.fullname, str(self).strip()))
615 def extension_def(self):
616 '''Definition of the extension type in the .pb.c file'''
621 result = 'typedef struct {\n'
623 result += '\n} %s;\n\n' % self.struct_name
624 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
625 (self.fullname, self.pb_field_t(None)))
626 result += 'const pb_extension_type_t %s = {\n' % self.fullname
629 result += ' &%s_field\n' % self.fullname
634 # ---------------------------------------------------------------------------
635 # Generation of oneofs (unions)
636 # ---------------------------------------------------------------------------
639 def __init__(self, struct_name, oneof_desc):
640 self.struct_name = struct_name
641 self.name = oneof_desc.name
643 self.pbtype = 'oneof'
645 self.allocation = 'ONEOF'
649 def add_field(self, field):
650 if field.allocation == 'CALLBACK':
651 raise Exception("Callback fields inside of oneof are not supported"
652 + " (field %s)" % field.name)
654 field.union_name = self.name
655 field.rules = 'ONEOF'
656 self.fields.append(field)
657 self.fields.sort(key = lambda f: f.tag)
659 # Sort by the lowest tag number inside union
660 self.tag = min([f.tag for f in self.fields])
665 result += ' pb_size_t which_' + self.name + ";\n"
666 result += ' union {\n'
667 for f in self.fields:
668 result += ' ' + str(f).replace('\n', '\n ') + '\n'
669 result += ' } ' + self.name + ';'
673 return ''.join([f.types() for f in self.fields])
675 def get_dependencies(self):
677 for f in self.fields:
678 deps += f.get_dependencies()
681 def get_initializer(self, null_init):
682 return '0, {' + self.fields[0].get_initializer(null_init) + '}'
684 def default_decl(self, declaration_only = False):
688 return '\n'.join([f.tags() for f in self.fields])
690 def pb_field_t(self, prev_field_name):
691 result = ',\n'.join([f.pb_field_t(prev_field_name) for f in self.fields])
694 def largest_field_value(self):
695 largest = FieldMaxSize()
696 for f in self.fields:
697 largest.extend(f.largest_field_value())
700 def encoded_size(self, dependencies):
701 largest = EncodedSize(0)
702 for f in self.fields:
703 size = f.encoded_size(dependencies)
707 return None # Cannot resolve maximum of symbols
708 elif size.value > largest.value:
713 # ---------------------------------------------------------------------------
714 # Generation of messages (structures)
715 # ---------------------------------------------------------------------------
719 def __init__(self, names, desc, message_options):
725 if message_options.msgid:
726 self.msgid = message_options.msgid
728 if hasattr(desc, 'oneof_decl'):
729 for i, f in enumerate(desc.oneof_decl):
730 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
731 if oneof_options.no_unions:
732 no_unions.append(i) # No union, but add fields normally
733 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
734 pass # No union and skip fields also
736 oneof = OneOf(self.name, f)
737 self.oneofs[i] = oneof
738 self.fields.append(oneof)
741 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
742 if field_options.type == nanopb_pb2.FT_IGNORE:
745 field = Field(self.name, f, field_options)
746 if (hasattr(f, 'oneof_index') and
747 f.HasField('oneof_index') and
748 f.oneof_index not in no_unions):
749 if f.oneof_index in self.oneofs:
750 self.oneofs[f.oneof_index].add_field(field)
752 self.fields.append(field)
754 if len(desc.extension_range) > 0:
755 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
756 range_start = min([r.start for r in desc.extension_range])
757 if field_options.type != nanopb_pb2.FT_IGNORE:
758 self.fields.append(ExtensionRange(self.name, range_start, field_options))
760 self.packed = message_options.packed_struct
761 self.ordered_fields = self.fields[:]
762 self.ordered_fields.sort()
764 def get_dependencies(self):
765 '''Get list of type names that this structure refers to.'''
767 for f in self.fields:
768 deps += f.get_dependencies()
772 result = 'typedef struct _%s {\n' % self.name
774 if not self.ordered_fields:
775 # Empty structs are not allowed in C standard.
776 # Therefore add a dummy field if an empty message occurs.
777 result += ' uint8_t dummy_field;'
779 result += '\n'.join([str(f) for f in self.ordered_fields])
783 result += ' pb_packed'
785 result += ' %s;' % self.name
788 result = 'PB_PACKED_STRUCT_START\n' + result
789 result += '\nPB_PACKED_STRUCT_END'
794 return ''.join([f.types() for f in self.fields])
796 def get_initializer(self, null_init):
797 if not self.ordered_fields:
801 for field in self.ordered_fields:
802 parts.append(field.get_initializer(null_init))
803 return '{' + ', '.join(parts) + '}'
805 def default_decl(self, declaration_only = False):
807 for field in self.fields:
808 default = field.default_decl(declaration_only)
809 if default is not None:
810 result += default + '\n'
813 def count_required_fields(self):
814 '''Returns number of required fields inside this message'''
816 for f in self.fields:
817 if not isinstance(f, OneOf):
818 if f.rules == 'REQUIRED':
822 def count_all_fields(self):
824 for f in self.fields:
825 if isinstance(f, OneOf):
826 count += len(f.fields)
831 def fields_declaration(self):
832 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
835 def fields_definition(self):
836 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
839 for field in self.ordered_fields:
840 result += field.pb_field_t(prev)
842 if isinstance(field, OneOf):
843 prev = field.name + '.' + field.fields[-1].name
847 result += ' PB_LAST_FIELD\n};'
850 def encoded_size(self, dependencies):
851 '''Return the maximum size that this message can take when encoded.
852 If the size cannot be determined, returns None.
854 size = EncodedSize(0)
855 for field in self.fields:
856 fsize = field.encoded_size(dependencies)
864 # ---------------------------------------------------------------------------
865 # Processing of entire .proto files
866 # ---------------------------------------------------------------------------
868 def iterate_messages(desc, names = Names()):
869 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
870 if hasattr(desc, 'message_type'):
871 submsgs = desc.message_type
873 submsgs = desc.nested_type
875 for submsg in submsgs:
876 sub_names = names + submsg.name
877 yield sub_names, submsg
879 for x in iterate_messages(submsg, sub_names):
882 def iterate_extensions(desc, names = Names()):
883 '''Recursively find all extensions.
884 For each, yield name, FieldDescriptorProto.
886 for extension in desc.extension:
887 yield names, extension
889 for subname, subdesc in iterate_messages(desc, names):
890 for extension in subdesc.extension:
891 yield subname, extension
895 From http://code.activestate.com/recipes/577413-topological-sort/
896 This function is under the MIT license.
898 for k, v in list(data.items()):
899 v.discard(k) # Ignore self dependencies
900 extra_items_in_deps = reduce(set.union, list(data.values()), set()) - set(data.keys())
901 data.update(dict([(item, set()) for item in extra_items_in_deps]))
903 ordered = set(item for item,dep in list(data.items()) if not dep)
906 for item in sorted(ordered):
908 data = dict([(item, (dep - ordered)) for item,dep in list(data.items())
909 if item not in ordered])
910 assert not data, "A cyclic dependency exists amongst %r" % data
912 def sort_dependencies(messages):
913 '''Sort a list of Messages based on dependencies.'''
916 for message in messages:
917 dependencies[str(message.name)] = set(message.get_dependencies())
918 message_by_name[str(message.name)] = message
920 for msgname in toposort2(dependencies):
921 if msgname in message_by_name:
922 yield message_by_name[msgname]
924 def make_identifier(headername):
925 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
927 for c in headername.upper():
935 def __init__(self, fdesc, file_options):
936 '''Takes a FileDescriptorProto and parses it.'''
938 self.file_options = file_options
939 self.dependencies = {}
942 # Some of types used in this file probably come from the file itself.
943 # Thus it has implicit dependency on itself.
944 self.add_dependency(self)
951 if self.fdesc.package:
952 base_name = Names(self.fdesc.package.split('.'))
956 for enum in self.fdesc.enum_type:
957 enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
958 self.enums.append(Enum(base_name, enum, enum_options))
960 for names, message in iterate_messages(self.fdesc, base_name):
961 message_options = get_nanopb_suboptions(message, self.file_options, names)
963 if message_options.skip_message:
966 self.messages.append(Message(names, message, message_options))
967 for enum in message.enum_type:
968 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
969 self.enums.append(Enum(names, enum, enum_options))
971 for names, extension in iterate_extensions(self.fdesc, base_name):
972 field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
973 if field_options.type != nanopb_pb2.FT_IGNORE:
974 self.extensions.append(ExtensionField(names, extension, field_options))
976 def add_dependency(self, other):
977 for enum in other.enums:
978 self.dependencies[str(enum.names)] = enum
980 for msg in other.messages:
981 self.dependencies[str(msg.name)] = msg
983 # Fix field default values where enum short names are used.
984 for enum in other.enums:
985 if not enum.options.long_names:
986 for message in self.messages:
987 for field in message.fields:
988 if field.default in enum.value_longnames:
989 idx = enum.value_longnames.index(field.default)
990 field.default = enum.values[idx][0]
992 # Fix field data types where enums have negative values.
993 for enum in other.enums:
994 if not enum.has_negative():
995 for message in self.messages:
996 for field in message.fields:
997 if field.pbtype == 'ENUM' and field.ctype == enum.names:
998 field.pbtype = 'UENUM'
1000 def generate_header(self, includes, headername, options):
1001 '''Generate content for a header file.
1002 Generates strings, which should be concatenated and stored to file.
1005 yield '/* Automatically generated nanopb header */\n'
1006 if options.notimestamp:
1007 yield '/* Generated by %s */\n\n' % (nanopb_version)
1009 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1011 symbol = make_identifier(headername)
1012 yield '#ifndef PB_%s_INCLUDED\n' % symbol
1013 yield '#define PB_%s_INCLUDED\n' % symbol
1015 yield options.libformat % ('pb.h')
1017 # no %s specified - use whatever was passed in as options.libformat
1018 yield options.libformat
1021 for incfile in includes:
1022 noext = os.path.splitext(incfile)[0]
1023 yield options.genformat % (noext + options.extension + '.h')
1026 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1027 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1031 yield '#ifdef __cplusplus\n'
1032 yield 'extern "C" {\n'
1036 yield '/* Enum definitions */\n'
1037 for enum in self.enums:
1038 yield str(enum) + '\n\n'
1041 yield '/* Struct definitions */\n'
1042 for msg in sort_dependencies(self.messages):
1044 yield str(msg) + '\n\n'
1047 yield '/* Extensions */\n'
1048 for extension in self.extensions:
1049 yield extension.extension_decl()
1053 yield '/* Default values for struct fields */\n'
1054 for msg in self.messages:
1055 yield msg.default_decl(True)
1058 yield '/* Initializer values for message structs */\n'
1059 for msg in self.messages:
1060 identifier = '%s_init_default' % msg.name
1061 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1062 for msg in self.messages:
1063 identifier = '%s_init_zero' % msg.name
1064 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1067 yield '/* Field tags (for use in manual encoding/decoding) */\n'
1068 for msg in sort_dependencies(self.messages):
1069 for field in msg.fields:
1071 for extension in self.extensions:
1072 yield extension.tags()
1075 yield '/* Struct field encoding specification for nanopb */\n'
1076 for msg in self.messages:
1077 yield msg.fields_declaration() + '\n'
1080 yield '/* Maximum encoded size of messages (where known) */\n'
1081 for msg in self.messages:
1082 msize = msg.encoded_size(self.dependencies)
1083 if msize is not None:
1084 identifier = '%s_size' % msg.name
1085 yield '#define %-40s %s\n' % (identifier, msize)
1088 yield '/* Message IDs (where set with "msgid" option) */\n'
1090 yield '#ifdef PB_MSGID\n'
1091 for msg in self.messages:
1092 if hasattr(msg,'msgid'):
1093 yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1096 symbol = make_identifier(headername.split('.')[0])
1097 yield '#define %s_MESSAGES \\\n' % symbol
1099 for msg in self.messages:
1101 msize = msg.encoded_size(self.dependencies)
1102 if msize is not None:
1104 if hasattr(msg,'msgid'):
1105 yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1108 for msg in self.messages:
1109 if hasattr(msg,'msgid'):
1110 yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1115 yield '#ifdef __cplusplus\n'
1116 yield '} /* extern "C" */\n'
1122 def generate_source(self, headername, options):
1123 '''Generate content for a source file.'''
1125 yield '/* Automatically generated nanopb constant definitions */\n'
1126 if options.notimestamp:
1127 yield '/* Generated by %s */\n\n' % (nanopb_version)
1129 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1130 yield options.genformat % (headername)
1133 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1134 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1138 for msg in self.messages:
1139 yield msg.default_decl(False)
1143 for msg in self.messages:
1144 yield msg.fields_definition() + '\n\n'
1146 for ext in self.extensions:
1147 yield ext.extension_def() + '\n'
1149 # Add checks for numeric limits
1151 largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1152 largest_count = largest_msg.count_required_fields()
1153 if largest_count > 64:
1154 yield '\n/* Check that missing required fields will be properly detected */\n'
1155 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1156 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1157 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1160 max_field = FieldMaxSize()
1161 checks_msgnames = []
1162 for msg in self.messages:
1163 checks_msgnames.append(msg.name)
1164 for field in msg.fields:
1165 max_field.extend(field.largest_field_value())
1167 worst = max_field.worst
1168 worst_field = max_field.worst_field
1169 checks = max_field.checks
1171 if worst > 255 or checks:
1172 yield '\n/* Check that field information fits in pb_field_t */\n'
1174 if worst > 65535 or checks:
1175 yield '#if !defined(PB_FIELD_32BIT)\n'
1177 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1179 assertion = ' && '.join(str(c) + ' < 65536' 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_32BIT\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 8 or 16 bit\n'
1186 yield ' * field descriptors.\n'
1188 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1192 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1194 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1196 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1197 msgs = '_'.join(str(n) for n in checks_msgnames)
1198 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1199 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1201 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1202 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1203 yield ' * 8 bit descriptors.\n'
1205 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1208 # Add check for sizeof(double)
1210 for msg in self.messages:
1211 for field in msg.fields:
1212 if field.ctype == 'double':
1217 yield '/* On some platforms (such as AVR), double is really float.\n'
1218 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1219 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1221 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1225 # ---------------------------------------------------------------------------
1226 # Options parsing for the .proto files
1227 # ---------------------------------------------------------------------------
1229 from fnmatch import fnmatch
1231 def read_options_file(infile):
1232 '''Parse a separate options file to list:
1233 [(namemask, options), ...]
1236 data = infile.read()
1237 data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1238 data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1239 data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1240 for i, line in enumerate(data.split('\n')):
1245 parts = line.split(None, 1)
1248 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1249 "Option lines should have space between field name and options. " +
1250 "Skipping line: '%s'\n" % line)
1253 opts = nanopb_pb2.NanoPBOptions()
1256 text_format.Merge(parts[1], opts)
1257 except Exception as e:
1258 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1259 "Unparseable option line: '%s'. " % line +
1260 "Error: %s\n" % str(e))
1262 results.append((parts[0], opts))
1267 '''Ugly global variables, should find a good way to pass these.'''
1268 verbose_options = False
1269 separate_options = []
1270 matched_namemasks = set()
1272 def get_nanopb_suboptions(subdesc, options, name):
1273 '''Get copy of options, and merge information from subdesc.'''
1274 new_options = nanopb_pb2.NanoPBOptions()
1275 new_options.CopyFrom(options)
1277 # Handle options defined in a separate file
1278 dotname = '.'.join(name.parts)
1279 for namemask, options in Globals.separate_options:
1280 if fnmatch(dotname, namemask):
1281 Globals.matched_namemasks.add(namemask)
1282 new_options.MergeFrom(options)
1284 # Handle options defined in .proto
1285 if isinstance(subdesc.options, descriptor.FieldOptions):
1286 ext_type = nanopb_pb2.nanopb
1287 elif isinstance(subdesc.options, descriptor.FileOptions):
1288 ext_type = nanopb_pb2.nanopb_fileopt
1289 elif isinstance(subdesc.options, descriptor.MessageOptions):
1290 ext_type = nanopb_pb2.nanopb_msgopt
1291 elif isinstance(subdesc.options, descriptor.EnumOptions):
1292 ext_type = nanopb_pb2.nanopb_enumopt
1294 raise Exception("Unknown options type")
1296 if subdesc.options.HasExtension(ext_type):
1297 ext = subdesc.options.Extensions[ext_type]
1298 new_options.MergeFrom(ext)
1300 if Globals.verbose_options:
1301 sys.stderr.write("Options for " + dotname + ": ")
1302 sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1307 # ---------------------------------------------------------------------------
1308 # Command line interface
1309 # ---------------------------------------------------------------------------
1313 from optparse import OptionParser
1315 optparser = OptionParser(
1316 usage = "Usage: nanopb_generator.py [options] file.pb ...",
1317 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1318 "Output will be written to file.pb.h and file.pb.c.")
1319 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1320 help="Exclude file from generated #include list.")
1321 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1322 help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1323 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1324 help="Set name of a separate generator options file.")
1325 optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR",
1326 action="append", default = [],
1327 help="Search for .options files additionally in this path")
1328 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1329 metavar="FORMAT", default='#include "%s"\n',
1330 help="Set format string to use for including other .pb.h files. [default: %default]")
1331 optparser.add_option("-L", "--library-include-format", dest="libformat",
1332 metavar="FORMAT", default='#include <%s>\n',
1333 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1334 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1335 help="Don't add timestamp to .pb.h and .pb.c preambles")
1336 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1337 help="Don't print anything except errors.")
1338 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1339 help="Print more information.")
1340 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1341 help="Set generator option (max_size, max_count etc.).")
1343 def parse_file(filename, fdesc, options):
1344 '''Parse a single file. Returns a ProtoFile instance.'''
1345 toplevel_options = nanopb_pb2.NanoPBOptions()
1346 for s in options.settings:
1347 text_format.Merge(s, toplevel_options)
1350 data = open(filename, 'rb').read()
1351 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1353 # Check if there is a separate .options file
1356 optfilename = options.options_file % os.path.splitext(filename)[0]
1358 # No %s specified, use the filename as-is
1359 optfilename = options.options_file
1362 paths = ['.'] + options.options_path
1364 if os.path.isfile(os.path.join(p, optfilename)):
1365 optfilename = os.path.join(p, optfilename)
1367 sys.stderr.write('Reading options from ' + optfilename + '\n')
1368 Globals.separate_options = read_options_file(open(optfilename, "rU"))
1371 # If we are given a full filename and it does not exist, give an error.
1372 # However, don't give error when we automatically look for .options file
1373 # with the same name as .proto.
1374 if options.verbose or had_abspath:
1375 sys.stderr.write('Options file not found: ' + optfilename + '\n')
1376 Globals.separate_options = []
1378 Globals.matched_namemasks = set()
1381 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1382 f = ProtoFile(fdesc, file_options)
1383 f.optfilename = optfilename
1387 def process_file(filename, fdesc, options, other_files = {}):
1388 '''Process a single file.
1389 filename: The full path to the .proto or .pb source file, as string.
1390 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1391 options: Command line options as they come from OptionsParser.
1394 {'headername': Name of header file,
1395 'headerdata': Data for the .h header file,
1396 'sourcename': Name of the source code file,
1397 'sourcedata': Data for the .c source code file
1400 f = parse_file(filename, fdesc, options)
1402 # Provide dependencies if available
1403 for dep in f.fdesc.dependency:
1404 if dep in other_files:
1405 f.add_dependency(other_files[dep])
1407 # Decide the file names
1408 noext = os.path.splitext(filename)[0]
1409 headername = noext + options.extension + '.h'
1410 sourcename = noext + options.extension + '.c'
1411 headerbasename = os.path.basename(headername)
1413 # List of .proto files that should not be included in the C header file
1414 # even if they are mentioned in the source .proto.
1415 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1416 includes = [d for d in f.fdesc.dependency if d not in excludes]
1418 headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1419 sourcedata = ''.join(f.generate_source(headerbasename, options))
1421 # Check if there were any lines in .options that did not match a member
1422 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1423 if unmatched and not options.quiet:
1424 sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: "
1425 + ', '.join(unmatched) + "\n")
1426 if not Globals.verbose_options:
1427 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n")
1429 return {'headername': headername, 'headerdata': headerdata,
1430 'sourcename': sourcename, 'sourcedata': sourcedata}
1433 '''Main function when invoked directly from the command line.'''
1435 options, filenames = optparser.parse_args()
1438 optparser.print_help()
1442 options.verbose = False
1444 Globals.verbose_options = options.verbose
1446 for filename in filenames:
1447 results = process_file(filename, None, options)
1449 if not options.quiet:
1450 sys.stderr.write("Writing to " + results['headername'] + " and "
1451 + results['sourcename'] + "\n")
1453 open(results['headername'], 'w').write(results['headerdata'])
1454 open(results['sourcename'], 'w').write(results['sourcedata'])
1457 '''Main function when invoked as a protoc plugin.'''
1460 if sys.platform == "win32":
1462 # Set stdin and stdout to binary mode
1463 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1464 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1466 data = io.open(sys.stdin.fileno(), "rb").read()
1468 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1471 # Versions of Python prior to 2.7.3 do not support unicode
1472 # input to shlex.split(). Try to convert to str if possible.
1473 params = str(request.parameter)
1474 except UnicodeEncodeError:
1475 params = request.parameter
1478 args = shlex.split(params)
1479 options, dummy = optparser.parse_args(args)
1481 Globals.verbose_options = options.verbose
1483 response = plugin_pb2.CodeGeneratorResponse()
1485 # Google's protoc does not currently indicate the full path of proto files.
1486 # Instead always add the main file path to the search dirs, that works for
1489 options.options_path.append(os.path.dirname(request.file_to_generate[0]))
1491 # Process any include files first, in order to have them
1492 # available as dependencies
1494 for fdesc in request.proto_file:
1495 other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)
1497 for filename in request.file_to_generate:
1498 for fdesc in request.proto_file:
1499 if fdesc.name == filename:
1500 results = process_file(filename, fdesc, options, other_files)
1502 f = response.file.add()
1503 f.name = results['headername']
1504 f.content = results['headerdata']
1506 f = response.file.add()
1507 f.name = results['sourcename']
1508 f.content = results['sourcedata']
1510 io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString())
1512 if __name__ == '__main__':
1513 # Check if we are running as a plugin under protoc
1514 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: