3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.3.3-dev"
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.'''
103 for i in range(1, 11):
104 if (max_value >> (i * 7)) == 0:
106 raise ValueError("Value too large for varint: " + str(max_value))
108 assert varint_max_size(0) == 1
109 assert varint_max_size(127) == 1
110 assert varint_max_size(128) == 2
113 '''Class used to represent the encoded size of a field or a message.
114 Consists of a combination of symbolic sizes and integer sizes.'''
115 def __init__(self, value = 0, symbols = []):
116 if isinstance(value, (str, Names)):
117 symbols = [str(value)]
120 self.symbols = symbols
122 def __add__(self, other):
123 if isinstance(other, (int, long)):
124 return EncodedSize(self.value + other, self.symbols)
125 elif isinstance(other, (str, Names)):
126 return EncodedSize(self.value, self.symbols + [str(other)])
127 elif isinstance(other, EncodedSize):
128 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
130 raise ValueError("Cannot add size: " + repr(other))
132 def __mul__(self, other):
133 if isinstance(other, (int, long)):
134 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
136 raise ValueError("Cannot multiply size: " + repr(other))
140 return str(self.value)
142 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
144 def upperlimit(self):
151 def __init__(self, names, desc, enum_options):
152 '''desc is EnumDescriptorProto'''
154 self.options = enum_options
155 self.names = names + desc.name
157 if enum_options.long_names:
158 self.values = [(self.names + x.name, x.number) for x in desc.value]
160 self.values = [(names + x.name, x.number) for x in desc.value]
162 self.value_longnames = [self.names + x.name for x in desc.value]
165 result = 'typedef enum _%s {\n' % self.names
166 result += ',\n'.join([" %s = %d" % x for x in self.values])
167 result += '\n} %s;' % self.names
169 if not self.options.long_names:
170 # Define the long names always so that enum value references
171 # from other files work properly.
172 for i, x in enumerate(self.values):
173 result += '\n#define %s %s' % (self.value_longnames[i], x[0])
178 def __init__(self, struct_name, desc, field_options):
179 '''desc is FieldDescriptorProto'''
180 self.tag = desc.number
181 self.struct_name = struct_name
182 self.union_name = None
183 self.name = desc.name
186 self.max_count = None
191 # Parse field options
192 if field_options.HasField("max_size"):
193 self.max_size = field_options.max_size
195 if field_options.HasField("max_count"):
196 self.max_count = field_options.max_count
198 if desc.HasField('default_value'):
199 self.default = desc.default_value
201 # Check field rules, i.e. required/optional/repeated.
203 if desc.label == FieldD.LABEL_REQUIRED:
204 self.rules = 'REQUIRED'
205 elif desc.label == FieldD.LABEL_OPTIONAL:
206 self.rules = 'OPTIONAL'
207 elif desc.label == FieldD.LABEL_REPEATED:
208 self.rules = 'REPEATED'
209 if self.max_count is None:
210 can_be_static = False
212 self.array_decl = '[%d]' % self.max_count
214 raise NotImplementedError(desc.label)
216 # Check if the field can be implemented with static allocation
217 # i.e. whether the data size is known.
218 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
219 can_be_static = False
221 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
222 can_be_static = False
224 # Decide how the field data will be allocated
225 if field_options.type == nanopb_pb2.FT_DEFAULT:
227 field_options.type = nanopb_pb2.FT_STATIC
229 field_options.type = nanopb_pb2.FT_CALLBACK
231 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
232 raise Exception("Field %s is defined as static, but max_size or "
233 "max_count is not given." % self.name)
235 if field_options.type == nanopb_pb2.FT_STATIC:
236 self.allocation = 'STATIC'
237 elif field_options.type == nanopb_pb2.FT_POINTER:
238 self.allocation = 'POINTER'
239 elif field_options.type == nanopb_pb2.FT_CALLBACK:
240 self.allocation = 'CALLBACK'
242 raise NotImplementedError(field_options.type)
244 # Decide the C data type to use in the struct.
245 if datatypes.has_key(desc.type):
246 self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
248 # Override the field size if user wants to use smaller integers
249 if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
250 self.ctype = intsizes[field_options.int_size]
251 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
252 self.ctype = 'u' + self.ctype;
253 elif desc.type == FieldD.TYPE_ENUM:
255 self.ctype = names_from_type_name(desc.type_name)
256 if self.default is not None:
257 self.default = self.ctype + self.default
258 self.enc_size = 5 # protoc rejects enum values > 32 bits
259 elif desc.type == FieldD.TYPE_STRING:
260 self.pbtype = 'STRING'
262 if self.allocation == 'STATIC':
264 self.array_decl += '[%d]' % self.max_size
265 self.enc_size = varint_max_size(self.max_size) + self.max_size
266 elif desc.type == FieldD.TYPE_BYTES:
267 self.pbtype = 'BYTES'
268 if self.allocation == 'STATIC':
269 self.ctype = self.struct_name + self.name + 't'
270 self.enc_size = varint_max_size(self.max_size) + self.max_size
271 elif self.allocation == 'POINTER':
272 self.ctype = 'pb_bytes_array_t'
273 elif desc.type == FieldD.TYPE_MESSAGE:
274 self.pbtype = 'MESSAGE'
275 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
276 self.enc_size = None # Needs to be filled in after the message type is available
278 raise NotImplementedError(desc.type)
280 def __cmp__(self, other):
281 return cmp(self.tag, other.tag)
285 if self.allocation == 'POINTER':
286 if self.rules == 'REPEATED':
287 result += ' pb_size_t ' + self.name + '_count;\n'
289 if self.pbtype == 'MESSAGE':
290 # Use struct definition, so recursive submessages are possible
291 result += ' struct _%s *%s;' % (self.ctype, self.name)
292 elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
293 # String/bytes arrays need to be defined as pointers to pointers
294 result += ' %s **%s;' % (self.ctype, self.name)
296 result += ' %s *%s;' % (self.ctype, self.name)
297 elif self.allocation == 'CALLBACK':
298 result += ' pb_callback_t %s;' % self.name
300 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
301 result += ' bool has_' + self.name + ';\n'
302 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
303 result += ' pb_size_t ' + self.name + '_count;\n'
304 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
308 '''Return definitions for any special types this field might need.'''
309 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
310 result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
315 def get_dependencies(self):
316 '''Get list of type names used by this field.'''
317 if self.allocation == 'STATIC':
318 return [str(self.ctype)]
322 def get_initializer(self, null_init, inner_init_only = False):
323 '''Return literal expression for this field's default value.
324 null_init: If True, initialize to a 0 value instead of default from .proto
325 inner_init_only: If True, exclude initialization for any count/has fields
329 if self.pbtype == 'MESSAGE':
331 inner_init = '%s_init_zero' % self.ctype
333 inner_init = '%s_init_default' % self.ctype
334 elif self.default is None or null_init:
335 if self.pbtype == 'STRING':
337 elif self.pbtype == 'BYTES':
338 inner_init = '{0, {0}}'
339 elif self.pbtype == 'ENUM':
340 inner_init = '(%s)0' % self.ctype
344 if self.pbtype == 'STRING':
345 inner_init = self.default.encode('utf-8').encode('string_escape')
346 inner_init = inner_init.replace('"', '\\"')
347 inner_init = '"' + inner_init + '"'
348 elif self.pbtype == 'BYTES':
349 data = str(self.default).decode('string_escape')
350 data = ['0x%02x' % ord(c) for c in data]
352 inner_init = '{0, {0}}'
354 inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
355 elif self.pbtype in ['FIXED32', 'UINT32']:
356 inner_init = str(self.default) + 'u'
357 elif self.pbtype in ['FIXED64', 'UINT64']:
358 inner_init = str(self.default) + 'ull'
359 elif self.pbtype in ['SFIXED64', 'INT64']:
360 inner_init = str(self.default) + 'll'
362 inner_init = str(self.default)
368 if self.allocation == 'STATIC':
369 if self.rules == 'REPEATED':
371 outer_init += ', '.join([inner_init] * self.max_count)
373 elif self.rules == 'OPTIONAL':
374 outer_init = 'false, ' + inner_init
376 outer_init = inner_init
377 elif self.allocation == 'POINTER':
378 if self.rules == 'REPEATED':
379 outer_init = '0, NULL'
382 elif self.allocation == 'CALLBACK':
383 if self.pbtype == 'EXTENSION':
386 outer_init = '{{NULL}, NULL}'
390 def default_decl(self, declaration_only = False):
391 '''Return definition for this field's default value.'''
392 if self.default is None:
396 default = self.get_initializer(False, True)
399 if self.pbtype == 'STRING':
400 if self.allocation != 'STATIC':
401 return None # Not implemented
402 array_decl = '[%d]' % self.max_size
403 elif self.pbtype == 'BYTES':
404 if self.allocation != 'STATIC':
405 return None # Not implemented
408 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
410 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
413 '''Return the #define for the tag number of this field.'''
414 identifier = '%s_%s_tag' % (self.struct_name, self.name)
415 return '#define %-40s %d\n' % (identifier, self.tag)
417 def pb_field_t(self, prev_field_name):
418 '''Return the pb_field_t initializer to use in the constant array.
419 prev_field_name is the name of the previous field or None.
422 if self.rules == 'ONEOF':
423 result = ' PB_ONEOF_FIELD(%s, ' % self.union_name
425 result = ' PB_FIELD('
427 result += '%3d, ' % self.tag
428 result += '%-8s, ' % self.pbtype
429 result += '%s, ' % self.rules
430 result += '%-8s, ' % self.allocation
431 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
432 result += '%s, ' % self.struct_name
433 result += '%s, ' % self.name
434 result += '%s, ' % (prev_field_name or self.name)
436 if self.pbtype == 'MESSAGE':
437 result += '&%s_fields)' % self.submsgname
438 elif self.default is None:
440 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
441 result += '0)' # Arbitrary size default values not implemented
442 elif self.rules == 'OPTEXT':
443 result += '0)' # Default value for extensions is not implemented
445 result += '&%s_default)' % (self.struct_name + self.name)
449 def largest_field_value(self):
450 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
451 Returns numeric value or a C-expression for assert.'''
452 if self.pbtype == 'MESSAGE':
453 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
454 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
455 elif self.rules == 'ONEOF':
456 return 'pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name)
458 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
460 return max(self.tag, self.max_size, self.max_count)
462 def encoded_size(self, allmsgs):
463 '''Return the maximum size that this field can take when encoded,
464 including the field tag. If the size cannot be determined, returns
467 if self.allocation != 'STATIC':
470 if self.pbtype == 'MESSAGE':
472 if msg.name == self.submsgname:
473 encsize = msg.encoded_size(allmsgs)
475 return None # Submessage size is indeterminate
477 # Include submessage length prefix
478 encsize += varint_max_size(encsize.upperlimit())
481 # Submessage cannot be found, this currently occurs when
482 # the submessage type is defined in a different file.
483 # Instead of direct numeric value, reference the size that
484 # has been #defined in the other file.
485 encsize = EncodedSize(self.submsgname + 'size')
487 # We will have to make a conservative assumption on the length
488 # prefix size, though.
491 elif self.enc_size is None:
492 raise RuntimeError("Could not determine encoded size for %s.%s"
493 % (self.struct_name, self.name))
495 encsize = EncodedSize(self.enc_size)
497 encsize += varint_max_size(self.tag << 3) # Tag + wire type
499 if self.rules == 'REPEATED':
500 # Decoders must be always able to handle unpacked arrays.
501 # Therefore we have to reserve space for it, even though
502 # we emit packed arrays ourselves.
503 encsize *= self.max_count
508 class ExtensionRange(Field):
509 def __init__(self, struct_name, range_start, field_options):
510 '''Implements a special pb_extension_t* field in an extensible message
511 structure. The range_start signifies the index at which the extensions
512 start. Not necessarily all tags above this are extensions, it is merely
513 a speed optimization.
515 self.tag = range_start
516 self.struct_name = struct_name
517 self.name = 'extensions'
518 self.pbtype = 'EXTENSION'
519 self.rules = 'OPTIONAL'
520 self.allocation = 'CALLBACK'
521 self.ctype = 'pb_extension_t'
528 return ' pb_extension_t *extensions;'
536 def encoded_size(self, allmsgs):
537 # We exclude extensions from the count, because they cannot be known
538 # until runtime. Other option would be to return None here, but this
539 # way the value remains useful if extensions are not used.
540 return EncodedSize(0)
542 class ExtensionField(Field):
543 def __init__(self, struct_name, desc, field_options):
544 self.fullname = struct_name + desc.name
545 self.extendee_name = names_from_type_name(desc.extendee)
546 Field.__init__(self, self.fullname + 'struct', desc, field_options)
548 if self.rules != 'OPTIONAL':
552 self.rules = 'OPTEXT'
555 '''Return the #define for the tag number of this field.'''
556 identifier = '%s_tag' % self.fullname
557 return '#define %-40s %d\n' % (identifier, self.tag)
559 def extension_decl(self):
560 '''Declaration of the extension type in the .pb.h file'''
562 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
563 msg +=' type of extension fields is currently supported. */\n'
566 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
567 (self.fullname, str(self).strip()))
569 def extension_def(self):
570 '''Definition of the extension type in the .pb.c file'''
575 result = 'typedef struct {\n'
577 result += '\n} %s;\n\n' % self.struct_name
578 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
579 (self.fullname, self.pb_field_t(None)))
580 result += 'const pb_extension_type_t %s = {\n' % self.fullname
583 result += ' &%s_field\n' % self.fullname
588 # ---------------------------------------------------------------------------
589 # Generation of oneofs (unions)
590 # ---------------------------------------------------------------------------
593 def __init__(self, struct_name, oneof_desc):
594 self.struct_name = struct_name
595 self.name = oneof_desc.name
598 self.allocation = 'ONEOF'
602 def add_field(self, field):
603 if field.allocation == 'CALLBACK':
604 raise Exception("Callback fields inside of oneof are not supported"
605 + " (field %s)" % field.name)
607 field.union_name = self.name
608 field.rules = 'ONEOF'
609 self.fields.append(field)
610 self.fields.sort(key = lambda f: f.tag)
612 # Sort by the lowest tag number inside union
613 self.tag = min([f.tag for f in self.fields])
615 def __cmp__(self, other):
616 return cmp(self.tag, other.tag)
621 result += ' pb_size_t which_' + self.name + ";\n"
622 result += ' union {\n'
623 for f in self.fields:
624 result += ' ' + str(f).replace('\n', '\n ') + '\n'
625 result += ' } ' + self.name + ';'
629 return ''.join([f.types() for f in self.fields])
631 def get_dependencies(self):
633 for f in self.fields:
634 deps += f.get_dependencies()
637 def get_initializer(self, null_init):
638 return '0, {' + self.fields[0].get_initializer(null_init) + '}'
640 def default_decl(self, declaration_only = False):
644 return '\n'.join([f.tags() for f in self.fields])
646 def pb_field_t(self, prev_field_name):
647 result = ',\n'.join([f.pb_field_t(prev_field_name) for f in self.fields])
650 def largest_field_value(self):
651 return max([f.largest_field_value() for f in self.fields])
653 def encoded_size(self, allmsgs):
654 largest = EncodedSize(0)
655 for f in self.fields:
656 size = f.encoded_size(allmsgs)
660 return None # Cannot resolve maximum of symbols
661 elif size.value > largest.value:
666 # ---------------------------------------------------------------------------
667 # Generation of messages (structures)
668 # ---------------------------------------------------------------------------
672 def __init__(self, names, desc, message_options):
678 if message_options.msgid:
679 self.msgid = message_options.msgid
681 if hasattr(desc, 'oneof_decl'):
682 for i, f in enumerate(desc.oneof_decl):
683 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
684 if oneof_options.no_unions:
685 no_unions.append(i) # No union, but add fields normally
686 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
687 pass # No union and skip fields also
689 oneof = OneOf(self.name, f)
690 self.oneofs[i] = oneof
691 self.fields.append(oneof)
694 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
695 if field_options.type == nanopb_pb2.FT_IGNORE:
698 field = Field(self.name, f, field_options)
699 if (hasattr(f, 'oneof_index') and
700 f.HasField('oneof_index') and
701 f.oneof_index not in no_unions):
702 if f.oneof_index in self.oneofs:
703 self.oneofs[f.oneof_index].add_field(field)
705 self.fields.append(field)
707 if len(desc.extension_range) > 0:
708 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
709 range_start = min([r.start for r in desc.extension_range])
710 if field_options.type != nanopb_pb2.FT_IGNORE:
711 self.fields.append(ExtensionRange(self.name, range_start, field_options))
713 self.packed = message_options.packed_struct
714 self.ordered_fields = self.fields[:]
715 self.ordered_fields.sort()
717 def get_dependencies(self):
718 '''Get list of type names that this structure refers to.'''
720 for f in self.fields:
721 deps += f.get_dependencies()
725 result = 'typedef struct _%s {\n' % self.name
727 if not self.ordered_fields:
728 # Empty structs are not allowed in C standard.
729 # Therefore add a dummy field if an empty message occurs.
730 result += ' uint8_t dummy_field;'
732 result += '\n'.join([str(f) for f in self.ordered_fields])
736 result += ' pb_packed'
738 result += ' %s;' % self.name
741 result = 'PB_PACKED_STRUCT_START\n' + result
742 result += '\nPB_PACKED_STRUCT_END'
747 return ''.join([f.types() for f in self.fields])
749 def get_initializer(self, null_init):
750 if not self.ordered_fields:
754 for field in self.ordered_fields:
755 parts.append(field.get_initializer(null_init))
756 return '{' + ', '.join(parts) + '}'
758 def default_decl(self, declaration_only = False):
760 for field in self.fields:
761 default = field.default_decl(declaration_only)
762 if default is not None:
763 result += default + '\n'
766 def count_required_fields(self):
767 '''Returns number of required fields inside this message'''
769 for f in self.fields:
770 if not isinstance(f, OneOf):
771 if f.rules == 'REQUIRED':
775 def count_all_fields(self):
777 for f in self.fields:
778 if isinstance(f, OneOf):
779 count += len(f.fields)
784 def fields_declaration(self):
785 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
788 def fields_definition(self):
789 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
792 for field in self.ordered_fields:
793 result += field.pb_field_t(prev)
795 if isinstance(field, OneOf):
796 prev = field.name + '.' + field.fields[-1].name
800 result += ' PB_LAST_FIELD\n};'
803 def encoded_size(self, allmsgs):
804 '''Return the maximum size that this message can take when encoded.
805 If the size cannot be determined, returns None.
807 size = EncodedSize(0)
808 for field in self.fields:
809 fsize = field.encoded_size(allmsgs)
817 # ---------------------------------------------------------------------------
818 # Processing of entire .proto files
819 # ---------------------------------------------------------------------------
822 def iterate_messages(desc, names = Names()):
823 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
824 if hasattr(desc, 'message_type'):
825 submsgs = desc.message_type
827 submsgs = desc.nested_type
829 for submsg in submsgs:
830 sub_names = names + submsg.name
831 yield sub_names, submsg
833 for x in iterate_messages(submsg, sub_names):
836 def iterate_extensions(desc, names = Names()):
837 '''Recursively find all extensions.
838 For each, yield name, FieldDescriptorProto.
840 for extension in desc.extension:
841 yield names, extension
843 for subname, subdesc in iterate_messages(desc, names):
844 for extension in subdesc.extension:
845 yield subname, extension
847 def parse_file(fdesc, file_options):
848 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
855 base_name = Names(fdesc.package.split('.'))
859 for enum in fdesc.enum_type:
860 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
861 enums.append(Enum(base_name, enum, enum_options))
863 for names, message in iterate_messages(fdesc, base_name):
864 message_options = get_nanopb_suboptions(message, file_options, names)
866 if message_options.skip_message:
869 messages.append(Message(names, message, message_options))
870 for enum in message.enum_type:
871 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
872 enums.append(Enum(names, enum, enum_options))
874 for names, extension in iterate_extensions(fdesc, base_name):
875 field_options = get_nanopb_suboptions(extension, file_options, names + extension.name)
876 if field_options.type != nanopb_pb2.FT_IGNORE:
877 extensions.append(ExtensionField(names, extension, field_options))
879 # Fix field default values where enum short names are used.
881 if not enum.options.long_names:
882 for message in messages:
883 for field in message.fields:
884 if field.default in enum.value_longnames:
885 idx = enum.value_longnames.index(field.default)
886 field.default = enum.values[idx][0]
888 return enums, messages, extensions
892 From http://code.activestate.com/recipes/577413-topological-sort/
893 This function is under the MIT license.
895 for k, v in data.items():
896 v.discard(k) # Ignore self dependencies
897 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
898 data.update(dict([(item, set()) for item in extra_items_in_deps]))
900 ordered = set(item for item,dep in data.items() if not dep)
903 for item in sorted(ordered):
905 data = dict([(item, (dep - ordered)) for item,dep in data.items()
906 if item not in ordered])
907 assert not data, "A cyclic dependency exists amongst %r" % data
909 def sort_dependencies(messages):
910 '''Sort a list of Messages based on dependencies.'''
913 for message in messages:
914 dependencies[str(message.name)] = set(message.get_dependencies())
915 message_by_name[str(message.name)] = message
917 for msgname in toposort2(dependencies):
918 if msgname in message_by_name:
919 yield message_by_name[msgname]
921 def make_identifier(headername):
922 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
924 for c in headername.upper():
931 def generate_header(dependencies, headername, enums, messages, extensions, options):
932 '''Generate content for a header file.
933 Generates strings, which should be concatenated and stored to file.
936 yield '/* Automatically generated nanopb header */\n'
937 if options.notimestamp:
938 yield '/* Generated by %s */\n\n' % (nanopb_version)
940 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
942 symbol = make_identifier(headername)
943 yield '#ifndef PB_%s_INCLUDED\n' % symbol
944 yield '#define PB_%s_INCLUDED\n' % symbol
946 yield options.libformat % ('pb.h')
948 # no %s specified - use whatever was passed in as options.libformat
949 yield options.libformat
952 for dependency in dependencies:
953 noext = os.path.splitext(dependency)[0]
954 yield options.genformat % (noext + options.extension + '.h')
957 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
958 yield '#error Regenerate this file with the current version of nanopb generator.\n'
962 yield '#ifdef __cplusplus\n'
963 yield 'extern "C" {\n'
966 yield '/* Enum definitions */\n'
968 yield str(enum) + '\n\n'
970 yield '/* Struct definitions */\n'
971 for msg in sort_dependencies(messages):
973 yield str(msg) + '\n\n'
976 yield '/* Extensions */\n'
977 for extension in extensions:
978 yield extension.extension_decl()
981 yield '/* Default values for struct fields */\n'
983 yield msg.default_decl(True)
986 yield '/* Initializer values for message structs */\n'
988 identifier = '%s_init_default' % msg.name
989 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
991 identifier = '%s_init_zero' % msg.name
992 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
995 yield '/* Field tags (for use in manual encoding/decoding) */\n'
996 for msg in sort_dependencies(messages):
997 for field in msg.fields:
999 for extension in extensions:
1000 yield extension.tags()
1003 yield '/* Struct field encoding specification for nanopb */\n'
1004 for msg in messages:
1005 yield msg.fields_declaration() + '\n'
1008 yield '/* Maximum encoded size of messages (where known) */\n'
1009 for msg in messages:
1010 msize = msg.encoded_size(messages)
1011 if msize is not None:
1012 identifier = '%s_size' % msg.name
1013 yield '#define %-40s %s\n' % (identifier, msize)
1016 yield '/* Message IDs (where set with "msgid" option) */\n'
1018 yield '#ifdef PB_MSGID\n'
1019 for msg in messages:
1020 if hasattr(msg,'msgid'):
1021 yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1024 symbol = make_identifier(headername.split('.')[0])
1025 yield '#define %s_MESSAGES \\\n' % symbol
1027 for msg in messages:
1029 msize = msg.encoded_size(messages)
1030 if msize is not None:
1032 if hasattr(msg,'msgid'):
1033 yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1036 for msg in messages:
1037 if hasattr(msg,'msgid'):
1038 yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1044 yield '#ifdef __cplusplus\n'
1045 yield '} /* extern "C" */\n'
1051 def generate_source(headername, enums, messages, extensions, options):
1052 '''Generate content for a source file.'''
1054 yield '/* Automatically generated nanopb constant definitions */\n'
1055 if options.notimestamp:
1056 yield '/* Generated by %s */\n\n' % (nanopb_version)
1058 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1059 yield options.genformat % (headername)
1062 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1063 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1067 for msg in messages:
1068 yield msg.default_decl(False)
1072 for msg in messages:
1073 yield msg.fields_definition() + '\n\n'
1075 for ext in extensions:
1076 yield ext.extension_def() + '\n'
1078 # Add checks for numeric limits
1080 largest_msg = max(messages, key = lambda m: m.count_required_fields())
1081 largest_count = largest_msg.count_required_fields()
1082 if largest_count > 64:
1083 yield '\n/* Check that missing required fields will be properly detected */\n'
1084 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1085 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1086 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1092 checks_msgnames = []
1093 for msg in messages:
1094 checks_msgnames.append(msg.name)
1095 for field in msg.fields:
1096 status = field.largest_field_value()
1097 if isinstance(status, (str, unicode)):
1098 checks.append(status)
1099 elif status > worst:
1101 worst_field = str(field.struct_name) + '.' + str(field.name)
1103 if worst > 255 or checks:
1104 yield '\n/* Check that field information fits in pb_field_t */\n'
1106 if worst > 65535 or checks:
1107 yield '#if !defined(PB_FIELD_32BIT)\n'
1109 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1111 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1112 msgs = '_'.join(str(n) for n in checks_msgnames)
1113 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1114 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1116 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1117 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1118 yield ' * field descriptors.\n'
1120 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1124 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1126 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1128 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1129 msgs = '_'.join(str(n) for n in checks_msgnames)
1130 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1131 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1133 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1134 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1135 yield ' * 8 bit descriptors.\n'
1137 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1140 # Add check for sizeof(double)
1142 for msg in messages:
1143 for field in msg.fields:
1144 if field.ctype == 'double':
1149 yield '/* On some platforms (such as AVR), double is really float.\n'
1150 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1151 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1153 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1157 # ---------------------------------------------------------------------------
1158 # Options parsing for the .proto files
1159 # ---------------------------------------------------------------------------
1161 from fnmatch import fnmatch
1163 def read_options_file(infile):
1164 '''Parse a separate options file to list:
1165 [(namemask, options), ...]
1168 data = infile.read()
1169 data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1170 data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1171 data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1172 for i, line in enumerate(data.split('\n')):
1177 parts = line.split(None, 1)
1180 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1181 "Option lines should have space between field name and options. " +
1182 "Skipping line: '%s'\n" % line)
1185 opts = nanopb_pb2.NanoPBOptions()
1188 text_format.Merge(parts[1], opts)
1189 except Exception, e:
1190 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1191 "Unparseable option line: '%s'. " % line +
1192 "Error: %s\n" % str(e))
1194 results.append((parts[0], opts))
1199 '''Ugly global variables, should find a good way to pass these.'''
1200 verbose_options = False
1201 separate_options = []
1202 matched_namemasks = set()
1204 def get_nanopb_suboptions(subdesc, options, name):
1205 '''Get copy of options, and merge information from subdesc.'''
1206 new_options = nanopb_pb2.NanoPBOptions()
1207 new_options.CopyFrom(options)
1209 # Handle options defined in a separate file
1210 dotname = '.'.join(name.parts)
1211 for namemask, options in Globals.separate_options:
1212 if fnmatch(dotname, namemask):
1213 Globals.matched_namemasks.add(namemask)
1214 new_options.MergeFrom(options)
1216 # Handle options defined in .proto
1217 if isinstance(subdesc.options, descriptor.FieldOptions):
1218 ext_type = nanopb_pb2.nanopb
1219 elif isinstance(subdesc.options, descriptor.FileOptions):
1220 ext_type = nanopb_pb2.nanopb_fileopt
1221 elif isinstance(subdesc.options, descriptor.MessageOptions):
1222 ext_type = nanopb_pb2.nanopb_msgopt
1223 elif isinstance(subdesc.options, descriptor.EnumOptions):
1224 ext_type = nanopb_pb2.nanopb_enumopt
1226 raise Exception("Unknown options type")
1228 if subdesc.options.HasExtension(ext_type):
1229 ext = subdesc.options.Extensions[ext_type]
1230 new_options.MergeFrom(ext)
1232 if Globals.verbose_options:
1233 sys.stderr.write("Options for " + dotname + ": ")
1234 sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1239 # ---------------------------------------------------------------------------
1240 # Command line interface
1241 # ---------------------------------------------------------------------------
1245 from optparse import OptionParser
1247 optparser = OptionParser(
1248 usage = "Usage: nanopb_generator.py [options] file.pb ...",
1249 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1250 "Output will be written to file.pb.h and file.pb.c.")
1251 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1252 help="Exclude file from generated #include list.")
1253 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1254 help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1255 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1256 help="Set name of a separate generator options file.")
1257 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1258 metavar="FORMAT", default='#include "%s"\n',
1259 help="Set format string to use for including other .pb.h files. [default: %default]")
1260 optparser.add_option("-L", "--library-include-format", dest="libformat",
1261 metavar="FORMAT", default='#include <%s>\n',
1262 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1263 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1264 help="Don't add timestamp to .pb.h and .pb.c preambles")
1265 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1266 help="Don't print anything except errors.")
1267 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1268 help="Print more information.")
1269 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1270 help="Set generator option (max_size, max_count etc.).")
1272 def process_file(filename, fdesc, options):
1273 '''Process a single file.
1274 filename: The full path to the .proto or .pb source file, as string.
1275 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1276 options: Command line options as they come from OptionsParser.
1279 {'headername': Name of header file,
1280 'headerdata': Data for the .h header file,
1281 'sourcename': Name of the source code file,
1282 'sourcedata': Data for the .c source code file
1285 toplevel_options = nanopb_pb2.NanoPBOptions()
1286 for s in options.settings:
1287 text_format.Merge(s, toplevel_options)
1290 data = open(filename, 'rb').read()
1291 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1293 # Check if there is a separate .options file
1296 optfilename = options.options_file % os.path.splitext(filename)[0]
1298 # No %s specified, use the filename as-is
1299 optfilename = options.options_file
1302 if os.path.isfile(optfilename):
1304 sys.stderr.write('Reading options from ' + optfilename + '\n')
1306 Globals.separate_options = read_options_file(open(optfilename, "rU"))
1308 # If we are given a full filename and it does not exist, give an error.
1309 # However, don't give error when we automatically look for .options file
1310 # with the same name as .proto.
1311 if options.verbose or had_abspath:
1312 sys.stderr.write('Options file not found: ' + optfilename)
1314 Globals.separate_options = []
1316 Globals.matched_namemasks = set()
1319 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1320 enums, messages, extensions = parse_file(fdesc, file_options)
1322 # Decide the file names
1323 noext = os.path.splitext(filename)[0]
1324 headername = noext + options.extension + '.h'
1325 sourcename = noext + options.extension + '.c'
1326 headerbasename = os.path.basename(headername)
1328 # List of .proto files that should not be included in the C header file
1329 # even if they are mentioned in the source .proto.
1330 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1331 dependencies = [d for d in fdesc.dependency if d not in excludes]
1333 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
1334 messages, extensions, options))
1336 sourcedata = ''.join(generate_source(headerbasename, enums,
1337 messages, extensions, options))
1339 # Check if there were any lines in .options that did not match a member
1340 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1341 if unmatched and not options.quiet:
1342 sys.stderr.write("Following patterns in " + optfilename + " did not match any fields: "
1343 + ', '.join(unmatched) + "\n")
1344 if not Globals.verbose_options:
1345 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n")
1347 return {'headername': headername, 'headerdata': headerdata,
1348 'sourcename': sourcename, 'sourcedata': sourcedata}
1351 '''Main function when invoked directly from the command line.'''
1353 options, filenames = optparser.parse_args()
1356 optparser.print_help()
1360 options.verbose = False
1362 Globals.verbose_options = options.verbose
1364 for filename in filenames:
1365 results = process_file(filename, None, options)
1367 if not options.quiet:
1368 sys.stderr.write("Writing to " + results['headername'] + " and "
1369 + results['sourcename'] + "\n")
1371 open(results['headername'], 'w').write(results['headerdata'])
1372 open(results['sourcename'], 'w').write(results['sourcedata'])
1375 '''Main function when invoked as a protoc plugin.'''
1378 if sys.platform == "win32":
1380 # Set stdin and stdout to binary mode
1381 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1382 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1384 data = sys.stdin.read()
1385 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1388 # Versions of Python prior to 2.7.3 do not support unicode
1389 # input to shlex.split(). Try to convert to str if possible.
1390 params = str(request.parameter)
1391 except UnicodeEncodeError:
1392 params = request.parameter
1395 args = shlex.split(params)
1396 options, dummy = optparser.parse_args(args)
1398 Globals.verbose_options = options.verbose
1400 response = plugin_pb2.CodeGeneratorResponse()
1402 for filename in request.file_to_generate:
1403 for fdesc in request.proto_file:
1404 if fdesc.name == filename:
1405 results = process_file(filename, fdesc, options)
1407 f = response.file.add()
1408 f.name = results['headername']
1409 f.content = results['headerdata']
1411 f = response.file.add()
1412 f.name = results['sourcename']
1413 f.content = results['sourcedata']
1415 sys.stdout.write(response.SerializeToString())
1417 if __name__ == '__main__':
1418 # Check if we are running as a plugin under protoc
1419 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: